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