ctdb-locking: Update ctdb statistics for all lock types
[samba.git] / ctdb / server / ctdb_lock.c
1 /*
2    ctdb lock handling
3    provide API to do non-blocking locks for single or all databases
4
5    Copyright (C) Amitay Isaacs  2012
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20 #include "includes.h"
21 #include "include/ctdb_private.h"
22 #include "include/ctdb_protocol.h"
23 #include "tevent.h"
24 #include "tdb.h"
25 #include "db_wrap.h"
26 #include "system/filesys.h"
27 #include "lib/util/dlinklist.h"
28
29 /*
30  * Non-blocking Locking API
31  *
32  * 1. Create a child process to do blocking locks.
33  * 2. Once the locks are obtained, signal parent process via fd.
34  * 3. Invoke registered callback routine with locking status.
35  * 4. If the child process cannot get locks within certain time,
36  *    diagnose using /proc/locks and log warning message
37  *
38  * ctdb_lock_record()      - get a lock on a record
39  * ctdb_lock_db()          - get a lock on a DB
40  * ctdb_lock_alldb_prio()  - get a lock on all DBs with given priority
41  * ctdb_lock_alldb()       - get a lock on all DBs
42  *
43  *  auto_mark              - whether to mark/unmark DBs in before/after callback
44  */
45
46 enum lock_type {
47         LOCK_RECORD,
48         LOCK_DB,
49         LOCK_ALLDB_PRIO,
50         LOCK_ALLDB,
51 };
52
53 static const char * const lock_type_str[] = {
54         "lock_record",
55         "lock_db",
56         "lock_alldb_prio",
57         "lock_alldb",
58 };
59
60 struct lock_request;
61
62 /* lock_context is the common part for a lock request */
63 struct lock_context {
64         struct lock_context *next, *prev;
65         enum lock_type type;
66         struct ctdb_context *ctdb;
67         struct ctdb_db_context *ctdb_db;
68         TDB_DATA key;
69         uint32_t priority;
70         bool auto_mark;
71         struct lock_request *request;
72         pid_t child;
73         int fd[2];
74         struct tevent_fd *tfd;
75         struct tevent_timer *ttimer;
76         struct timeval start_time;
77         uint32_t key_hash;
78         bool can_schedule;
79 };
80
81 /* lock_request is the client specific part for a lock request */
82 struct lock_request {
83         struct lock_context *lctx;
84         void (*callback)(void *, bool);
85         void *private_data;
86 };
87
88
89 /*
90  * Support samba 3.6.x (and older) versions which do not set db priority.
91  *
92  * By default, all databases are set to priority 1. So only when priority
93  * is set to 1, check for databases that need higher priority.
94  */
95 static bool later_db(struct ctdb_context *ctdb, const char *name)
96 {
97         if (ctdb->tunable.samba3_hack == 0) {
98                 return false;
99         }
100
101         if (strstr(name, "brlock") ||
102             strstr(name, "g_lock") ||
103             strstr(name, "notify_onelevel") ||
104             strstr(name, "serverid") ||
105             strstr(name, "xattr_tdb")) {
106                 return true;
107         }
108
109         return false;
110 }
111
112 typedef int (*db_handler_t)(struct ctdb_db_context *ctdb_db,
113                             uint32_t priority,
114                             void *private_data);
115
116 static int ctdb_db_iterator(struct ctdb_context *ctdb, uint32_t priority,
117                             db_handler_t handler, void *private_data)
118 {
119         struct ctdb_db_context *ctdb_db;
120         int ret;
121
122         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
123                 if (ctdb_db->priority != priority) {
124                         continue;
125                 }
126                 if (later_db(ctdb, ctdb_db->db_name)) {
127                         continue;
128                 }
129                 ret = handler(ctdb_db, priority, private_data);
130                 if (ret != 0) {
131                         return -1;
132                 }
133         }
134
135         /* If priority != 1, later_db check is not required and can return */
136         if (priority != 1) {
137                 return 0;
138         }
139
140         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
141                 if (!later_db(ctdb, ctdb_db->db_name)) {
142                         continue;
143                 }
144                 ret = handler(ctdb_db, priority, private_data);
145                 if (ret != 0) {
146                         return -1;
147                 }
148         }
149
150         return 0;
151 }
152
153
154 /*
155  * lock all databases - mark only
156  */
157 static int db_lock_mark_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
158                                 void *private_data)
159 {
160         int tdb_transaction_write_lock_mark(struct tdb_context *);
161
162         DEBUG(DEBUG_INFO, ("marking locked database %s, priority:%u\n",
163                            ctdb_db->db_name, priority));
164
165         if (tdb_transaction_write_lock_mark(ctdb_db->ltdb->tdb) != 0) {
166                 DEBUG(DEBUG_ERR, ("Failed to mark (transaction lock) database %s\n",
167                                   ctdb_db->db_name));
168                 return -1;
169         }
170
171         if (tdb_lockall_mark(ctdb_db->ltdb->tdb) != 0) {
172                 DEBUG(DEBUG_ERR, ("Failed to mark (all lock) database %s\n",
173                                   ctdb_db->db_name));
174                 return -1;
175         }
176
177         return 0;
178 }
179
180 int ctdb_lockall_mark_prio(struct ctdb_context *ctdb, uint32_t priority)
181 {
182         /*
183          * This function is only used by the main dameon during recovery.
184          * At this stage, the databases have already been locked, by a
185          * dedicated child process. The freeze_mode variable is used to track
186          * whether the actual locks are held by the child process or not.
187          */
188
189         if (ctdb->freeze_mode[priority] != CTDB_FREEZE_FROZEN) {
190                 DEBUG(DEBUG_ERR, ("Attempt to mark all databases locked when not frozen\n"));
191                 return -1;
192         }
193
194         return ctdb_db_iterator(ctdb, priority, db_lock_mark_handler, NULL);
195 }
196
197 static int ctdb_lockall_mark(struct ctdb_context *ctdb)
198 {
199         uint32_t priority;
200
201         for (priority=1; priority<=NUM_DB_PRIORITIES; priority++) {
202                 if (ctdb_db_iterator(ctdb, priority, db_lock_mark_handler, NULL) != 0) {
203                         return -1;
204                 }
205         }
206
207         return 0;
208 }
209
210
211 /*
212  * lock all databases - unmark only
213  */
214 static int db_lock_unmark_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
215                                   void *private_data)
216 {
217         int tdb_transaction_write_lock_unmark(struct tdb_context *);
218
219         DEBUG(DEBUG_INFO, ("unmarking locked database %s, priority:%u\n",
220                            ctdb_db->db_name, priority));
221
222         if (tdb_transaction_write_lock_unmark(ctdb_db->ltdb->tdb) != 0) {
223                 DEBUG(DEBUG_ERR, ("Failed to unmark (transaction lock) database %s\n",
224                                   ctdb_db->db_name));
225                 return -1;
226         }
227
228         if (tdb_lockall_unmark(ctdb_db->ltdb->tdb) != 0) {
229                 DEBUG(DEBUG_ERR, ("Failed to unmark (all lock) database %s\n",
230                                   ctdb_db->db_name));
231                 return -1;
232         }
233
234         return 0;
235 }
236
237 int ctdb_lockall_unmark_prio(struct ctdb_context *ctdb, uint32_t priority)
238 {
239         /*
240          * This function is only used by the main daemon during recovery.
241          * At this stage, the databases have already been locked, by a
242          * dedicated child process. The freeze_mode variable is used to track
243          * whether the actual locks are held by the child process or not.
244          */
245
246         if (ctdb->freeze_mode[priority] != CTDB_FREEZE_FROZEN) {
247                 DEBUG(DEBUG_ERR, ("Attempt to unmark all databases locked when not frozen\n"));
248                 return -1;
249         }
250
251         return ctdb_db_iterator(ctdb, priority, db_lock_unmark_handler, NULL);
252 }
253
254 static int ctdb_lockall_unmark(struct ctdb_context *ctdb)
255 {
256         uint32_t priority;
257
258         for (priority=NUM_DB_PRIORITIES; priority>0; priority--) {
259                 if (ctdb_db_iterator(ctdb, priority, db_lock_unmark_handler, NULL) != 0) {
260                         return -1;
261                 }
262         }
263
264         return 0;
265 }
266
267
268 static void ctdb_lock_schedule(struct ctdb_context *ctdb);
269
270 /*
271  * Destructor to kill the child locking process
272  */
273 static int ctdb_lock_context_destructor(struct lock_context *lock_ctx)
274 {
275         if (lock_ctx->child > 0) {
276                 ctdb_kill(lock_ctx->ctdb, lock_ctx->child, SIGKILL);
277                 DLIST_REMOVE(lock_ctx->ctdb->lock_current, lock_ctx);
278                 if (lock_ctx->ctdb_db) {
279                         lock_ctx->ctdb_db->lock_num_current--;
280                 }
281                 CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_current);
282                 if (lock_ctx->type == LOCK_RECORD || lock_ctx->type == LOCK_DB) {
283                         CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_current);
284                 }
285         } else {
286                 DLIST_REMOVE(lock_ctx->ctdb->lock_pending, lock_ctx);
287                 CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_pending);
288                 if (lock_ctx->type == LOCK_RECORD || lock_ctx->type == LOCK_DB) {
289                         CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_pending);
290                 }
291         }
292
293         ctdb_lock_schedule(lock_ctx->ctdb);
294
295         return 0;
296 }
297
298
299 /*
300  * Destructor to remove lock request
301  */
302 static int ctdb_lock_request_destructor(struct lock_request *lock_request)
303 {
304         lock_request->lctx->request = NULL;
305         return 0;
306 }
307
308 void ctdb_lock_free_request_context(struct lock_request *lock_req)
309 {
310         struct lock_context *lock_ctx;
311
312         lock_ctx = lock_req->lctx;
313         talloc_free(lock_req);
314         talloc_free(lock_ctx);
315 }
316
317
318 /*
319  * Process all the callbacks waiting for lock
320  *
321  * If lock has failed, callback is executed with locked=false
322  */
323 static void process_callbacks(struct lock_context *lock_ctx, bool locked)
324 {
325         struct lock_request *request;
326
327         if (lock_ctx->auto_mark && locked) {
328                 switch (lock_ctx->type) {
329                 case LOCK_RECORD:
330                         tdb_chainlock_mark(lock_ctx->ctdb_db->ltdb->tdb, lock_ctx->key);
331                         break;
332
333                 case LOCK_DB:
334                         tdb_lockall_mark(lock_ctx->ctdb_db->ltdb->tdb);
335                         break;
336
337                 case LOCK_ALLDB_PRIO:
338                         ctdb_lockall_mark_prio(lock_ctx->ctdb, lock_ctx->priority);
339                         break;
340
341                 case LOCK_ALLDB:
342                         ctdb_lockall_mark(lock_ctx->ctdb);
343                         break;
344                 }
345         }
346
347         request = lock_ctx->request;
348         if (lock_ctx->auto_mark) {
349                 /* Reset the destructor, so request is not removed from the list */
350                 talloc_set_destructor(request, NULL);
351         }
352         request->callback(request->private_data, locked);
353
354         if (lock_ctx->auto_mark && locked) {
355                 switch (lock_ctx->type) {
356                 case LOCK_RECORD:
357                         tdb_chainlock_unmark(lock_ctx->ctdb_db->ltdb->tdb, lock_ctx->key);
358                         break;
359
360                 case LOCK_DB:
361                         tdb_lockall_unmark(lock_ctx->ctdb_db->ltdb->tdb);
362                         break;
363
364                 case LOCK_ALLDB_PRIO:
365                         ctdb_lockall_unmark_prio(lock_ctx->ctdb, lock_ctx->priority);
366                         break;
367
368                 case LOCK_ALLDB:
369                         ctdb_lockall_unmark(lock_ctx->ctdb);
370                         break;
371                 }
372         }
373 }
374
375
376 static int lock_bucket_id(double t)
377 {
378         double ms = 1.e-3, s = 1;
379         int id;
380
381         if (t < 1*ms) {
382                 id = 0;
383         } else if (t < 10*ms) {
384                 id = 1;
385         } else if (t < 100*ms) {
386                 id = 2;
387         } else if (t < 1*s) {
388                 id = 3;
389         } else if (t < 2*s) {
390                 id = 4;
391         } else if (t < 4*s) {
392                 id = 5;
393         } else if (t < 8*s) {
394                 id = 6;
395         } else if (t < 16*s) {
396                 id = 7;
397         } else if (t < 32*s) {
398                 id = 8;
399         } else if (t < 64*s) {
400                 id = 9;
401         } else {
402                 id = 10;
403         }
404
405         return id;
406 }
407
408 /*
409  * Callback routine when the required locks are obtained.
410  * Called from parent context
411  */
412 static void ctdb_lock_handler(struct tevent_context *ev,
413                             struct tevent_fd *tfd,
414                             uint16_t flags,
415                             void *private_data)
416 {
417         struct lock_context *lock_ctx;
418         TALLOC_CTX *tmp_ctx = NULL;
419         char c;
420         bool locked;
421         double t;
422         int id;
423
424         lock_ctx = talloc_get_type_abort(private_data, struct lock_context);
425
426         /* cancel the timeout event */
427         if (lock_ctx->ttimer) {
428                 TALLOC_FREE(lock_ctx->ttimer);
429         }
430
431         t = timeval_elapsed(&lock_ctx->start_time);
432         id = lock_bucket_id(t);
433
434         if (lock_ctx->auto_mark) {
435                 tmp_ctx = talloc_new(ev);
436                 talloc_steal(tmp_ctx, lock_ctx);
437         }
438
439         /* Read the status from the child process */
440         if (read(lock_ctx->fd[0], &c, 1) != 1) {
441                 locked = false;
442         } else {
443                 locked = (c == 0 ? true : false);
444         }
445
446         /* Update statistics */
447         CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_pending);
448         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_calls);
449         if (lock_ctx->ctdb_db) {
450                 CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_pending);
451                 CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_calls);
452         }
453
454         if (locked) {
455                 if (lock_ctx->ctdb_db) {
456                         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.buckets[id]);
457                         CTDB_UPDATE_LATENCY(lock_ctx->ctdb, lock_ctx->ctdb_db,
458                                             lock_type_str[lock_ctx->type], locks.latency,
459                                             lock_ctx->start_time);
460
461                         CTDB_UPDATE_DB_LATENCY(lock_ctx->ctdb_db, lock_type_str[lock_ctx->type], locks.latency, t);
462                         CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.buckets[id]);
463                 }
464         } else {
465                 CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_failed);
466                 if (lock_ctx->ctdb_db) {
467                         CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_failed);
468                 }
469         }
470
471         process_callbacks(lock_ctx, locked);
472
473         if (lock_ctx->auto_mark) {
474                 talloc_free(tmp_ctx);
475         }
476 }
477
478
479 /*
480  * Callback routine when required locks are not obtained within timeout
481  * Called from parent context
482  */
483 static void ctdb_lock_timeout_handler(struct tevent_context *ev,
484                                     struct tevent_timer *ttimer,
485                                     struct timeval current_time,
486                                     void *private_data)
487 {
488         static const char * debug_locks = NULL;
489         struct lock_context *lock_ctx;
490         struct ctdb_context *ctdb;
491         pid_t pid;
492
493         lock_ctx = talloc_get_type_abort(private_data, struct lock_context);
494         ctdb = lock_ctx->ctdb;
495
496         if (lock_ctx->type == LOCK_RECORD || lock_ctx->type == LOCK_DB) {
497                 DEBUG(DEBUG_WARNING,
498                       ("Unable to get %s lock on database %s for %.0lf seconds\n",
499                        (lock_ctx->type == LOCK_RECORD ? "RECORD" : "DB"),
500                        lock_ctx->ctdb_db->db_name,
501                        timeval_elapsed(&lock_ctx->start_time)));
502         } else {
503                 DEBUG(DEBUG_WARNING,
504                       ("Unable to get ALLDB locks for %.0lf seconds\n",
505                        timeval_elapsed(&lock_ctx->start_time)));
506         }
507
508         /* Fire a child process to find the blocking process. */
509         if (debug_locks == NULL) {
510                 debug_locks = getenv("CTDB_DEBUG_LOCKS");
511                 if (debug_locks == NULL) {
512                         debug_locks = talloc_asprintf(ctdb,
513                                                       "%s/debug_locks.sh",
514                                                       getenv("CTDB_BASE"));
515                 }
516         }
517         if (debug_locks != NULL) {
518                 pid = vfork();
519                 if (pid == 0) {
520                         execl(debug_locks, debug_locks, NULL);
521                         _exit(0);
522                 }
523                 ctdb_track_child(ctdb, pid);
524         } else {
525                 DEBUG(DEBUG_WARNING,
526                       (__location__
527                        " Unable to setup lock debugging - no memory?\n"));
528         }
529
530         /* reset the timeout timer */
531         // talloc_free(lock_ctx->ttimer);
532         lock_ctx->ttimer = tevent_add_timer(ctdb->ev,
533                                             lock_ctx,
534                                             timeval_current_ofs(10, 0),
535                                             ctdb_lock_timeout_handler,
536                                             (void *)lock_ctx);
537 }
538
539
540 static int db_count_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
541                             void *private_data)
542 {
543         int *count = (int *)private_data;
544
545         (*count)++;
546
547         return 0;
548 }
549
550 struct db_namelist {
551         char **names;
552         int n;
553 };
554
555 static int db_name_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
556                            void *private_data)
557 {
558         struct db_namelist *list = (struct db_namelist *)private_data;
559
560         list->names[list->n] = talloc_strdup(list->names, ctdb_db->db_path);
561         list->n++;
562
563         return 0;
564 }
565
566 static char **lock_helper_args(TALLOC_CTX *mem_ctx, struct lock_context *lock_ctx, int fd)
567 {
568         struct ctdb_context *ctdb = lock_ctx->ctdb;
569         char **args = NULL;
570         int nargs, i;
571         int priority;
572         struct db_namelist list;
573
574         switch (lock_ctx->type) {
575         case LOCK_RECORD:
576                 nargs = 6;
577                 break;
578
579         case LOCK_DB:
580                 nargs = 5;
581                 break;
582
583         case LOCK_ALLDB_PRIO:
584                 nargs = 4;
585                 ctdb_db_iterator(ctdb, lock_ctx->priority, db_count_handler, &nargs);
586                 break;
587
588         case LOCK_ALLDB:
589                 nargs = 4;
590                 for (priority=1; priority<NUM_DB_PRIORITIES; priority++) {
591                         ctdb_db_iterator(ctdb, priority, db_count_handler, &nargs);
592                 }
593                 break;
594         }
595
596         /* Add extra argument for null termination */
597         nargs++;
598
599         args = talloc_array(mem_ctx, char *, nargs);
600         if (args == NULL) {
601                 return NULL;
602         }
603
604         args[0] = talloc_strdup(args, "ctdb_lock_helper");
605         args[1] = talloc_asprintf(args, "%d", getpid());
606         args[2] = talloc_asprintf(args, "%d", fd);
607
608         switch (lock_ctx->type) {
609         case LOCK_RECORD:
610                 args[3] = talloc_strdup(args, "RECORD");
611                 args[4] = talloc_strdup(args, lock_ctx->ctdb_db->db_path);
612                 if (lock_ctx->key.dsize == 0) {
613                         args[5] = talloc_strdup(args, "NULL");
614                 } else {
615                         args[5] = hex_encode_talloc(args, lock_ctx->key.dptr, lock_ctx->key.dsize);
616                 }
617                 break;
618
619         case LOCK_DB:
620                 args[3] = talloc_strdup(args, "DB");
621                 args[4] = talloc_strdup(args, lock_ctx->ctdb_db->db_path);
622                 break;
623
624         case LOCK_ALLDB_PRIO:
625                 args[3] = talloc_strdup(args, "DB");
626                 list.names = args;
627                 list.n = 4;
628                 ctdb_db_iterator(ctdb, lock_ctx->priority, db_name_handler, &list);
629                 break;
630
631         case LOCK_ALLDB:
632                 args[3] = talloc_strdup(args, "DB");
633                 list.names = args;
634                 list.n = 4;
635                 for (priority=1; priority<NUM_DB_PRIORITIES; priority++) {
636                         ctdb_db_iterator(ctdb, priority, db_name_handler, &list);
637                 }
638                 break;
639         }
640
641         /* Make sure last argument is NULL */
642         args[nargs-1] = NULL;
643
644         for (i=0; i<nargs-1; i++) {
645                 if (args[i] == NULL) {
646                         talloc_free(args);
647                         return NULL;
648                 }
649         }
650
651         return args;
652 }
653
654
655 /*
656  * Schedule a new lock child process
657  * Set up callback handler and timeout handler
658  */
659 static void ctdb_lock_schedule(struct ctdb_context *ctdb)
660 {
661         struct lock_context *lock_ctx, *next_ctx;
662         int ret;
663         TALLOC_CTX *tmp_ctx;
664         const char *helper = BINDIR "/ctdb_lock_helper";
665         static const char *prog = NULL;
666         char **args;
667
668         if (prog == NULL) {
669                 const char *t;
670
671                 t = getenv("CTDB_LOCK_HELPER");
672                 if (t != NULL) {
673                         prog = talloc_strdup(ctdb, t);
674                 } else {
675                         prog = talloc_strdup(ctdb, helper);
676                 }
677                 CTDB_NO_MEMORY_VOID(ctdb, prog);
678         }
679
680         if (ctdb->lock_pending == NULL) {
681                 return;
682         }
683
684         /* Find a lock context with requests */
685         lock_ctx = ctdb->lock_pending;
686         while (lock_ctx != NULL) {
687                 next_ctx = lock_ctx->next;
688                 if (! lock_ctx->request) {
689                         DEBUG(DEBUG_INFO, ("Removing lock context without lock request\n"));
690                         DLIST_REMOVE(ctdb->lock_pending, lock_ctx);
691                         CTDB_DECREMENT_STAT(ctdb, locks.num_pending);
692                         if (lock_ctx->ctdb_db) {
693                                 CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_pending);
694                         }
695                         talloc_free(lock_ctx);
696                 } else {
697                         if (lock_ctx->ctdb_db == NULL ||
698                             lock_ctx->ctdb_db->lock_num_current < ctdb->tunable.lock_processes_per_db) {
699                                 /* Found a lock context with lock requests */
700                                 break;
701                         }
702                 }
703                 lock_ctx = next_ctx;
704         }
705
706         if (lock_ctx == NULL) {
707                 return;
708         }
709
710         lock_ctx->child = -1;
711         ret = pipe(lock_ctx->fd);
712         if (ret != 0) {
713                 DEBUG(DEBUG_ERR, ("Failed to create pipe in ctdb_lock_schedule\n"));
714                 return;
715         }
716
717         set_close_on_exec(lock_ctx->fd[0]);
718
719         /* Create data for child process */
720         tmp_ctx = talloc_new(lock_ctx);
721         if (tmp_ctx == NULL) {
722                 DEBUG(DEBUG_ERR, ("Failed to allocate memory for helper args\n"));
723                 close(lock_ctx->fd[0]);
724                 close(lock_ctx->fd[1]);
725                 return;
726         }
727
728         /* Create arguments for lock helper */
729         args = lock_helper_args(tmp_ctx, lock_ctx, lock_ctx->fd[1]);
730         if (args == NULL) {
731                 DEBUG(DEBUG_ERR, ("Failed to create lock helper args\n"));
732                 close(lock_ctx->fd[0]);
733                 close(lock_ctx->fd[1]);
734                 talloc_free(tmp_ctx);
735                 return;
736         }
737
738         lock_ctx->child = vfork();
739
740         if (lock_ctx->child == (pid_t)-1) {
741                 DEBUG(DEBUG_ERR, ("Failed to create a child in ctdb_lock_schedule\n"));
742                 close(lock_ctx->fd[0]);
743                 close(lock_ctx->fd[1]);
744                 talloc_free(tmp_ctx);
745                 return;
746         }
747
748
749         /* Child process */
750         if (lock_ctx->child == 0) {
751                 ret = execv(prog, args);
752                 if (ret < 0) {
753                         DEBUG(DEBUG_ERR, ("Failed to execute helper %s (%d, %s)\n",
754                                           prog, errno, strerror(errno)));
755                 }
756                 _exit(1);
757         }
758
759         /* Parent process */
760         ctdb_track_child(ctdb, lock_ctx->child);
761         close(lock_ctx->fd[1]);
762
763         talloc_set_destructor(lock_ctx, ctdb_lock_context_destructor);
764
765         talloc_free(tmp_ctx);
766
767         /* Set up timeout handler */
768         lock_ctx->ttimer = tevent_add_timer(ctdb->ev,
769                                             lock_ctx,
770                                             timeval_current_ofs(10, 0),
771                                             ctdb_lock_timeout_handler,
772                                             (void *)lock_ctx);
773         if (lock_ctx->ttimer == NULL) {
774                 ctdb_kill(ctdb, lock_ctx->child, SIGKILL);
775                 lock_ctx->child = -1;
776                 talloc_set_destructor(lock_ctx, NULL);
777                 close(lock_ctx->fd[0]);
778                 return;
779         }
780
781         /* Set up callback */
782         lock_ctx->tfd = tevent_add_fd(ctdb->ev,
783                                       lock_ctx,
784                                       lock_ctx->fd[0],
785                                       EVENT_FD_READ,
786                                       ctdb_lock_handler,
787                                       (void *)lock_ctx);
788         if (lock_ctx->tfd == NULL) {
789                 TALLOC_FREE(lock_ctx->ttimer);
790                 ctdb_kill(ctdb, lock_ctx->child, SIGKILL);
791                 lock_ctx->child = -1;
792                 talloc_set_destructor(lock_ctx, NULL);
793                 close(lock_ctx->fd[0]);
794                 return;
795         }
796         tevent_fd_set_auto_close(lock_ctx->tfd);
797
798         /* Move the context from pending to current */
799         DLIST_REMOVE(ctdb->lock_pending, lock_ctx);
800         DLIST_ADD_END(ctdb->lock_current, lock_ctx, NULL);
801         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_current);
802         if (lock_ctx->ctdb_db) {
803                 lock_ctx->ctdb_db->lock_num_current++;
804                 CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_current);
805         }
806 }
807
808
809 /*
810  * Lock record / db depending on type
811  */
812 static struct lock_request *ctdb_lock_internal(struct ctdb_context *ctdb,
813                                                struct ctdb_db_context *ctdb_db,
814                                                TDB_DATA key,
815                                                uint32_t priority,
816                                                void (*callback)(void *, bool),
817                                                void *private_data,
818                                                enum lock_type type,
819                                                bool auto_mark)
820 {
821         struct lock_context *lock_ctx = NULL;
822         struct lock_request *request;
823
824         if (callback == NULL) {
825                 DEBUG(DEBUG_WARNING, ("No callback function specified, not locking\n"));
826                 return NULL;
827         }
828
829         lock_ctx = talloc_zero(ctdb, struct lock_context);
830         if (lock_ctx == NULL) {
831                 DEBUG(DEBUG_ERR, ("Failed to create a new lock context\n"));
832                 return NULL;
833         }
834
835         if ((request = talloc_zero(lock_ctx, struct lock_request)) == NULL) {
836                 talloc_free(lock_ctx);
837                 return NULL;
838         }
839
840         lock_ctx->type = type;
841         lock_ctx->ctdb = ctdb;
842         lock_ctx->ctdb_db = ctdb_db;
843         lock_ctx->key.dsize = key.dsize;
844         if (key.dsize > 0) {
845                 lock_ctx->key.dptr = talloc_memdup(lock_ctx, key.dptr, key.dsize);
846                 if (lock_ctx->key.dptr == NULL) {
847                         DEBUG(DEBUG_ERR, (__location__ "Memory allocation error\n"));
848                         talloc_free(lock_ctx);
849                         return NULL;
850                 }
851                 lock_ctx->key_hash = ctdb_hash(&key);
852         } else {
853                 lock_ctx->key.dptr = NULL;
854         }
855         lock_ctx->priority = priority;
856         lock_ctx->auto_mark = auto_mark;
857
858         lock_ctx->request = request;
859         lock_ctx->child = -1;
860
861         /* Non-record locks are required by recovery and should be scheduled
862          * immediately, so keep them at the head of the pending queue.
863          */
864         if (lock_ctx->type == LOCK_RECORD) {
865                 DLIST_ADD_END(ctdb->lock_pending, lock_ctx, NULL);
866         } else {
867                 DLIST_ADD(ctdb->lock_pending, lock_ctx);
868         }
869         CTDB_INCREMENT_STAT(ctdb, locks.num_pending);
870         if (ctdb_db) {
871                 CTDB_INCREMENT_DB_STAT(ctdb_db, locks.num_pending);
872         }
873
874         /* Start the timer when we activate the context */
875         lock_ctx->start_time = timeval_current();
876
877         request->lctx = lock_ctx;
878         request->callback = callback;
879         request->private_data = private_data;
880
881         talloc_set_destructor(request, ctdb_lock_request_destructor);
882
883         ctdb_lock_schedule(ctdb);
884
885         return request;
886 }
887
888
889 /*
890  * obtain a lock on a record in a database
891  */
892 struct lock_request *ctdb_lock_record(struct ctdb_db_context *ctdb_db,
893                                       TDB_DATA key,
894                                       bool auto_mark,
895                                       void (*callback)(void *, bool),
896                                       void *private_data)
897 {
898         return ctdb_lock_internal(ctdb_db->ctdb,
899                                   ctdb_db,
900                                   key,
901                                   0,
902                                   callback,
903                                   private_data,
904                                   LOCK_RECORD,
905                                   auto_mark);
906 }
907
908
909 /*
910  * obtain a lock on a database
911  */
912 struct lock_request *ctdb_lock_db(struct ctdb_db_context *ctdb_db,
913                                   bool auto_mark,
914                                   void (*callback)(void *, bool),
915                                   void *private_data)
916 {
917         return ctdb_lock_internal(ctdb_db->ctdb,
918                                   ctdb_db,
919                                   tdb_null,
920                                   0,
921                                   callback,
922                                   private_data,
923                                   LOCK_DB,
924                                   auto_mark);
925 }
926
927
928 /*
929  * obtain locks on all databases of specified priority
930  */
931 struct lock_request *ctdb_lock_alldb_prio(struct ctdb_context *ctdb,
932                                           uint32_t priority,
933                                           bool auto_mark,
934                                           void (*callback)(void *, bool),
935                                           void *private_data)
936 {
937         if (priority < 1 || priority > NUM_DB_PRIORITIES) {
938                 DEBUG(DEBUG_ERR, ("Invalid db priority: %u\n", priority));
939                 return NULL;
940         }
941
942         return ctdb_lock_internal(ctdb,
943                                   NULL,
944                                   tdb_null,
945                                   priority,
946                                   callback,
947                                   private_data,
948                                   LOCK_ALLDB_PRIO,
949                                   auto_mark);
950 }
951
952
953 /*
954  * obtain locks on all databases
955  */
956 struct lock_request *ctdb_lock_alldb(struct ctdb_context *ctdb,
957                                      bool auto_mark,
958                                      void (*callback)(void *, bool),
959                                      void *private_data)
960 {
961         return ctdb_lock_internal(ctdb,
962                                   NULL,
963                                   tdb_null,
964                                   0,
965                                   callback,
966                                   private_data,
967                                   LOCK_ALLDB,
968                                   auto_mark);
969 }
970