]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Change loglevel and add a few debug log statements
[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 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif /* HAVE_CONFIG_H */
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdarg.h>
24 #include <limits.h>
25 #include <signal.h>
26 #include <string.h>
27 #include <errno.h>
28
29 #include <atalk/logger.h>
30 #include <atalk/cnid_dbd_private.h>
31 #include <atalk/globals.h>
32 #include <atalk/netatalk_conf.h>
33 #include <atalk/util.h>
34
35 #include "cmd_dbd.h"
36 #include "dbd.h"
37 #include "dbif.h"
38 #include "db_param.h"
39 #include "pack.h"
40
41 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
42
43 int nocniddb = 0;               /* Dont open CNID database, only scan filesystem */
44 volatile sig_atomic_t alarmed;  /* flags for signals */
45 int db_locked;                  /* have we got the fcntl lock on lockfile ? */
46
47 static DBD *dbd;
48 static int verbose;             /* Logging flag */
49 static int exclusive;           /* Exclusive volume access */
50 static struct db_param db_param = {
51     NULL,                       /* Volume dirpath */
52     1,                          /* bdb logfile autoremove */
53     64 * 1024,                  /* bdb cachesize (64 MB) */
54     DEFAULT_MAXLOCKS,           /* maxlocks */
55     DEFAULT_MAXLOCKOBJS,        /* maxlockobjs */
56     0,                          /* flush_interval */
57     0,                          /* flush_frequency */
58     0,                          /* usock_file */
59     -1,                         /* fd_table_size */
60     -1,                         /* idle_timeout */
61     -1                          /* max_vols */
62 };
63 static char dbpath[MAXPATHLEN+1];   /* Path to the dbd database */
64
65 /* 
66    Provide some logging
67  */
68 void dbd_log(enum logtype lt, char *fmt, ...)
69 {
70     int len;
71     static char logbuffer[1024];
72     va_list args;
73
74     if ( (lt == LOGSTD) || (verbose == 1)) {
75         va_start(args, fmt);
76         len = vsnprintf(logbuffer, 1023, fmt, args);
77         va_end(args);
78         logbuffer[1023] = 0;
79
80         printf("%s\n", logbuffer);
81     }
82 }
83
84 /* 
85    SIGNAL handling:
86    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
87  */
88
89 static void sig_handler(int signo)
90 {
91     alarmed = 1;
92     return;
93 }
94
95 static void set_signal(void)
96 {
97     struct sigaction sv;
98
99     sv.sa_handler = sig_handler;
100     sv.sa_flags = SA_RESTART;
101     sigemptyset(&sv.sa_mask);
102     if (sigaction(SIGTERM, &sv, NULL) < 0) {
103         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
104         exit(EXIT_FAILURE);
105     }        
106     if (sigaction(SIGINT, &sv, NULL) < 0) {
107         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
108         exit(EXIT_FAILURE);
109     }        
110
111     memset(&sv, 0, sizeof(struct sigaction));
112     sv.sa_handler = SIG_IGN;
113     sigemptyset(&sv.sa_mask);
114
115     if (sigaction(SIGABRT, &sv, NULL) < 0) {
116         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
117         exit(EXIT_FAILURE);
118     }        
119     if (sigaction(SIGHUP, &sv, NULL) < 0) {
120         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
121         exit(EXIT_FAILURE);
122     }        
123     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
124         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
125         exit(EXIT_FAILURE);
126     }        
127 }
128
129 static void usage (void)
130 {
131     printf("dbd (Netatalk %s)\n"
132            "Usage: dbd [-CeFtvx] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
133            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
134            "dbd must be run with appropiate permissions i.e. as root.\n\n"
135            "Main commands are:\n"
136            "   -d Dump CNID database\n"
137            "      Option: -i dump indexes too\n\n"
138            "   -s Scan volume:\n"
139            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
140            "               -n Don't open CNID database, skip CNID checks.\n\n"
141            "   -r Rebuild volume:\n"
142            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
143            "               -f wipe database and rebuild from IDs stored in AppleDouble\n"
144            "                  metadata file or EA. Implies -e.\n\n"
145            "   -u Upgrade:\n"
146            "      Opens the database which triggers any necessary upgrades,\n"
147            "      then closes and exits.\n\n"
148            "General options:\n"
149            "   -C convert from adouble:v2 to adouble:ea (use with -r)\n"
150            "   -F location of the afp.conf config file\n"
151            "   -e only work on inactive volumes and lock them (exclusive)\n"
152            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
153            "   -t show statistics while running\n"
154            "   -v verbose\n\n"
155            , VERSION
156         );
157 }
158
159 int main(int argc, char **argv)
160 {
161     int c, lockfd, ret = -1;
162     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
163     dbd_flags_t flags = 0;
164     char *volpath;
165     int cdir;
166     AFPObj obj = { 0 };
167     struct vol *vol;
168
169     if (geteuid() != 0) {
170         usage();
171         exit(EXIT_FAILURE);
172     }
173     /* Inhereting perms in ad_mkdir etc requires this */
174     ad_setfuid(0);
175
176     while ((c = getopt(argc, argv, ":cCdefFinrstuvx")) != -1) {
177         switch(c) {
178         case 'c':
179             flags |= DBD_FLAGS_CLEANUP;
180             break;
181         case 'C':
182             flags |= DBD_FLAGS_V2TOEA;
183             break;
184         case 'd':
185             dump = 1;
186             break;
187         case 'i':
188             dumpindexes = 1;
189             break;
190         case 's':
191             scan = 1;
192             flags |= DBD_FLAGS_SCAN;
193             break;
194         case 'n':
195             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
196             break;
197         case 'r':
198             rebuild = 1;
199             break;
200         case 't':
201             flags |= DBD_FLAGS_STATS;
202             break;
203         case 'u':
204             prep_upgrade = 1;
205             break;
206         case 'v':
207             verbose = 1;
208             break;
209         case 'e':
210             exclusive = 1;
211             flags |= DBD_FLAGS_EXCL;
212             break;
213         case 'x':
214             rebuildindexes = 1;
215             break;
216         case 'f':
217             force = 1;
218             exclusive = 1;
219             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
220             break;
221         case 'F':
222             obj.cmdlineconfigfile = strdup(optarg);
223             break;
224         case ':':
225         case '?':
226             usage();
227             exit(EXIT_FAILURE);
228             break;
229         }
230     }
231
232     if ((dump + scan + rebuild + prep_upgrade) != 1) {
233         usage();
234         exit(EXIT_FAILURE);
235     }
236
237     if ( (optind + 1) != argc ) {
238         usage();
239         exit(EXIT_FAILURE);
240     }
241     volpath = argv[optind];
242
243     setvbuf(stdout, (char *) NULL, _IONBF, 0);
244
245     /* Remember cwd */
246     if ((cdir = open(".", O_RDONLY)) < 0) {
247         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
248         exit(EXIT_FAILURE);
249     }
250         
251     /* Setup signal handling */
252     set_signal();
253
254     /* Load config */
255     if (afp_config_parse(&obj, "dbd") != 0) {
256         dbd_log( LOGSTD, "Couldn't load afp.conf");
257         exit(EXIT_FAILURE);
258     }
259
260     /* Setup logging. Should be portable among *NIXes */
261     if (!verbose)
262         setuplog("default:info", "/dev/tty");
263     else
264         setuplog("default:debug", "/dev/tty");
265
266     if (load_volumes(&obj, NULL) != 0) {
267         dbd_log( LOGSTD, "Couldn't load volumes");
268         exit(EXIT_FAILURE);
269     }
270
271     if ((vol = getvolbypath(&obj, volpath)) == NULL) {
272         dbd_log( LOGSTD, "Couldn't find volume for '%s'", volpath);
273         exit(EXIT_FAILURE);
274     }
275
276     if (load_charset(vol) != 0) {
277         dbd_log( LOGSTD, "Couldn't load charsets for '%s'", volpath);
278         exit(EXIT_FAILURE);
279     }
280
281     pack_setvol(vol);
282
283     if (vol->v_adouble == AD_VERSION_EA)
284         dbd_log( LOGDEBUG, "adouble:ea volume");
285     else if (vol->v_adouble == AD_VERSION2)
286         dbd_log( LOGDEBUG, "adouble:v2 volume");
287     else {
288         dbd_log( LOGSTD, "unknown adouble volume");
289         exit(EXIT_FAILURE);
290     }
291
292     /* -C v2 to ea conversion only on adouble:ea volumes */
293     if ((flags & DBD_FLAGS_V2TOEA) && (vol->v_adouble!= AD_VERSION_EA)) {
294         dbd_log( LOGSTD, "Can't run adouble:v2 to adouble:ea conversion because not an adouble:ea volume");
295         exit(EXIT_FAILURE);
296     }
297
298     /* Sanity checks to ensure we can touch this volume */
299     if (vol->v_vfs_ea != AFPVOL_EA_AD && vol->v_vfs_ea != AFPVOL_EA_SYS) {
300         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", vol->v_vfs_ea);
301         exit(EXIT_FAILURE);        
302     }
303
304     /* Enuser dbpath is there, create if necessary */
305     struct stat st;
306     if (stat(vol->v_dbpath, &st) != 0) {
307         if (errno != ENOENT) {
308             dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
309             exit(EXIT_FAILURE);        
310         }
311         if ((mkdir(vol->v_dbpath, 0755)) != 0) {
312             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
313             exit(EXIT_FAILURE);
314         }        
315     }
316
317     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
318     if ( (strlen(vol->v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
319         dbd_log( LOGSTD, "Volume pathname too long");
320         exit(EXIT_FAILURE);        
321     }
322     strncpy(dbpath, vol->v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
323     strcat(dbpath, "/.AppleDB");
324
325     /* Check or create dbpath */
326     int dbdirfd = open(dbpath, O_RDONLY);
327     if (dbdirfd == -1 && errno == ENOENT) {
328         if (errno == ENOENT) {
329             if ((mkdir(dbpath, 0755)) != 0) {
330                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
331                 exit(EXIT_FAILURE);
332             }
333         } else {
334             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
335             exit(EXIT_FAILURE);
336         }
337     } else {
338         close(dbdirfd);
339     }
340
341     /* Get db lock */
342     if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
343         goto exit_noenv;
344     if (db_locked != LOCK_EXCL) {
345         dbd_log(LOGDEBUG, "Database is in use, acquiring shared lock");
346         /* Couldn't get exclusive lock, try shared lock if -e wasn't requested */
347         if (exclusive) {
348             dbd_log(LOGSTD, "Database is in use and exlusive was requested");
349             goto exit_noenv;
350         }
351         if ((db_locked = get_lock(LOCK_SHRD, NULL)) != LOCK_SHRD)
352             goto exit_noenv;
353     }
354
355     /* Check if -f is requested and wipe db if yes */
356     if ((flags & DBD_FLAGS_FORCE) && rebuild) {
357         char cmd[8 + MAXPATHLEN];
358         if ((db_locked = get_lock(LOCK_FREE, NULL)) != 0)
359             goto exit_noenv;
360
361         snprintf(cmd, 8 + MAXPATHLEN, "rm -rf \"%s\"", dbpath);
362         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
363         system(cmd);
364         if ((mkdir(dbpath, 0755)) != 0) {
365             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
366             exit(EXIT_FAILURE);
367         }
368         dbd_log( LOGDEBUG, "Removed old database.");
369         if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
370             goto exit_noenv;
371     }
372
373     /* 
374        Lets start with the BerkeleyDB stuff
375     */
376     if ( ! nocniddb) {
377         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
378             goto exit_noenv;
379         
380         if (dbif_env_open(dbd,
381                           &db_param,
382                           (db_locked == LOCK_EXCL) ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
383             dbd_log( LOGSTD, "error opening database!");
384             goto exit_noenv;
385         }
386
387         if (db_locked == LOCK_EXCL)
388             dbd_log( LOGDEBUG, "Finished recovery.");
389
390         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
391             dbif_close(dbd);
392             goto exit_failure;
393         }
394
395         /* Prepare upgrade ? We're done */
396         if (prep_upgrade) {
397             (void)dbif_txn_close(dbd, 1);
398             goto cleanup;
399         }
400     }
401
402     /* Downgrade db lock if not running exclusive */
403     if (!exclusive && (db_locked == LOCK_EXCL)) {
404         if (get_lock(LOCK_UNLOCK, NULL) != 0)
405             goto exit_failure;
406         if (get_lock(LOCK_SHRD, NULL) != LOCK_SHRD)
407             goto exit_failure;
408     }
409
410     /* Now execute given command scan|rebuild|dump */
411     if (dump && ! nocniddb) {
412         if (dbif_dump(dbd, dumpindexes) < 0) {
413             dbd_log( LOGSTD, "Error dumping database");
414         }
415     } else if ((rebuild && ! nocniddb) || scan) {
416         if (cmd_dbd_scanvol(dbd, vol, flags) < 0) {
417             dbd_log( LOGSTD, "Error repairing database.");
418         }
419     }
420
421 cleanup:
422     /* Cleanup */
423     dbd_log(LOGDEBUG, "Closing db");
424     if (! nocniddb) {
425         if (dbif_close(dbd) < 0) {
426             dbd_log( LOGSTD, "Error closing database");
427             goto exit_failure;
428         }
429     }
430
431 exit_success:
432     ret = 0;
433
434 exit_failure:
435     if (dbif_env_remove(dbpath) < 0) {
436         dbd_log( LOGSTD, "Error removing BerkeleyDB database environment");
437         ret++;
438     }
439     get_lock(0, NULL);
440
441 exit_noenv:    
442     if ((fchdir(cdir)) < 0)
443         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
444
445     if (ret == 0)
446         exit(EXIT_SUCCESS);
447     else
448         exit(EXIT_FAILURE);
449 }