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