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