Change to using TDB_INCOMPATIBLE_HASH (the jenkins hash) on all
[metze/samba/wip.git] / source3 / lib / g_lock.c
1 /*
2    Unix SMB/CIFS implementation.
3    global locks based on dbwrap and messaging
4    Copyright (C) 2009 by Volker Lendecke
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "g_lock.h"
22 #include "librpc/gen_ndr/messaging.h"
23 #include "ctdbd_conn.h"
24
25 static NTSTATUS g_lock_force_unlock(struct g_lock_ctx *ctx, const char *name,
26                                     struct server_id pid);
27
28 struct g_lock_ctx {
29         struct db_context *db;
30         struct messaging_context *msg;
31 };
32
33 /*
34  * The "g_lock.tdb" file contains records, indexed by the 0-terminated
35  * lockname. The record contains an array of "struct g_lock_rec"
36  * structures. Waiters have the lock_type with G_LOCK_PENDING or'ed.
37  */
38
39 struct g_lock_rec {
40         enum g_lock_type lock_type;
41         struct server_id pid;
42 };
43
44 struct g_lock_ctx *g_lock_ctx_init(TALLOC_CTX *mem_ctx,
45                                    struct messaging_context *msg)
46 {
47         struct g_lock_ctx *result;
48
49         result = talloc(mem_ctx, struct g_lock_ctx);
50         if (result == NULL) {
51                 return NULL;
52         }
53         result->msg = msg;
54
55         result->db = db_open(result, lock_path("g_lock.tdb"), 0,
56                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDWR|O_CREAT, 0700);
57         if (result->db == NULL) {
58                 DEBUG(1, ("g_lock_init: Could not open g_lock.tdb"));
59                 TALLOC_FREE(result);
60                 return NULL;
61         }
62         return result;
63 }
64
65 static bool g_lock_conflicts(enum g_lock_type lock_type,
66                              const struct g_lock_rec *rec)
67 {
68         enum g_lock_type rec_lock = rec->lock_type;
69
70         if ((rec_lock & G_LOCK_PENDING) != 0) {
71                 return false;
72         }
73
74         /*
75          * Only tested write locks so far. Very likely this routine
76          * needs to be fixed for read locks....
77          */
78         if ((lock_type == G_LOCK_READ) && (rec_lock == G_LOCK_READ)) {
79                 return false;
80         }
81         return true;
82 }
83
84 static bool g_lock_parse(TALLOC_CTX *mem_ctx, TDB_DATA data,
85                          int *pnum_locks, struct g_lock_rec **plocks)
86 {
87         int i, num_locks;
88         struct g_lock_rec *locks;
89
90         if ((data.dsize % sizeof(struct g_lock_rec)) != 0) {
91                 DEBUG(1, ("invalid lock record length %d\n", (int)data.dsize));
92                 return false;
93         }
94
95         num_locks = data.dsize / sizeof(struct g_lock_rec);
96         locks = talloc_array(mem_ctx, struct g_lock_rec, num_locks);
97         if (locks == NULL) {
98                 DEBUG(1, ("talloc failed\n"));
99                 return false;
100         }
101
102         memcpy(locks, data.dptr, data.dsize);
103
104         DEBUG(10, ("locks:\n"));
105         for (i=0; i<num_locks; i++) {
106                 DEBUGADD(10, ("%s: %s %s\n",
107                               procid_str(talloc_tos(), &locks[i].pid),
108                               ((locks[i].lock_type & 1) == G_LOCK_READ) ?
109                               "read" : "write",
110                               (locks[i].lock_type & G_LOCK_PENDING) ?
111                               "(pending)" : "(owner)"));
112
113                 if (((locks[i].lock_type & G_LOCK_PENDING) == 0)
114                     && !process_exists(locks[i].pid)) {
115
116                         DEBUGADD(10, ("lock owner %s died -- discarding\n",
117                                       procid_str(talloc_tos(),
118                                                  &locks[i].pid)));
119
120                         if (i < (num_locks-1)) {
121                                 locks[i] = locks[num_locks-1];
122                         }
123                         num_locks -= 1;
124                 }
125         }
126
127         *plocks = locks;
128         *pnum_locks = num_locks;
129         return true;
130 }
131
132 static void g_lock_cleanup(int *pnum_locks, struct g_lock_rec *locks)
133 {
134         int i, num_locks;
135
136         num_locks = *pnum_locks;
137
138         DEBUG(10, ("g_lock_cleanup: %d locks\n", num_locks));
139
140         for (i=0; i<num_locks; i++) {
141                 if (process_exists(locks[i].pid)) {
142                         continue;
143                 }
144                 DEBUGADD(10, ("%s does not exist -- discarding\n",
145                               procid_str(talloc_tos(), &locks[i].pid)));
146
147                 if (i < (num_locks-1)) {
148                         locks[i] = locks[num_locks-1];
149                 }
150                 num_locks -= 1;
151         }
152         *pnum_locks = num_locks;
153         return;
154 }
155
156 static struct g_lock_rec *g_lock_addrec(TALLOC_CTX *mem_ctx,
157                                         struct g_lock_rec *locks,
158                                         int *pnum_locks,
159                                         const struct server_id pid,
160                                         enum g_lock_type lock_type)
161 {
162         struct g_lock_rec *result;
163         int num_locks = *pnum_locks;
164
165         result = talloc_realloc(mem_ctx, locks, struct g_lock_rec,
166                                 num_locks+1);
167         if (result == NULL) {
168                 return NULL;
169         }
170
171         result[num_locks].pid = pid;
172         result[num_locks].lock_type = lock_type;
173         *pnum_locks += 1;
174         return result;
175 }
176
177 static void g_lock_got_retry(struct messaging_context *msg,
178                              void *private_data,
179                              uint32_t msg_type,
180                              struct server_id server_id,
181                              DATA_BLOB *data);
182
183 static NTSTATUS g_lock_trylock(struct g_lock_ctx *ctx, const char *name,
184                                enum g_lock_type lock_type)
185 {
186         struct db_record *rec = NULL;
187         struct g_lock_rec *locks = NULL;
188         int i, num_locks;
189         struct server_id self;
190         int our_index;
191         TDB_DATA data;
192         NTSTATUS status = NT_STATUS_OK;
193         NTSTATUS store_status;
194
195 again:
196         rec = ctx->db->fetch_locked(ctx->db, talloc_tos(),
197                                     string_term_tdb_data(name));
198         if (rec == NULL) {
199                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
200                 status = NT_STATUS_LOCK_NOT_GRANTED;
201                 goto done;
202         }
203
204         if (!g_lock_parse(talloc_tos(), rec->value, &num_locks, &locks)) {
205                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
206                 status = NT_STATUS_INTERNAL_ERROR;
207                 goto done;
208         }
209
210         self = messaging_server_id(ctx->msg);
211         our_index = -1;
212
213         for (i=0; i<num_locks; i++) {
214                 if (procid_equal(&self, &locks[i].pid)) {
215                         if (our_index != -1) {
216                                 DEBUG(1, ("g_lock_trylock: Added ourself "
217                                           "twice!\n"));
218                                 status = NT_STATUS_INTERNAL_ERROR;
219                                 goto done;
220                         }
221                         if ((locks[i].lock_type & G_LOCK_PENDING) == 0) {
222                                 DEBUG(1, ("g_lock_trylock: Found ourself not "
223                                           "pending!\n"));
224                                 status = NT_STATUS_INTERNAL_ERROR;
225                                 goto done;
226                         }
227
228                         our_index = i;
229
230                         /* never conflict with ourself */
231                         continue;
232                 }
233                 if (g_lock_conflicts(lock_type, &locks[i])) {
234                         struct server_id pid = locks[i].pid;
235
236                         if (!process_exists(pid)) {
237                                 TALLOC_FREE(locks);
238                                 TALLOC_FREE(rec);
239                                 status = g_lock_force_unlock(ctx, name, pid);
240                                 if (!NT_STATUS_IS_OK(status)) {
241                                         DEBUG(1, ("Could not unlock dead lock "
242                                                   "holder!\n"));
243                                         goto done;
244                                 }
245                                 goto again;
246                         }
247                         lock_type |= G_LOCK_PENDING;
248                 }
249         }
250
251         if (our_index == -1) {
252                 /* First round, add ourself */
253
254                 locks = g_lock_addrec(talloc_tos(), locks, &num_locks,
255                                       self, lock_type);
256                 if (locks == NULL) {
257                         DEBUG(10, ("g_lock_addrec failed\n"));
258                         status = NT_STATUS_NO_MEMORY;
259                         goto done;
260                 }
261         } else {
262                 /*
263                  * Retry. We were pending last time. Overwrite the
264                  * stored lock_type with what we calculated, we might
265                  * have acquired the lock this time.
266                  */
267                 locks[our_index].lock_type = lock_type;
268         }
269
270         if (NT_STATUS_IS_OK(status) && ((lock_type & G_LOCK_PENDING) == 0)) {
271                 /*
272                  * Walk through the list of locks, search for dead entries
273                  */
274                 g_lock_cleanup(&num_locks, locks);
275         }
276
277         data = make_tdb_data((uint8_t *)locks, num_locks * sizeof(*locks));
278         store_status = rec->store(rec, data, 0);
279         if (!NT_STATUS_IS_OK(store_status)) {
280                 DEBUG(1, ("rec->store failed: %s\n",
281                           nt_errstr(store_status)));
282                 status = store_status;
283         }
284
285 done:
286         TALLOC_FREE(locks);
287         TALLOC_FREE(rec);
288
289         if (NT_STATUS_IS_OK(status) && (lock_type & G_LOCK_PENDING) != 0) {
290                 return STATUS_PENDING;
291         }
292
293         return NT_STATUS_OK;
294 }
295
296 NTSTATUS g_lock_lock(struct g_lock_ctx *ctx, const char *name,
297                      enum g_lock_type lock_type, struct timeval timeout)
298 {
299         struct tevent_timer *te = NULL;
300         NTSTATUS status;
301         bool retry = false;
302         struct timeval timeout_end;
303         struct timeval time_now;
304
305         DEBUG(10, ("Trying to acquire lock %d for %s\n", (int)lock_type,
306                    name));
307
308         if (lock_type & ~1) {
309                 DEBUG(1, ("Got invalid lock type %d for %s\n",
310                           (int)lock_type, name));
311                 return NT_STATUS_INVALID_PARAMETER;
312         }
313
314 #ifdef CLUSTER_SUPPORT
315         if (lp_clustering()) {
316                 status = ctdb_watch_us(messaging_ctdbd_connection());
317                 if (!NT_STATUS_IS_OK(status)) {
318                         DEBUG(10, ("could not register retry with ctdb: %s\n",
319                                    nt_errstr(status)));
320                         goto done;
321                 }
322         }
323 #endif
324
325         status = messaging_register(ctx->msg, &retry, MSG_DBWRAP_G_LOCK_RETRY,
326                                     g_lock_got_retry);
327         if (!NT_STATUS_IS_OK(status)) {
328                 DEBUG(10, ("messaging_register failed: %s\n",
329                            nt_errstr(status)));
330                 return status;
331         }
332
333         time_now = timeval_current();
334         timeout_end = timeval_sum(&time_now, &timeout);
335
336         while (true) {
337 #ifdef CLUSTER_SUPPORT
338                 fd_set _r_fds;
339 #endif
340                 fd_set *r_fds = NULL;
341                 int max_fd = 0;
342                 int ret;
343                 struct timeval timeout_remaining, select_timeout;
344
345                 status = g_lock_trylock(ctx, name, lock_type);
346                 if (NT_STATUS_IS_OK(status)) {
347                         DEBUG(10, ("Got lock %s\n", name));
348                         break;
349                 }
350                 if (!NT_STATUS_EQUAL(status, STATUS_PENDING)) {
351                         DEBUG(10, ("g_lock_trylock failed: %s\n",
352                                    nt_errstr(status)));
353                         break;
354                 }
355
356                 DEBUG(10, ("g_lock_trylock: Did not get lock, waiting...\n"));
357
358                 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
359                  *             !!! HACK ALERT --- FIX ME !!!
360                  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361                  * What we really want to do here is to react to
362                  * MSG_DBWRAP_G_LOCK_RETRY messages that are either sent
363                  * by a client doing g_lock_unlock or by ourselves when
364                  * we receive a CTDB_SRVID_SAMBA_NOTIFY or
365                  * CTDB_SRVID_RECONFIGURE message from ctdbd, i.e. when
366                  * either a client holding a lock or a complete node
367                  * has died.
368                  *
369                  * Doing this properly involves calling tevent_loop_once(),
370                  * but doing this here with the main ctdbd messaging context
371                  * creates a nested event loop when g_lock_lock() is called
372                  * from the main event loop, e.g. in a tcon_and_X where the
373                  * share_info.tdb needs to be initialized and is locked by
374                  * another process, or when the remore registry is accessed
375                  * for writing and some other process already holds a lock
376                  * on the registry.tdb.
377                  *
378                  * So as a quick fix, we act a little coarsely here: we do
379                  * a select on the ctdb connection fd and when it is readable
380                  * or we get EINTR, then we retry without actually parsing
381                  * any ctdb packages or dispatching messages. This means that
382                  * we retry more often than intended by design, but this does
383                  * not harm and it is unobtrusive. When we have finished,
384                  * the main loop will pick up all the messages and ctdb
385                  * packets. The only extra twist is that we cannot use timed
386                  * events here but have to handcode a timeout.
387                  */
388
389 #ifdef CLUSTER_SUPPORT
390                 if (lp_clustering()) {
391                         struct ctdbd_connection *conn;
392                         conn = messaging_ctdbd_connection();
393
394                         r_fds = &_r_fds;
395                         FD_ZERO(r_fds);
396                         max_fd = ctdbd_conn_get_fd(conn);
397                         FD_SET(max_fd, r_fds);
398                 }
399 #endif
400
401                 time_now = timeval_current();
402                 timeout_remaining = timeval_until(&time_now, &timeout_end);
403                 select_timeout = timeval_set(60, 0);
404
405                 select_timeout = timeval_min(&select_timeout,
406                                              &timeout_remaining);
407
408                 ret = sys_select(max_fd + 1, r_fds, NULL, NULL,
409                                  &select_timeout);
410                 if (ret == -1) {
411                         if (errno != EINTR) {
412                                 DEBUG(1, ("error calling select: %s\n",
413                                           strerror(errno)));
414                                 status = NT_STATUS_INTERNAL_ERROR;
415                                 break;
416                         }
417                         /*
418                          * errno == EINTR:
419                          * This means a signal was received.
420                          * It might have been a MSG_DBWRAP_G_LOCK_RETRY message.
421                          * ==> retry
422                          */
423                 } else if (ret == 0) {
424                         if (timeval_expired(&timeout_end)) {
425                                 DEBUG(10, ("g_lock_lock timed out\n"));
426                                 status = NT_STATUS_LOCK_NOT_GRANTED;
427                                 break;
428                         } else {
429                                 DEBUG(10, ("select returned 0 but timeout not "
430                                            "not expired, retrying\n"));
431                         }
432                 } else if (ret != 1) {
433                         DEBUG(1, ("invalid return code of select: %d\n", ret));
434                         status = NT_STATUS_INTERNAL_ERROR;
435                         break;
436                 }
437                 /*
438                  * ret == 1:
439                  * This means ctdbd has sent us some data.
440                  * Might be a CTDB_SRVID_RECONFIGURE or a
441                  * CTDB_SRVID_SAMBA_NOTIFY message.
442                  * ==> retry
443                  */
444         }
445
446 #ifdef CLUSTER_SUPPORT
447 done:
448 #endif
449
450         if (!NT_STATUS_IS_OK(status)) {
451                 NTSTATUS unlock_status;
452
453                 unlock_status = g_lock_unlock(ctx, name);
454
455                 if (!NT_STATUS_IS_OK(unlock_status)) {
456                         DEBUG(1, ("Could not remove ourself from the locking "
457                                   "db: %s\n", nt_errstr(status)));
458                 }
459         }
460
461         messaging_deregister(ctx->msg, MSG_DBWRAP_G_LOCK_RETRY, &retry);
462         TALLOC_FREE(te);
463
464         return status;
465 }
466
467 static void g_lock_got_retry(struct messaging_context *msg,
468                              void *private_data,
469                              uint32_t msg_type,
470                              struct server_id server_id,
471                              DATA_BLOB *data)
472 {
473         bool *pretry = (bool *)private_data;
474
475         DEBUG(10, ("Got retry message from pid %s\n",
476                    procid_str(talloc_tos(), &server_id)));
477
478         *pretry = true;
479 }
480
481 static NTSTATUS g_lock_force_unlock(struct g_lock_ctx *ctx, const char *name,
482                                     struct server_id pid)
483 {
484         struct db_record *rec = NULL;
485         struct g_lock_rec *locks = NULL;
486         int i, num_locks;
487         enum g_lock_type lock_type;
488         NTSTATUS status;
489
490         rec = ctx->db->fetch_locked(ctx->db, talloc_tos(),
491                                     string_term_tdb_data(name));
492         if (rec == NULL) {
493                 DEBUG(10, ("fetch_locked(\"%s\") failed\n", name));
494                 status = NT_STATUS_INTERNAL_ERROR;
495                 goto done;
496         }
497
498         if (!g_lock_parse(talloc_tos(), rec->value, &num_locks, &locks)) {
499                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
500                 status = NT_STATUS_INTERNAL_ERROR;
501                 goto done;
502         }
503
504         for (i=0; i<num_locks; i++) {
505                 if (procid_equal(&pid, &locks[i].pid)) {
506                         break;
507                 }
508         }
509
510         if (i == num_locks) {
511                 DEBUG(10, ("g_lock_force_unlock: Lock not found\n"));
512                 status = NT_STATUS_INTERNAL_ERROR;
513                 goto done;
514         }
515
516         lock_type = locks[i].lock_type;
517
518         if (i < (num_locks-1)) {
519                 locks[i] = locks[num_locks-1];
520         }
521         num_locks -= 1;
522
523         if (num_locks == 0) {
524                 status = rec->delete_rec(rec);
525         } else {
526                 TDB_DATA data;
527                 data = make_tdb_data((uint8_t *)locks,
528                                      sizeof(struct g_lock_rec) * num_locks);
529                 status = rec->store(rec, data, 0);
530         }
531
532         if (!NT_STATUS_IS_OK(status)) {
533                 DEBUG(1, ("g_lock_force_unlock: Could not store record: %s\n",
534                           nt_errstr(status)));
535                 goto done;
536         }
537
538         TALLOC_FREE(rec);
539
540         if ((lock_type & G_LOCK_PENDING) == 0) {
541                 int num_wakeups = 0;
542
543                 /*
544                  * We've been the lock holder. Others to retry. Don't
545                  * tell all others to avoid a thundering herd. In case
546                  * this leads to a complete stall because we miss some
547                  * processes, the loop in g_lock_lock tries at least
548                  * once a minute.
549                  */
550
551                 for (i=0; i<num_locks; i++) {
552                         if ((locks[i].lock_type & G_LOCK_PENDING) == 0) {
553                                 continue;
554                         }
555                         if (!process_exists(locks[i].pid)) {
556                                 continue;
557                         }
558
559                         /*
560                          * Ping all waiters to retry
561                          */
562                         status = messaging_send(ctx->msg, locks[i].pid,
563                                                 MSG_DBWRAP_G_LOCK_RETRY,
564                                                 &data_blob_null);
565                         if (!NT_STATUS_IS_OK(status)) {
566                                 DEBUG(1, ("sending retry to %s failed: %s\n",
567                                           procid_str(talloc_tos(),
568                                                      &locks[i].pid),
569                                           nt_errstr(status)));
570                         } else {
571                                 num_wakeups += 1;
572                         }
573                         if (num_wakeups > 5) {
574                                 break;
575                         }
576                 }
577         }
578 done:
579         /*
580          * For the error path, TALLOC_FREE(rec) as well. In the good
581          * path we have already freed it.
582          */
583         TALLOC_FREE(rec);
584
585         TALLOC_FREE(locks);
586         return status;
587 }
588
589 NTSTATUS g_lock_unlock(struct g_lock_ctx *ctx, const char *name)
590 {
591         NTSTATUS status;
592
593         status = g_lock_force_unlock(ctx, name, messaging_server_id(ctx->msg));
594
595 #ifdef CLUSTER_SUPPORT
596         if (lp_clustering()) {
597                 ctdb_unwatch(messaging_ctdbd_connection());
598         }
599 #endif
600         return status;
601 }
602
603 struct g_lock_locks_state {
604         int (*fn)(const char *name, void *private_data);
605         void *private_data;
606 };
607
608 static int g_lock_locks_fn(struct db_record *rec, void *priv)
609 {
610         struct g_lock_locks_state *state = (struct g_lock_locks_state *)priv;
611
612         if ((rec->key.dsize == 0) || (rec->key.dptr[rec->key.dsize-1] != 0)) {
613                 DEBUG(1, ("invalid key in g_lock.tdb, ignoring\n"));
614                 return 0;
615         }
616         return state->fn((char *)rec->key.dptr, state->private_data);
617 }
618
619 int g_lock_locks(struct g_lock_ctx *ctx,
620                  int (*fn)(const char *name, void *private_data),
621                  void *private_data)
622 {
623         struct g_lock_locks_state state;
624
625         state.fn = fn;
626         state.private_data = private_data;
627
628         return ctx->db->traverse_read(ctx->db, g_lock_locks_fn, &state);
629 }
630
631 NTSTATUS g_lock_dump(struct g_lock_ctx *ctx, const char *name,
632                      int (*fn)(struct server_id pid,
633                                enum g_lock_type lock_type,
634                                void *private_data),
635                      void *private_data)
636 {
637         TDB_DATA data;
638         int i, num_locks;
639         struct g_lock_rec *locks = NULL;
640         bool ret;
641
642         if (ctx->db->fetch(ctx->db, talloc_tos(), string_term_tdb_data(name),
643                            &data) != 0) {
644                 return NT_STATUS_NOT_FOUND;
645         }
646
647         if ((data.dsize == 0) || (data.dptr == NULL)) {
648                 return NT_STATUS_OK;
649         }
650
651         ret = g_lock_parse(talloc_tos(), data, &num_locks, &locks);
652
653         TALLOC_FREE(data.dptr);
654
655         if (!ret) {
656                 DEBUG(10, ("g_lock_parse for %s failed\n", name));
657                 return NT_STATUS_INTERNAL_ERROR;
658         }
659
660         for (i=0; i<num_locks; i++) {
661                 if (fn(locks[i].pid, locks[i].lock_type, private_data) != 0) {
662                         break;
663                 }
664         }
665         TALLOC_FREE(locks);
666         return NT_STATUS_OK;
667 }
668
669 struct g_lock_get_state {
670         bool found;
671         struct server_id *pid;
672 };
673
674 static int g_lock_get_fn(struct server_id pid, enum g_lock_type lock_type,
675                          void *priv)
676 {
677         struct g_lock_get_state *state = (struct g_lock_get_state *)priv;
678
679         if ((lock_type & G_LOCK_PENDING) != 0) {
680                 return 0;
681         }
682
683         state->found = true;
684         *state->pid = pid;
685         return 1;
686 }
687
688 NTSTATUS g_lock_get(struct g_lock_ctx *ctx, const char *name,
689                     struct server_id *pid)
690 {
691         struct g_lock_get_state state;
692         NTSTATUS status;
693
694         state.found = false;
695         state.pid = pid;
696
697         status = g_lock_dump(ctx, name, g_lock_get_fn, &state);
698         if (!NT_STATUS_IS_OK(status)) {
699                 return status;
700         }
701         if (!state.found) {
702                 return NT_STATUS_NOT_FOUND;
703         }
704         return NT_STATUS_OK;
705 }
706
707 static bool g_lock_init_all(TALLOC_CTX *mem_ctx,
708                             struct tevent_context **pev,
709                             struct messaging_context **pmsg,
710                             const struct server_id self,
711                             struct g_lock_ctx **pg_ctx)
712 {
713         struct tevent_context *ev = NULL;
714         struct messaging_context *msg = NULL;
715         struct g_lock_ctx *g_ctx = NULL;
716
717         ev = tevent_context_init(mem_ctx);
718         if (ev == NULL) {
719                 d_fprintf(stderr, "ERROR: could not init event context\n");
720                 goto fail;
721         }
722         msg = messaging_init(mem_ctx, self, ev);
723         if (msg == NULL) {
724                 d_fprintf(stderr, "ERROR: could not init messaging context\n");
725                 goto fail;
726         }
727         g_ctx = g_lock_ctx_init(mem_ctx, msg);
728         if (g_ctx == NULL) {
729                 d_fprintf(stderr, "ERROR: could not init g_lock context\n");
730                 goto fail;
731         }
732
733         *pev = ev;
734         *pmsg = msg;
735         *pg_ctx = g_ctx;
736         return true;
737 fail:
738         TALLOC_FREE(g_ctx);
739         TALLOC_FREE(msg);
740         TALLOC_FREE(ev);
741         return false;
742 }
743
744 NTSTATUS g_lock_do(const char *name, enum g_lock_type lock_type,
745                    struct timeval timeout, const struct server_id self,
746                    void (*fn)(void *private_data), void *private_data)
747 {
748         struct tevent_context *ev = NULL;
749         struct messaging_context *msg = NULL;
750         struct g_lock_ctx *g_ctx = NULL;
751         NTSTATUS status;
752
753         if (!g_lock_init_all(talloc_tos(), &ev, &msg, self, &g_ctx)) {
754                 status = NT_STATUS_ACCESS_DENIED;
755                 goto done;
756         }
757
758         status = g_lock_lock(g_ctx, name, lock_type, timeout);
759         if (!NT_STATUS_IS_OK(status)) {
760                 goto done;
761         }
762         fn(private_data);
763         g_lock_unlock(g_ctx, name);
764
765 done:
766         TALLOC_FREE(g_ctx);
767         TALLOC_FREE(msg);
768         TALLOC_FREE(ev);
769         return status;
770 }