improve command-line help for --enable_peer_stats
[openafs.git] / src / budb / server.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12 #include <afs/stds.h>
13
14 #include <roken.h>
15
16 #ifdef AFS_NT40_ENV
17 #include <WINNT/afsevent.h>
18 #endif
19 #include <afs/cmd.h>
20 #include <lwp.h>
21 #include <ubik.h>
22 #include <rx/xdr.h>
23 #include <rx/rx.h>
24 #include <rx/rxkad.h>
25 #include <rx/rx_globals.h>
26 #include <afs/cellconfig.h>
27 #include <afs/bubasics.h>
28 #include <afs/afsutil.h>
29 #include <afs/com_err.h>
30 #include <afs/audit.h>
31
32 #include "budb_errs.h"
33 #include "database.h"
34 #include "error_macros.h"
35 #include "budb_internal.h"
36 #include "globals.h"
37
38 struct ubik_dbase *BU_dbase;
39 struct afsconf_dir *BU_conf;    /* for getting cell info */
40
41 int argHandler(struct cmd_syndesc *, void *);
42 int truncateDatabase(void);
43 int parseServerList(struct cmd_item *);
44
45 char lcell[MAXKTCREALMLEN];
46 afs_uint32 myHost = 0;
47 int helpOption;
48 static struct logOptions logopts;
49
50 /* server's global configuration information. This is exported to other
51  * files/routines
52  */
53
54 buServerConfT globalConf;
55 buServerConfP globalConfPtr = &globalConf;
56 char dbDir[AFSDIR_PATH_MAX], cellConfDir[AFSDIR_PATH_MAX];
57 /* debugging control */
58 int debugging = 0;
59
60 int rxBind = 0;
61 int lwps   = 3;
62
63 #define MINLWP  3
64 #define MAXLWP 16
65
66 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
67 afs_uint32 SHostAddrs[ADDRSPERSITE];
68
69 /* check whether caller is authorized to manage RX statistics */
70 int
71 BU_rxstat_userok(struct rx_call *call)
72 {
73     return afsconf_SuperUser(BU_conf, call, NULL);
74 }
75
76 /**
77  * Return true if this name is a member of the local realm.
78  */
79 int
80 BU_IsLocalRealmMatch(void *rock, char *name, char *inst, char *cell)
81 {
82     struct afsconf_dir *dir = (struct afsconf_dir *)rock;
83     afs_int32 islocal = 0;      /* default to no */
84     int code;
85
86     code = afsconf_IsLocalRealmMatch(dir, &islocal, name, inst, cell);
87     if (code) {
88         LogError(code, "Failed local realm check; name=%s, inst=%s, cell=%s\n",
89                  name, inst, cell);
90     }
91     return islocal;
92 }
93
94 int
95 convert_cell_to_ubik(struct afsconf_cell *cellinfo, afs_uint32 *myHost,
96                      afs_uint32 *serverList)
97 {
98     int i;
99     char hostname[64];
100     struct hostent *th;
101
102     /* get this host */
103     gethostname(hostname, sizeof(hostname));
104     th = gethostbyname(hostname);
105     if (!th) {
106         printf("prserver: couldn't get address of this host.\n");
107         BUDB_EXIT(1);
108     }
109     memcpy(myHost, th->h_addr, sizeof(afs_uint32));
110
111     for (i = 0; i < cellinfo->numServers; i++)
112         /* omit my host from serverList */
113         if (cellinfo->hostAddr[i].sin_addr.s_addr != *myHost)
114             *serverList++ = cellinfo->hostAddr[i].sin_addr.s_addr;
115
116     *serverList = 0;            /* terminate list */
117     return 0;
118 }
119
120 /* MyBeforeProc
121  *      The whole purpose of MyBeforeProc is to detect
122  *      if the -help option was not within the command line.
123  *      If it were, this routine would never have been called.
124  */
125 static int
126 MyBeforeProc(struct cmd_syndesc *as, void *arock)
127 {
128     helpOption = 0;
129     return 0;
130 }
131
132 /* initializeCommands
133  *      initialize all the supported commands and their arguments
134  */
135
136 void
137 initializeArgHandler(void)
138 {
139     struct cmd_syndesc *cptr;
140
141     cmd_SetBeforeProc(MyBeforeProc, NULL);
142
143     cptr = cmd_CreateSyntax(NULL, argHandler, NULL, 0, "Backup database server");
144
145     cmd_AddParm(cptr, "-database", CMD_SINGLE, CMD_OPTIONAL,
146                 "database directory");
147
148     cmd_AddParm(cptr, "-cellservdb", CMD_SINGLE, CMD_OPTIONAL,
149                 "cell configuration directory");
150
151     cmd_AddParm(cptr, "-resetdb", CMD_FLAG, CMD_OPTIONAL,
152                 "truncate the database");
153
154     cmd_AddParm(cptr, "-noauth", CMD_FLAG, CMD_OPTIONAL,
155                 "run without authentication");
156
157     cmd_AddParm(cptr, "-smallht", CMD_FLAG, CMD_OPTIONAL,
158                 "use small hash tables");
159
160     cmd_AddParm(cptr, "-servers", CMD_LIST, CMD_OPTIONAL,
161                 "list of ubik database servers");
162
163     cmd_AddParm(cptr, "-ubikbuffers", CMD_SINGLE, CMD_OPTIONAL,
164                 "the number of ubik buffers");
165
166     cmd_AddParm(cptr, "-auditlog", CMD_SINGLE, CMD_OPTIONAL,
167                 "audit log path");
168
169     cmd_AddParm(cptr, "-p", CMD_SINGLE, CMD_OPTIONAL,
170                 "number of processes");
171
172     cmd_AddParm(cptr, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
173                 "bind the Rx socket (primary interface only)");
174
175     cmd_AddParm(cptr, "-audit-interface", CMD_SINGLE, CMD_OPTIONAL,
176                 "audit interface (file or sysvmq)");
177
178     cmd_AddParm(cptr, "-transarc-logs", CMD_FLAG, CMD_OPTIONAL,
179                 "enable Transarc style logging");
180 }
181
182 int
183 argHandler(struct cmd_syndesc *as, void *arock)
184 {
185
186     /* globalConfPtr provides the handle for the configuration information */
187
188     /* database directory */
189     if (as->parms[0].items != 0) {
190         globalConfPtr->databaseDirectory = strdup(as->parms[0].items->data);
191         if (globalConfPtr->databaseDirectory == 0)
192             BUDB_EXIT(-1);
193     }
194
195     /* -cellservdb, cell configuration directory */
196     if (as->parms[1].items != 0) {
197         globalConfPtr->cellConfigdir = strdup(as->parms[1].items->data);
198         if (globalConfPtr->cellConfigdir == 0)
199             BUDB_EXIT(-1);
200
201         globalConfPtr->debugFlags |= DF_RECHECKNOAUTH;
202     }
203
204     /* truncate the database */
205     if (as->parms[2].items != 0)
206         truncateDatabase();
207
208     /* run without authentication */
209     if (as->parms[3].items != 0)
210         globalConfPtr->debugFlags |= DF_NOAUTH;
211
212     /* use small hash tables */
213     if (as->parms[4].items != 0)
214         globalConfPtr->debugFlags |= DF_SMALLHT;
215
216     /* user provided list of ubik database servers */
217     if (as->parms[5].items != 0)
218         parseServerList(as->parms[5].items);
219
220     /* user provided the number of ubik buffers    */
221     if (as->parms[6].items != 0)
222         ubik_nBuffers = atoi(as->parms[6].items->data);
223     else
224         ubik_nBuffers = 0;
225
226     /* param 7 (-auditlog) handled below */
227
228     /* user provided the number of threads    */
229     if (as->parms[8].items != 0) {
230         lwps = atoi(as->parms[8].items->data);
231         if (lwps > MAXLWP) {
232             printf ("Warning: '-p %d' is too big; using %d instead\n",
233                 lwps, MAXLWP);
234             lwps = MAXLWP;
235         }
236         if (lwps < MINLWP) {
237             printf ("Warning: '-p %d' is too small; using %d instead\n",
238                 lwps, MINLWP);
239             lwps = MINLWP;
240         }
241     }
242
243     /* user provided rxbind option    */
244     if (as->parms[9].items != 0) {
245         rxBind = 1;
246     }
247
248     /* -audit-interface */
249     if (as->parms[10].items != 0) {
250         char *interface = as->parms[10].items->data;
251
252         if (osi_audit_interface(interface)) {
253             printf("Invalid audit interface '%s'\n", interface);
254             BUDB_EXIT(-1);
255         }
256     }
257     /* -transarc-logs */
258     if (as->parms[11].items != 0) {
259         logopts.lopt_rotateOnOpen = 1;
260         logopts.lopt_rotateStyle = logRotate_old;
261     }
262
263     /* -auditlog */
264     /* needs to be after -audit-interface, so we osi_audit_interface
265      * before we osi_audit_file */
266     if (as->parms[7].items != 0) {
267         char *fileName = as->parms[7].items->data;
268
269         osi_audit_file(fileName);
270     }
271
272     return 0;
273 }
274
275 /* --- */
276
277 int
278 parseServerList(struct cmd_item *itemPtr)
279 {
280     struct cmd_item *save;
281     char **serverArgs;
282     char **ptr;
283     afs_int32 nservers = 0;
284     afs_int32 code = 0;
285
286     save = itemPtr;
287
288     /* compute number of servers in the list */
289     while (itemPtr) {
290         nservers++;
291         itemPtr = itemPtr->next;
292     }
293
294     LogDebug(3, "%d servers\n", nservers);
295
296     /* now can allocate the space for the server arguments */
297     serverArgs = malloc((nservers + 2) * sizeof(char *));
298     if (serverArgs == 0)
299         ERROR(-1);
300
301     ptr = serverArgs;
302     *ptr++ = "";
303     *ptr++ = "-servers";
304
305     /* now go through and construct the list of servers */
306     itemPtr = save;
307     while (itemPtr) {
308         *ptr++ = itemPtr->data;
309         itemPtr = itemPtr->next;
310     }
311
312     code =
313         ubik_ParseServerList(nservers + 2, serverArgs, &globalConfPtr->myHost,
314                              globalConfPtr->serverList);
315     if (code)
316         ERROR(code);
317
318     /* free space for the server args */
319     free(serverArgs);
320
321   error_exit:
322     return (code);
323 }
324
325 /* truncateDatabase
326  *      truncates just the database file.
327  */
328
329 int
330 truncateDatabase(void)
331 {
332     char *path;
333     afs_int32 code = 0;
334     int fd,r;
335
336     r = asprintf(&path, "%s%s%s",
337                  globalConfPtr->databaseDirectory,
338                  globalConfPtr->databaseName,
339                  globalConfPtr->databaseExtension);
340     if (r < 0 || path == NULL)
341         ERROR(-1);
342
343     fd = open(path, O_RDWR, 0755);
344     if (!fd) {
345         code = errno;
346     } else {
347         if (ftruncate(fd, 0) != 0) {
348             code = errno;
349         } else
350             close(fd);
351     }
352
353     free(path);
354
355   error_exit:
356     return (code);
357 }
358
359
360 /* --- */
361
362 #include "AFS_component_version_number.c"
363
364 int
365 main(int argc, char **argv)
366 {
367     char *whoami = argv[0];
368     char *dbNamePtr = 0;
369     struct afsconf_cell cellinfo_s;
370     struct afsconf_cell *cellinfo = NULL;
371     time_t currentTime;
372     afs_int32 code = 0;
373     char hoststr[16];
374     afs_uint32 host = ntohl(INADDR_ANY);
375     int r;
376
377     char  clones[MAXHOSTSPERCELL];
378
379     struct rx_service *tservice;
380     struct rx_securityClass **securityClasses;
381     afs_int32 numClasses;
382
383     extern int rx_stackSize;
384
385 #ifdef AFS_NT40_ENV
386     /* initialize winsock */
387     if (afs_winsockInit() < 0) {
388         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
389         fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
390         exit(1);
391     }
392 #endif
393
394 #ifdef  AFS_AIX32_ENV
395     /*
396      * The following signal action for AIX is necessary so that in case of a
397      * crash (i.e. core is generated) we can include the user's data section
398      * in the core dump. Unfortunately, by default, only a partial core is
399      * generated which, in many cases, isn't too useful.
400      */
401     struct sigaction nsa;
402
403     sigemptyset(&nsa.sa_mask);
404     nsa.sa_handler = SIG_DFL;
405     nsa.sa_flags = SA_FULLDUMP;
406     sigaction(SIGSEGV, &nsa, NULL);
407     sigaction(SIGABRT, &nsa, NULL);
408 #endif
409
410     memset(&cellinfo_s, 0, sizeof(cellinfo_s));
411     memset(clones, 0, sizeof(clones));
412
413     memset(&logopts, 0, sizeof(logopts));
414     logopts.lopt_dest = logDest_file;
415     logopts.lopt_filename = AFSDIR_SERVER_BUDBLOG_FILEPATH;
416
417     osi_audit_init();
418     osi_audit(BUDB_StartEvent, 0, AUD_END);
419
420     initialize_BUDB_error_table();
421     initializeArgHandler();
422
423     /* Initialize dirpaths */
424     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
425 #ifdef AFS_NT40_ENV
426         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
427 #endif
428         afs_com_err(whoami, errno, "; Unable to obtain AFS server directory.");
429         exit(2);
430     }
431
432     memset(globalConfPtr, 0, sizeof(*globalConfPtr));
433
434     /* set default configuration values */
435     strcpy(dbDir, AFSDIR_SERVER_DB_DIRPATH);
436     strcat(dbDir, "/");
437     globalConfPtr->databaseDirectory = dbDir;
438     globalConfPtr->databaseName = DEFAULT_DBPREFIX;
439     strcpy(cellConfDir, AFSDIR_SERVER_ETC_DIRPATH);
440     globalConfPtr->cellConfigdir = cellConfDir;
441
442     srandom(1);
443
444 #ifdef AFS_PTHREAD_ENV
445     SetLogThreadNumProgram( rx_GetThreadNum );
446 #endif
447
448     /* process the user supplied args */
449     helpOption = 1;
450     code = cmd_Dispatch(argc, argv);
451     if (code)
452         ERROR(code);
453
454     /* exit if there was a help option */
455     if (helpOption)
456         BUDB_EXIT(0);
457
458     /* open the log file */
459     OpenLog(&logopts);
460
461     /* open the cell's configuration directory */
462     LogDebug(4, "opening %s\n", globalConfPtr->cellConfigdir);
463
464     BU_conf = afsconf_Open(globalConfPtr->cellConfigdir);
465     if (BU_conf == 0) {
466         LogError(code, "Failed getting cell info\n");
467         afs_com_err(whoami, code, "Failed getting cell info");
468         ERROR(BUDB_NOCELLS);
469     }
470
471     code = afsconf_GetLocalCell(BU_conf, lcell, sizeof(lcell));
472     if (code) {
473         LogError(0, "** Can't determine local cell name!\n");
474         ERROR(code);
475     }
476
477     if (globalConfPtr->myHost == 0) {
478         /* if user hasn't supplied a list of servers, extract server
479          * list from the cell's database
480          */
481
482         cellinfo = &cellinfo_s;
483
484         LogDebug(1, "Using server list from %s cell database.\n", lcell);
485
486         code = afsconf_GetExtendedCellInfo (BU_conf, lcell, 0, cellinfo,
487                                             clones);
488         if (code) {
489             LogError(0, "Can't read cell information\n");
490             ERROR(code);
491         }
492
493         code =
494             convert_cell_to_ubik(cellinfo, &globalConfPtr->myHost,
495                                  globalConfPtr->serverList);
496         if (code)
497             ERROR(code);
498     }
499
500     /* initialize audit user check */
501     osi_audit_set_user_check(BU_conf, BU_IsLocalRealmMatch);
502
503     /* initialize ubik */
504     ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, BU_conf);
505     ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
506                                 afsconf_CheckAuth, BU_conf);
507
508     if (ubik_nBuffers == 0)
509         ubik_nBuffers = 400;
510
511     LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);
512
513     r = asprintf(&dbNamePtr, "%s%s", globalConfPtr->databaseDirectory,
514                  globalConfPtr->databaseName);
515     if (r < 0 || dbNamePtr == 0)
516         ERROR(-1);
517
518     rx_SetRxDeadTime(60);       /* 60 seconds inactive before timeout */
519
520     if (rxBind) {
521         afs_int32 ccode;
522         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
523             AFSDIR_SERVER_NETINFO_FILEPATH) {
524             char reason[1024];
525             ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
526                                           ADDRSPERSITE, reason,
527                                           AFSDIR_SERVER_NETINFO_FILEPATH,
528                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
529         } else
530         {
531             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
532         }
533         if (ccode == 1) {
534             host = SHostAddrs[0];
535         }
536     }
537
538     Log("buserver binding rx to %s:%d\n",
539         afs_inet_ntoa_r(host, hoststr), AFSCONF_BUDBPORT);
540     code = rx_InitHost(host, htons(AFSCONF_BUDBPORT));
541     if (code) {
542         LogError(code, "rx init failed\n");
543         afs_com_err(whoami, code, "rx init failed");
544         ERROR(code);
545     }
546
547     /* Disable jumbograms */
548     rx_SetNoJumbo();
549
550     if (cellinfo) {
551         code = ubik_ServerInitByInfo(globalConfPtr->myHost,
552                                      htons(AFSCONF_BUDBPORT),
553                                      cellinfo,
554                                      clones,
555                                      dbNamePtr,           /* name prefix */
556                                      &BU_dbase);
557     } else {
558         code = ubik_ServerInit(globalConfPtr->myHost, htons(AFSCONF_BUDBPORT),
559                                globalConfPtr->serverList,
560                                dbNamePtr,  /* name prefix */
561                                &BU_dbase);
562     }
563
564     if (code) {
565         LogError(code, "Ubik init failed\n");
566         afs_com_err(whoami, code, "Ubik init failed");
567         ERROR(code);
568     }
569
570     afsconf_BuildServerSecurityObjects(BU_conf, &securityClasses, &numClasses);
571
572     tservice =
573         rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase",
574                           securityClasses, numClasses, BUDB_ExecuteRequest);
575
576     if (tservice == (struct rx_service *)0) {
577         LogError(0, "Could not create backup database rx service\n");
578         printf("Could not create backup database rx service\n");
579         BUDB_EXIT(3);
580     }
581     rx_SetMinProcs(tservice, 1);
582     rx_SetMaxProcs(tservice, lwps);
583     rx_SetStackSize(tservice, 10000);
584
585     /* allow super users to manage RX statistics */
586     rx_SetRxStatUserOk(BU_rxstat_userok);
587
588     /* misc. initialization */
589
590     /* database dump synchronization */
591     memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
592     Lock_Init(&dumpSyncPtr->ds_lock);
593
594     rx_StartServer(0);          /* start handling requests */
595
596     code = InitProcs();
597     if (code)
598         ERROR(code);
599
600
601     currentTime = time(0);
602     LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));
603
604     rx_ServerProc(NULL);                /* donate this LWP */
605
606   error_exit:
607     osi_audit(BUDB_FinishEvent, code, AUD_END);
608     return (code);
609 }
610
611 void
612 consistencyCheckDb(void)
613 {
614     /* do consistency checks on structure sizes */
615     if ((sizeof(struct htBlock) > BLOCKSIZE)
616         || (sizeof(struct vfBlock) > BLOCKSIZE)
617         || (sizeof(struct viBlock) > BLOCKSIZE)
618         || (sizeof(struct dBlock) > BLOCKSIZE)
619         || (sizeof(struct tBlock) > BLOCKSIZE)
620         ) {
621         fprintf(stderr, "Block layout error!\n");
622         BUDB_EXIT(99);
623     }
624 }
625
626 void
627 LogDebug(int level, char *fmt, ... )
628 {
629     if (debugging >= level) {
630         va_list ap;
631         va_start(ap, fmt);
632         vFSLog(fmt, ap);
633         va_end(ap);
634     }
635 }
636
637 void
638 Log(char *fmt, ...)
639 {
640     va_list ap;
641
642     va_start(ap, fmt);
643     vFSLog(fmt, ap);
644     va_end(ap);
645 }
646
647 void
648 LogError(long code, char *fmt, ... )
649 {
650     va_list ap;
651     int len;
652     char buffer[1024];
653
654     va_start(ap, fmt);
655     len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
656     va_end(ap);
657     if (len >= 1024) {
658         len = 1023;
659         buffer[1023] = '\0';
660     }
661     /* Be consistent with (unintentional?) historic behavior. */
662     if (code) {
663         FSLog("%s: %s\n", afs_error_table_name(code), afs_error_message(code));
664         WriteLogBuffer(buffer, len);
665     } else {
666         FSLog("%s", buffer);
667     }
668 }