volser: Convert command line parsing to cmd
[openafs.git] / src / volser / volmain.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
13 #include <roken.h>
14 #include <afs/opr.h>
15 #ifdef AFS_PTHREAD_ENV
16 # include <opr/lock.h>
17 #endif
18
19 #ifdef AFS_NT40_ENV
20 #include <windows.h>
21 #include <WINNT/afsevent.h>
22 #endif
23
24 #include <rx/rx_queue.h>
25 #include <afs/afsint.h>
26 #include <afs/prs_fs.h>
27 #include <afs/nfs.h>
28 #include <lwp.h>
29 #include <lock.h>
30 #include <afs/afssyscalls.h>
31 #include <afs/ihandle.h>
32 #ifdef AFS_NT40_ENV
33 #include <afs/ntops.h>
34 #endif
35 #include <afs/vnode.h>
36 #include <afs/volume.h>
37 #include <afs/partition.h>
38 #include <rx/rx.h>
39 #include <rx/rxstat.h>
40 #include <rx/rx_globals.h>
41 #include <afs/auth.h>
42 #include <afs/cellconfig.h>
43 #include <afs/keys.h>
44 #include <afs/dir.h>
45 #include <ubik.h>
46 #include <afs/audit.h>
47 #include <afs/afsutil.h>
48 #include <afs/cmd.h>
49 #include <lwp.h>
50
51 #include "volser.h"
52 #include "volint.h"
53 #include "volser_internal.h"
54
55 #define VolserVersion "2.0"
56 #define N_SECURITY_OBJECTS 3
57
58 extern struct Lock localLock;
59 char *GlobalNameHack = NULL;
60 int hackIsIn = 0;
61 afs_int32 GlobalVolCloneId, GlobalVolParentId;
62 int GlobalVolType;
63 int VolumeChanged;              /* XXXX */
64 static char busyFlags[MAXHELPERS];
65 struct volser_trans *QI_GlobalWriteTrans = 0;
66 struct afsconf_dir *tdir;
67 static afs_int32 runningCalls = 0;
68 int DoLogging = 0;
69 int debuglevel = 0;
70 #define MAXLWP 128
71 int lwps = 9;
72 int udpBufSize = 0;             /* UDP buffer size for receive */
73
74 int rxBind = 0;
75 int rxkadDisableDotCheck = 0;
76 int DoPreserveVolumeStats = 0;
77 int rxJumbograms = 0;   /* default is to not send and receive jumbograms. */
78 int rxMaxMTU = -1;
79 char *auditFileName = NULL;
80
81 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
82 afs_uint32 SHostAddrs[ADDRSPERSITE];
83
84 #define VS_EXIT(code)  {                                          \
85                           osi_audit(VS_ExitEvent, code, AUD_END); \
86                           exit(code);                             \
87                        }
88
89 static void
90 MyBeforeProc(struct rx_call *acall)
91 {
92     VTRANS_LOCK;
93     runningCalls++;
94     VTRANS_UNLOCK;
95     return;
96 }
97
98 static void
99 MyAfterProc(struct rx_call *acall, afs_int32 code)
100 {
101     VTRANS_LOCK;
102     runningCalls--;
103     VTRANS_UNLOCK;
104     return;
105 }
106
107 /* Called every GCWAKEUP seconds to try to unlock all our partitions,
108  * if we're idle and there are no active transactions
109  */
110 static void
111 TryUnlock(void)
112 {
113     /* if there are no running calls, and there are no active transactions, then
114      * it should be safe to release any partition locks we've accumulated */
115     VTRANS_LOCK;
116     if (runningCalls == 0 && TransList() == (struct volser_trans *)0) {
117         VTRANS_UNLOCK;
118         VPFullUnlock();         /* in volprocs.c */
119     } else
120         VTRANS_UNLOCK;
121 }
122
123 /* background daemon for timing out transactions */
124 static void*
125 BKGLoop(void *unused)
126 {
127     struct timeval tv;
128     int loop = 0;
129
130     afs_pthread_setname_self("vol bkg");
131     while (1) {
132         tv.tv_sec = GCWAKEUP;
133         tv.tv_usec = 0;
134 #ifdef AFS_PTHREAD_ENV
135 #ifdef AFS_NT40_ENV
136         Sleep(GCWAKEUP * 1000);
137 #else
138         select(0, 0, 0, 0, &tv);
139 #endif
140 #else
141         (void)IOMGR_Select(0, 0, 0, 0, &tv);
142 #endif
143         GCTrans();
144         TryUnlock();
145         loop++;
146         if (loop == 10) {       /* reopen log every 5 minutes */
147             loop = 0;
148             ReOpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);
149         }
150     }
151
152     return NULL;
153 }
154
155 /* Background daemon for sleeping so the volserver does not become I/O bound */
156 afs_int32 TTsleep, TTrun;
157 #ifndef AFS_PTHREAD_ENV
158 static void *
159 BKGSleep(void *unused)
160 {
161     struct volser_trans *tt;
162
163     if (TTsleep) {
164         while (1) {
165 #ifdef AFS_PTHREAD_ENV
166             sleep(TTrun);
167 #else /* AFS_PTHREAD_ENV */
168             IOMGR_Sleep(TTrun);
169 #endif
170             VTRANS_LOCK;
171             for (tt = TransList(); tt; tt = tt->next) {
172                 VTRANS_OBJ_LOCK(tt);
173                 if ((strcmp(tt->lastProcName, "DeleteVolume") == 0)
174                     || (strcmp(tt->lastProcName, "Clone") == 0)
175                     || (strcmp(tt->lastProcName, "ReClone") == 0)
176                     || (strcmp(tt->lastProcName, "Forward") == 0)
177                     || (strcmp(tt->lastProcName, "Restore") == 0)
178                     || (strcmp(tt->lastProcName, "ForwardMulti") == 0)) {
179                     VTRANS_OBJ_UNLOCK(tt);
180                     break;
181                 }
182                 VTRANS_OBJ_UNLOCK(tt);
183             }
184             if (tt) {
185                 VTRANS_UNLOCK;
186                 sleep(TTsleep);
187             } else
188                 VTRANS_UNLOCK;
189         }
190     }
191     return NULL;
192 }
193 #endif
194
195 #ifdef AFS_NT40_ENV
196 /* no volser_syscall */
197 #elif defined(AFS_SUN511_ENV)
198 int
199 volser_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
200 {
201     int err, code;
202     code = ioctl_sun_afs_syscall(28 /* AFSCALL_CALL */, a3, a4, a5, 0, 0, 0,
203                                  &err);
204     if (code) {
205         err = code;
206     }
207     return err;
208 }
209 #else
210 int
211 volser_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
212 {
213     afs_uint32 rcode;
214 #ifndef AFS_LINUX20_ENV
215     void (*old) (int);
216
217     old = signal(SIGSYS, SIG_IGN);
218 #endif
219     rcode =
220         syscall(AFS_SYSCALL /* AFS_SYSCALL */ , 28 /* AFSCALL_CALL */ , a3,
221                 a4, a5);
222 #ifndef AFS_LINUX20_ENV
223     signal(SIGSYS, old);
224 #endif
225
226     return rcode;
227 }
228 #endif
229
230
231 /* check whether caller is authorized to manage RX statistics */
232 int
233 vol_rxstat_userok(struct rx_call *call)
234 {
235     return afsconf_SuperUser(tdir, call, NULL);
236 }
237
238 /**
239  * Return true if this name is a member of the local realm.
240  */
241 static int
242 vol_IsLocalRealmMatch(void *rock, char *name, char *inst, char *cell)
243 {
244     struct afsconf_dir *dir = (struct afsconf_dir *)rock;
245     afs_int32 islocal = 0;      /* default to no */
246     int code;
247
248     code = afsconf_IsLocalRealmMatch(dir, &islocal, name, inst, cell);
249     if (code) {
250         ViceLog(0,
251                 ("Failed local realm check; code=%d, name=%s, inst=%s, cell=%s\n",
252                  code, name, inst, cell));
253     }
254     return islocal;
255 }
256
257 enum optionsList {
258     OPT_log,
259     OPT_rxbind,
260     OPT_dotted,
261     OPT_debug,
262     OPT_threads,
263     OPT_auditlog,
264     OPT_audit_interface,
265     OPT_nojumbo,
266     OPT_jumbo,
267     OPT_rxmaxmtu,
268     OPT_sleep,
269     OPT_udpsize,
270     OPT_peer,
271     OPT_process,
272     OPT_preserve_vol_stats,
273     OPT_sync,
274     OPT_syslog
275 };
276
277 static int
278 ParseArgs(int argc, char **argv) {
279     int code;
280     int optval;
281     char *optstring;
282     struct cmd_syndesc *opts;
283     char *sleepSpec;
284     char *sync_behavior;
285
286     opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);
287     cmd_AddParmAtOffset(opts, OPT_log, "-log", CMD_FLAG, CMD_OPTIONAL,
288            "log vos users");
289     cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
290            "bind only to the primary interface");
291     cmd_AddParmAtOffset(opts, OPT_dotted, "-dotted", CMD_FLAG, CMD_OPTIONAL,
292            "permit Kerberos 5 principals with dots");
293     cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE, CMD_OPTIONAL,
294            "debug level");
295     cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL,
296            "number of threads");
297     cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
298            CMD_OPTIONAL, "location of audit log");
299     cmd_AddParmAtOffset(opts, OPT_audit_interface, "-audit-interface",
300            CMD_SINGLE, CMD_OPTIONAL, "interface to use for audit logging");
301     cmd_AddParmAtOffset(opts, OPT_nojumbo, "-nojumbo", CMD_FLAG, CMD_OPTIONAL,
302             "disable jumbograms");
303     cmd_AddParmAtOffset(opts, OPT_jumbo, "-jumbo", CMD_FLAG, CMD_OPTIONAL,
304             "enable jumbograms");
305     cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
306             CMD_OPTIONAL, "maximum MTU for RX");
307     cmd_AddParmAtOffset(opts, OPT_udpsize, "-udpsize", CMD_SINGLE,
308             CMD_OPTIONAL, "size of socket buffer in bytes");
309     cmd_AddParmAtOffset(opts, OPT_udpsize, "-sleep", CMD_SINGLE,
310             CMD_OPTIONAL, "make background daemon sleep (LWP only)");
311     cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
312             CMD_OPTIONAL, "enable RX transport statistics");
313     cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
314             CMD_OPTIONAL, "enable RX RPC statistics");
315     cmd_AddParmAtOffset(opts, OPT_preserve_vol_stats, "-preserve-vol-stats", CMD_FLAG,
316             CMD_OPTIONAL, "preserve volume statistics");
317 #if !defined(AFS_NT40_ENV)
318     cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG,
319             CMD_OPTIONAL, "log to syslog");
320 #endif
321     cmd_AddParmAtOffset(opts, OPT_sync, "-sync",
322             CMD_SINGLE, CMD_OPTIONAL, "always | onclose | never");
323
324     code = cmd_Parse(argc, argv, &opts);
325
326     if (code)
327         return 1;
328
329     cmd_OptionAsFlag(opts, OPT_log, &DoLogging);
330     cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);
331     cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);
332     cmd_OptionAsFlag(opts, OPT_preserve_vol_stats, &DoPreserveVolumeStats);
333     cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
334     if (cmd_OptionPresent(opts, OPT_peer))
335         rx_enablePeerRPCStats();
336     if (cmd_OptionPresent(opts, OPT_process))
337         rx_enableProcessRPCStats();
338     if (cmd_OptionPresent(opts, OPT_nojumbo))
339         rxJumbograms = 0;
340     if (cmd_OptionPresent(opts, OPT_jumbo))
341         rxJumbograms = 1;
342 #ifndef AFS_NT40_ENV
343     if (cmd_OptionPresent(opts, OPT_syslog)) {
344         serverLogSyslog = 1;
345         cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
346     }
347 #endif
348     cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU);
349     if (cmd_OptionAsInt(opts, OPT_udpsize, &optval) == 0) {
350         if (optval < rx_GetMinUdpBufSize()) {
351             printf("Warning:udpsize %d is less than minimum %d; ignoring\n",
352                     optval, rx_GetMinUdpBufSize());
353         } else
354             udpBufSize = optval;
355     }
356     cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);
357
358     if (cmd_OptionAsString(opts, OPT_audit_interface, &optstring) == 0) {
359         if (osi_audit_interface(optstring)) {
360             printf("Invalid audit interface '%s'\n", optstring);
361             return -1;
362         }
363         free(optstring);
364         optstring = NULL;
365     }
366     if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
367         if (lwps > MAXLWP) {
368             printf("Warning: '-p %d' is too big; using %d instead\n", lwps, MAXLWP);
369             lwps = MAXLWP;
370         }
371     }
372     if (cmd_OptionAsString(opts, OPT_sleep, &sleepSpec) == 0) {
373         sscanf(sleepSpec, "%d/%d", &TTsleep, &TTrun);
374         if ((TTsleep < 0) || (TTrun <= 0)) {
375             printf("Warning: '-sleep %d/%d' is incorrect; ignoring\n",
376                     TTsleep, TTrun);
377             TTsleep = TTrun = 0;
378         }
379
380     }
381     if (cmd_OptionAsString(opts, OPT_sync, &sync_behavior) == 0) {
382         if (ih_SetSyncBehavior(sync_behavior)) {
383             printf("Invalid -sync value %s\n", sync_behavior);
384             return -1;
385         }
386     }
387
388     return 0;
389 }
390
391 #include "AFS_component_version_number.c"
392 int
393 main(int argc, char **argv)
394 {
395     afs_int32 code;
396     struct rx_securityClass **securityClasses;
397     afs_int32 numClasses;
398     struct rx_service *service;
399     int rxpackets = 100;
400     afs_uint32 host = ntohl(INADDR_ANY);
401     VolumePackageOptions opts;
402
403 #ifdef  AFS_AIX32_ENV
404     /*
405      * The following signal action for AIX is necessary so that in case of a
406      * crash (i.e. core is generated) we can include the user's data section
407      * in the core dump. Unfortunately, by default, only a partial core is
408      * generated which, in many cases, isn't too useful.
409      */
410     struct sigaction nsa;
411
412     sigemptyset(&nsa.sa_mask);
413     nsa.sa_handler = SIG_DFL;
414     nsa.sa_flags = SA_FULLDUMP;
415     sigaction(SIGABRT, &nsa, NULL);
416     sigaction(SIGSEGV, &nsa, NULL);
417 #endif
418     osi_audit_init();
419     osi_audit(VS_StartEvent, 0, AUD_END);
420
421     /* Initialize dirpaths */
422     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
423 #ifdef AFS_NT40_ENV
424         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
425 #endif
426         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
427                 argv[0]);
428         exit(2);
429     }
430
431     TTsleep = TTrun = 0;
432
433     ParseArgs(argc, argv);
434
435     if (auditFileName) {
436         osi_audit_file(auditFileName);
437         osi_audit(VS_StartEvent, 0, AUD_END);
438     }
439 #ifdef AFS_SGI_VNODE_GLUE
440     if (afs_init_kernel_config(-1) < 0) {
441         printf
442             ("Can't determine NUMA configuration, not starting volserver.\n");
443         exit(1);
444     }
445 #endif
446     InitErrTabs();
447
448 #ifdef AFS_PTHREAD_ENV
449     SetLogThreadNumProgram( rx_GetThreadNum );
450 #endif
451
452 #ifdef AFS_NT40_ENV
453     if (afs_winsockInit() < 0) {
454         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
455         printf("Volume server unable to start winsock, exiting.\n");
456         exit(1);
457     }
458 #endif
459     /* Open VolserLog and map stdout, stderr into it; VInitVolumePackage2 can
460        log, so we need to do this here */
461     OpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);
462
463     VOptDefaults(volumeServer, &opts);
464     if (VInitVolumePackage2(volumeServer, &opts)) {
465         Log("Shutting down: errors encountered initializing volume package\n");
466         exit(1);
467     }
468     /* For nuke() */
469     Lock_Init(&localLock);
470     DInit(40);
471 #ifndef AFS_PTHREAD_ENV
472     vol_PollProc = IOMGR_Poll;  /* tell vol pkg to poll io system periodically */
473 #endif
474 #ifndef AFS_NT40_ENV
475     rxi_syscallp = volser_syscall;
476 #endif
477     rx_nPackets = rxpackets;    /* set the max number of packets */
478     if (udpBufSize)
479         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
480     if (rxBind) {
481         afs_int32 ccode;
482         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
483             AFSDIR_SERVER_NETINFO_FILEPATH) {
484             char reason[1024];
485             ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
486                                           ADDRSPERSITE, reason,
487                                           AFSDIR_SERVER_NETINFO_FILEPATH,
488                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
489         } else
490         {
491             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
492         }
493         if (ccode == 1)
494             host = SHostAddrs[0];
495     }
496
497     code = rx_InitHost(host, (int)htons(AFSCONF_VOLUMEPORT));
498     if (code) {
499         fprintf(stderr, "rx init failed on socket AFSCONF_VOLUMEPORT %u\n",
500                 AFSCONF_VOLUMEPORT);
501         VS_EXIT(1);
502     }
503     if (!rxJumbograms) {
504         /* Don't allow 3.4 vos clients to send jumbograms and we don't send. */
505         rx_SetNoJumbo();
506     }
507     if (rxMaxMTU != -1) {
508         if (rx_SetMaxMTU(rxMaxMTU) != 0) {
509             fprintf(stderr, "rxMaxMTU %d is invalid\n", rxMaxMTU);
510             VS_EXIT(1);
511         }
512     }
513     rx_GetIFInfo();
514     rx_SetRxDeadTime(420);
515     memset(busyFlags, 0, sizeof(busyFlags));
516
517     SetupLogSignals();
518
519     {
520 #ifdef AFS_PTHREAD_ENV
521         pthread_t tid;
522         pthread_attr_t tattr;
523         opr_Verify(pthread_attr_init(&tattr) == 0);
524         opr_Verify(pthread_attr_setdetachstate(&tattr,
525                                                PTHREAD_CREATE_DETACHED) == 0);
526         opr_Verify(pthread_create(&tid, &tattr, BKGLoop, NULL) == 0);
527 #else
528         PROCESS pid;
529         LWP_CreateProcess(BKGLoop, 16*1024, 3, 0, "vol bkg daemon", &pid);
530         LWP_CreateProcess(BKGSleep,16*1024, 3, 0, "vol slp daemon", &pid);
531 #endif
532     }
533
534     /* Create a single security object, in this case the null security object, for unauthenticated connections, which will be used to control security on connections made to this server */
535
536     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
537     if (!tdir) {
538         Abort("volser: could not open conf files in %s\n",
539               AFSDIR_SERVER_ETC_DIRPATH);
540         VS_EXIT(1);
541     }
542
543     /* initialize audit user check */
544     osi_audit_set_user_check(tdir, vol_IsLocalRealmMatch);
545
546     afsconf_BuildServerSecurityObjects(tdir, &securityClasses, &numClasses);
547     if (securityClasses[0] == NULL)
548         Abort("rxnull_NewServerSecurityObject");
549     service =
550         rx_NewServiceHost(host, 0, VOLSERVICE_ID, "VOLSER", securityClasses,
551                           numClasses, AFSVolExecuteRequest);
552     if (service == (struct rx_service *)0)
553         Abort("rx_NewService");
554     rx_SetBeforeProc(service, MyBeforeProc);
555     rx_SetAfterProc(service, MyAfterProc);
556     rx_SetIdleDeadTime(service, 0);     /* never timeout */
557     if (lwps < 4)
558         lwps = 4;
559     rx_SetMaxProcs(service, lwps);
560 #if defined(AFS_XBSD_ENV)
561     rx_SetStackSize(service, (128 * 1024));
562 #elif defined(AFS_SGI_ENV)
563     rx_SetStackSize(service, (48 * 1024));
564 #else
565     rx_SetStackSize(service, (32 * 1024));
566 #endif
567
568     if (rxkadDisableDotCheck) {
569         rx_SetSecurityConfiguration(service, RXS_CONFIG_FLAGS,
570                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
571     }
572
573     service =
574         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses,
575                       numClasses, RXSTATS_ExecuteRequest);
576     if (service == (struct rx_service *)0)
577         Abort("rx_NewService");
578     rx_SetMinProcs(service, 2);
579     rx_SetMaxProcs(service, 4);
580
581     LogCommandLine(argc, argv, "Volserver", VolserVersion, "Starting AFS",
582                    Log);
583     if (TTsleep) {
584         Log("Will sleep %d second%s every %d second%s\n", TTsleep,
585             (TTsleep > 1) ? "s" : "", TTrun + TTsleep,
586             (TTrun + TTsleep > 1) ? "s" : "");
587     }
588
589     /* allow super users to manage RX statistics */
590     rx_SetRxStatUserOk(vol_rxstat_userok);
591
592     rx_StartServer(1);          /* Donate this process to the server process pool */
593
594     osi_audit(VS_FinishEvent, (-1), AUD_END);
595     Abort("StartServer returned?");
596     return 0; /* not reached */
597 }