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