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