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