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