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