]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Reliable db locking
[netatalk.git] / etc / cnid_dbd / cmd_dbd.c
1 /* 
2    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3    
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8  
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 */
14
15 /*
16   dbd specs and implementation progress
17   =====================================
18
19   St := Status
20
21   Force option
22   ------------
23   
24   St Spec
25   -- ----
26   OK If -f is requested, ensure -e is too.
27      Check if volumes is using AFPVOL_CACHE, then wipe db from disk. Rebuild from ad-files.
28
29   1st pass: Scan volume
30   --------------------
31
32   St Type Check
33   -- ---- -----
34   OK F/D  Make sure ad file exists
35   OK D    Make sure .AppleDouble dir exist, create if missing. Error creating
36           it is fatal as that shouldn't happen as root.
37   OK F/D  Delete orphaned ad-files, log dirs in ad-dir
38   OK F/D  Check name encoding by roundtripping, log on error
39   OK F/D  try: read CNID from ad file (if cnid caching is on)
40           try: fetch CNID from database
41           -> on mismatch: use CNID from file, update database (deleting both found CNIDs first)
42           -> if no CNID in ad file: write CNID from database to ad file
43           -> if no CNID in database: add CNID from ad file to database
44           -> on no CNID at all: create one and store in both places
45   OK F/D  Add found CNID, DID, filename, dev/inode, stamp to rebuild database
46   OK F/D  Check/update stamp (implicitly done while checking CNIDs)
47
48
49   2nd pass: Delete unused CNIDs
50   -----------------------------
51
52   St Spec
53   -- ----
54   OK Step through dbd (the one on disk) and rebuild-db from pass 1 and delete any CNID from
55      dbd not in rebuild db. This in only done in exclusive mode.
56 */
57
58 #ifdef HAVE_CONFIG_H
59 #include "config.h"
60 #endif /* HAVE_CONFIG_H */
61
62 #include <unistd.h>
63 #include <sys/types.h>
64 #include <stdlib.h>
65 #include <stdio.h>
66 #include <stdarg.h>
67 #include <limits.h>
68 #include <signal.h>
69 #include <string.h>
70 #include <errno.h>
71
72 #include <atalk/logger.h>
73 #include <atalk/cnid_dbd_private.h>
74 #include <atalk/volinfo.h>
75 #include <atalk/util.h>
76
77 #include "cmd_dbd.h"
78 #include "dbd.h"
79 #include "dbif.h"
80 #include "db_param.h"
81
82 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
83
84 int nocniddb = 0;               /* Dont open CNID database, only scan filesystem */
85 volatile sig_atomic_t alarmed;  /* flags for signals */
86 int db_locked;                  /* have we got the fcntl lock on lockfile ? */
87
88 static DBD *dbd;
89 static int verbose;             /* Logging flag */
90 static int exclusive;           /* Exclusive volume access */
91 static struct db_param db_param = {
92     NULL,                       /* Volume dirpath */
93     1,                          /* bdb logfile autoremove */
94     64 * 1024,                  /* bdb cachesize (64 MB) */
95     0,                          /* flush_interval */
96     0,                          /* flush_frequency */
97     0,                          /* usock_file */
98     -1,                         /* fd_table_size */
99     -1,                         /* idle_timeout */
100     -1                          /* max_vols */
101 };
102 static char dbpath[PATH_MAX];   /* Path to the dbd database */
103
104 /* 
105    Provide some logging
106  */
107 void dbd_log(enum logtype lt, char *fmt, ...)
108 {
109     int len;
110     static char logbuffer[1024];
111     va_list args;
112
113     if ( (lt == LOGSTD) || (verbose == 1)) {
114         va_start(args, fmt);
115         len = vsnprintf(logbuffer, 1023, fmt, args);
116         va_end(args);
117         logbuffer[1023] = 0;
118
119         printf("%s\n", logbuffer);
120     }
121 }
122
123 /* 
124    SIGNAL handling:
125    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
126  */
127
128 static void sig_handler(int signo)
129 {
130     alarmed = 1;
131     return;
132 }
133
134 static void set_signal(void)
135 {
136     struct sigaction sv;
137
138     sv.sa_handler = sig_handler;
139     sv.sa_flags = SA_RESTART;
140     sigemptyset(&sv.sa_mask);
141     if (sigaction(SIGTERM, &sv, NULL) < 0) {
142         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
143         exit(EXIT_FAILURE);
144     }        
145     if (sigaction(SIGINT, &sv, NULL) < 0) {
146         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
147         exit(EXIT_FAILURE);
148     }        
149
150     memset(&sv, 0, sizeof(struct sigaction));
151     sv.sa_handler = SIG_IGN;
152     sigemptyset(&sv.sa_mask);
153
154     if (sigaction(SIGABRT, &sv, NULL) < 0) {
155         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
156         exit(EXIT_FAILURE);
157     }        
158     if (sigaction(SIGHUP, &sv, NULL) < 0) {
159         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
160         exit(EXIT_FAILURE);
161     }        
162     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
163         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
164         exit(EXIT_FAILURE);
165     }        
166 }
167
168 static void usage (void)
169 {
170     printf("Usage: dbd [-e|-t|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
171            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
172            "dbd must be run with appropiate permissions i.e. as root.\n\n"
173            "Main commands are:\n"
174            "   -d Dump CNID database\n"
175            "      Option: -i dump indexes too\n\n"
176            "   -s Scan volume:\n"
177            "      1. Compare CNIDs in database with volume\n"
178            "      2. Check if .AppleDouble dirs exist\n"
179            "      3. Check if  AppleDouble file exist\n"
180            "      4. Report orphaned AppleDouble files\n"
181            "      5. Check for directories inside AppleDouble directories\n"
182            "      6. Check name encoding by roundtripping, log on error\n"
183            "      7. Check for orphaned CNIDs in database (requires -e)\n"
184            "      8. Open and close adouble files\n"
185            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
186            "               -n Don't open CNID database, skip CNID checks\n\n"
187            "   -r Rebuild volume:\n"
188            "      1. Sync CNIDSs in database with volume\n"
189            "      2. Make sure .AppleDouble dir exist, create if missing\n"
190            "      3. Make sure AppleDouble file exists, create if missing\n"
191            "      4. Delete orphaned AppleDouble files\n"
192            "      5. Check for directories inside AppleDouble directories\n"
193            "      6. Check name encoding by roundtripping, log on error\n"
194            "      7. Check for orphaned CNIDs in database (requires -e)\n"
195            "      8. Open and close adouble files\n"
196            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
197            "               -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
198            "                  only available for volumes without 'nocnidcache' option. Implies -e.\n\n"
199            "   -u Prepare upgrade:\n"
200            "      Before installing an upgraded version of Netatalk that is linked against\n"
201            "      a newer BerkeleyDB lib, run `dbd -u ...` from the OLD Netatalk pior to\n"
202            "      upgrading on all volumes. This removes the BerkleyDB environment.\n"
203            "      On exit cnid_dbd does this automatically, so normally calling dbd -u should not be necessary.\n\n"
204            "General options:\n"
205            "   -e only work on inactive volumes and lock them (exclusive)\n"
206            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
207            "   -t show statistics while running\n"
208            "   -v verbose\n\n"
209            "WARNING:\n"
210            "For -r -f restore of the CNID database from the adouble files, the CNID must of course\n"
211            "be synched to them files first with a plain -r rebuild !\n"
212         );
213 }
214
215 int main(int argc, char **argv)
216 {
217     int c, lockfd, ret = -1;
218     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
219     dbd_flags_t flags = 0;
220     char *volpath;
221     struct volinfo volinfo;
222     int cdir;
223
224     if (geteuid() != 0) {
225         usage();
226         exit(EXIT_FAILURE);
227     }
228     /* Inhereting perms in ad_mkdir etc requires this */
229     ad_setfuid(0);
230
231     while ((c = getopt(argc, argv, ":cdefinrstuvx")) != -1) {
232         switch(c) {
233         case 'c':
234             flags |= DBD_FLAGS_CLEANUP;
235             break;
236         case 'd':
237             dump = 1;
238             break;
239         case 'i':
240             dumpindexes = 1;
241             break;
242         case 's':
243             scan = 1;
244             flags |= DBD_FLAGS_SCAN;
245             break;
246         case 'n':
247             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
248             break;
249         case 'r':
250             rebuild = 1;
251             break;
252         case 't':
253             flags |= DBD_FLAGS_STATS;
254             break;
255         case 'u':
256             prep_upgrade = 1;
257             break;
258         case 'v':
259             verbose = 1;
260             break;
261         case 'e':
262             exclusive = 1;
263             flags |= DBD_FLAGS_EXCL;
264             break;
265         case 'x':
266             rebuildindexes = 1;
267             break;
268         case 'f':
269             force = 1;
270             exclusive = 1;
271             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
272             break;
273         case ':':
274         case '?':
275             usage();
276             exit(EXIT_FAILURE);
277             break;
278         }
279     }
280
281     if ((dump + scan + rebuild + prep_upgrade) != 1) {
282         usage();
283         exit(EXIT_FAILURE);
284     }
285
286     if ( (optind + 1) != argc ) {
287         usage();
288         exit(EXIT_FAILURE);
289     }
290     volpath = argv[optind];
291
292     setvbuf(stdout, (char *) NULL, _IONBF, 0);
293
294     /* Remember cwd */
295     if ((cdir = open(".", O_RDONLY)) < 0) {
296         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
297         exit(EXIT_FAILURE);
298     }
299         
300     /* Setup signal handling */
301     set_signal();
302
303     /* Setup logging. Should be portable among *NIXes */
304     if (!verbose)
305         setuplog("default log_info /dev/tty");
306     else
307         setuplog("default log_debug /dev/tty");
308
309     /* Load .volinfo file */
310     if (loadvolinfo(volpath, &volinfo) == -1) {
311         dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
312         exit(EXIT_FAILURE);
313     }
314     if (vol_load_charsets(&volinfo) == -1) {
315         dbd_log( LOGSTD, "Error loading charsets!");
316         exit(EXIT_FAILURE);
317     }
318
319     /* Sanity checks to ensure we can touch this volume */
320     if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
321         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
322         exit(EXIT_FAILURE);        
323     }
324
325     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
326     if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > (PATH_MAX - 1) ) {
327         dbd_log( LOGSTD, "Volume pathname too long");
328         exit(EXIT_FAILURE);        
329     }
330     strncpy(dbpath, volinfo.v_dbpath, PATH_MAX - 9 - 1);
331     strcat(dbpath, "/.AppleDB");
332
333     /* Check or create dbpath */
334     int dbdirfd = open(dbpath, O_RDONLY);
335     if (dbdirfd == -1 && errno == ENOENT) {
336         if (errno == ENOENT) {
337             if ((mkdir(dbpath, 0755)) != 0) {
338                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
339                 exit(EXIT_FAILURE);
340             }
341         } else {
342             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
343             exit(EXIT_FAILURE);
344         }
345     } else {
346         close(dbdirfd);
347     }
348
349     /* Get db lock */
350     if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
351         goto exit_failure;
352     if (db_locked != LOCK_EXCL) {
353         /* Couldn't get exclusive lock, try shared lock if -e wasn't requested */
354         if (exclusive) {
355             dbd_log(LOGSTD, "Database is in use and exlusive was requested");
356             goto exit_failure;
357         }
358         if ((db_locked = get_lock(LOCK_SHRD, NULL)) != LOCK_SHRD)
359             goto exit_failure;
360     }
361
362     /* Prepare upgrade ? */
363     if (prep_upgrade) {
364         if (dbif_prep_upgrade(dbpath))
365             goto exit_failure;
366         goto exit_success;
367     }        
368
369     /* Check if -f is requested and wipe db if yes */
370     if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
371         char cmd[8 + MAXPATHLEN];
372         if ((db_locked = get_lock(LOCK_FREE, NULL)) != 0)
373             goto exit_failure;
374         snprintf(cmd, 8 + MAXPATHLEN, "rm -f %s/*", dbpath);
375         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
376         system(cmd);
377         dbd_log( LOGDEBUG, "Removed old database.");
378         if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
379             goto exit_failure;
380     }
381
382     /* 
383        Lets start with the BerkeleyDB stuff
384     */
385     if ( ! nocniddb) {
386         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
387             goto exit_failure;
388         
389         if (dbif_env_open(dbd,
390                           &db_param,
391                           (db_locked == LOCK_EXCL) ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
392             dbd_log( LOGSTD, "error opening database!");
393             goto exit_failure;
394         }
395
396         if (db_locked == LOCK_EXCL)
397             dbd_log( LOGDEBUG, "Finished recovery.");
398
399         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
400             dbif_close(dbd);
401             goto exit_failure;
402         }
403
404         if (dbd_stamp(dbd) < 0) {
405             dbif_close(dbd);
406             goto exit_failure;
407         }
408     }
409
410     /* Downgrade db lock if not running exclusive */
411     if (!exclusive && (db_locked == LOCK_EXCL)) {
412         if (get_lock(LOCK_UNLOCK, NULL) != 0)
413             goto exit_failure;
414         if (get_lock(LOCK_SHRD, NULL) != LOCK_SHRD)
415             goto exit_failure;
416     }
417
418     /* Now execute given command scan|rebuild|dump */
419     if (dump && ! nocniddb) {
420         if (dbif_dump(dbd, dumpindexes) < 0) {
421             dbd_log( LOGSTD, "Error dumping database");
422         }
423     } else if ((rebuild && ! nocniddb) || scan) {
424         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
425             dbd_log( LOGSTD, "Error repairing database.");
426         }
427     }
428
429     /* Cleanup */
430     dbd_log(LOGDEBUG, "Closing db");
431     if (! nocniddb) {
432         if (dbif_close(dbd) < 0) {
433             dbd_log( LOGSTD, "Error closing database");
434             goto exit_failure;
435         }
436     }
437
438 exit_success:
439     ret = 0;
440
441 exit_failure:
442     get_lock(0, NULL);
443     
444     if ((fchdir(cdir)) < 0)
445         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
446
447     if (ret == 0)
448         exit(EXIT_SUCCESS);
449     else
450         exit(EXIT_FAILURE);
451 }