Update dmapi test suite, add Makefiles, remove Conscript files.
[xfstests-dev.git] / dmapi / src / sample_hsm / migin.c
1 /*
2  * Master migration daemon
3  *
4  * The master migration daemon waits for events on a file and
5  * spawns a child process to handle the event
6  *
7  * This code was written by Peter Lawthers, and placed in the public
8  * domain for use by DMAPI implementors and app writers.
9  *
10  * Standard disclaimer:
11  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND
12  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
15  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
16  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
17  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
19  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
20  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
21  * SUCH DAMAGE.
22  */
23
24 #include <sys/types.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <sys/wait.h>
28
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <signal.h>
33
34 #include <lib/hsm.h>
35
36 extern char     *optarg;
37 extern int       optind, optopt, opterr;
38 extern int       errno;
39 char            *Progname;
40 int              Verbose;
41
42 extern int       setup_dmapi(dm_sessid_t *);
43 extern void      err_msg(char *, ...);
44 extern void      errno_msg(char *, ...);
45
46 void             event_loop(dm_sessid_t);
47 int              set_events(dm_sessid_t, void *, size_t);
48 int              mk_daemon(char *);
49 void             spawn_kid(dm_sessid_t, dm_token_t, char *);
50 void             migin_exit(int);
51 void             usage(char *);
52
53
54 void
55 usage(
56         char *prog)
57 {
58         fprintf(stderr, "Usage: %s ", prog);
59         fprintf(stderr, " <-v verbose> ");
60         fprintf(stderr, " <-l logfile> ");
61         fprintf(stderr, "filesystem \n");
62 }
63
64
65 int
66 main(
67         int     argc, 
68         char    *argv[])
69 {
70         
71         int              c;
72         int              error;
73         char            *fsname, *logfile;
74         dm_sessid_t      sid;
75         void            *fs_hanp;
76         size_t           fs_hlen;
77
78
79         Progname  = argv[0];
80         fsname  = NULL;
81         logfile = NULL;
82
83         while ((c = getopt(argc, argv, "vl:")) != EOF) {
84                 switch (c) {
85                 case 'v':
86                         Verbose = 1;
87                         break;
88                 case 'l':
89                         logfile = optarg;
90                         break;
91                 case '?':
92                 default:
93                         usage(Progname);
94                         exit(1);
95                 }
96         }
97         if (optind >= argc) {
98                 usage(Progname);
99                 exit(1);
100         }
101         fsname = argv[optind];
102         if (fsname == NULL) {
103                 usage(Progname);
104                 exit(1);
105         }
106         /*
107          * If no logfile name is specified, we'll just send
108          * all output to some file in /tmp
109          */
110         if (logfile == NULL)
111                 logfile = LOG_DEFAULT;
112          
113
114         /*
115          * Now we have our filesystem name and possibly a size threshold
116          * to look for. Init the dmapi, and get a filesystem handle so
117          * we can set up our events
118          */
119         error = setup_dmapi(&sid);
120         if (error) 
121                 exit(1);
122         
123         if (dm_path_to_fshandle(fsname, &fs_hanp, &fs_hlen) == -1) {
124                 errno_msg("Can't get filesystem handle");
125                 exit(1);
126         }
127
128         /*
129          * Turn ourselves into a daemon
130          */
131         error = mk_daemon(logfile);
132         if (error) 
133                 exit(1);
134         
135
136         /*
137          * Set the event disposition so that our session will receive 
138          * the managed region events (read, write, and truncate)
139          */
140         error = set_events(sid, fs_hanp, fs_hlen);
141         if (error) 
142                 exit(1);
143         
144
145         /*
146          * Now wait forever for messages, spawning kids to
147          * do the actual work
148          */
149         event_loop(sid);
150         return(0);
151 }
152
153 /*
154  * Main event loop processing
155  */
156 void
157 event_loop(
158         dm_sessid_t     sid)
159 {
160         void            *msgbuf;
161         size_t           bufsize, rlen;
162         int              error;
163         dm_eventmsg_t   *msg;
164
165         /*
166          * We take a swag at a buffer size. If it's wrong, we can
167          * always resize it
168          */
169         bufsize = sizeof(dm_eventmsg_t) + sizeof(dm_data_event_t) + HANDLE_LEN;
170         bufsize *= 16;
171         msgbuf  = (void *)malloc(bufsize);
172         if (msgbuf == NULL) {
173                 err_msg("Can't allocate memory for buffer");
174                 goto out;
175         }
176
177         for (;;) {      
178                 error = dm_get_events(sid, ALL_AVAIL_MSGS, DM_EV_WAIT, bufsize,
179                                         msgbuf, &rlen);
180                 if (error == -1) {
181                         if (errno == E2BIG) {
182                                 free(msgbuf);
183                                 msgbuf = (void *)malloc(rlen);
184                                 if (msgbuf == NULL) {
185                                         err_msg("Can't resize msg buffer");
186                                         goto out;
187                                 }
188                                 continue;
189                         }
190                         errno_msg("Error getting events from DMAPI");
191                         goto out;
192                 }
193
194                 /*
195                  * Walk thru the message buffer, pull out each individual
196                  * message, and dispatch the messages to child processes
197                  * with the sid, token, and data. The children will
198                  * respond to the events.
199                  */
200                 msg = (dm_eventmsg_t *)msgbuf;
201                 while (msg != NULL ) {
202                         if (Verbose) {
203                                 fprintf(stderr, "Received %s, token %d\n",
204                                     (msg->ev_type == DM_EVENT_READ ? "read" : 
205                                     (msg->ev_type == DM_EVENT_WRITE ? "write" : "trunc")), msg->ev_token);
206                         }
207                         switch (msg->ev_type) {
208
209                         case DM_EVENT_READ:
210                                 spawn_kid(sid, msg->ev_token, RESTORE_FILE);
211                                 break;
212
213                         case DM_EVENT_WRITE:
214                         case DM_EVENT_TRUNCATE:
215                                 spawn_kid(sid, msg->ev_token, INVAL_FILE);
216                                 break;
217
218                         default:
219                                 err_msg("Invalid msg type %d\n", msg->ev_type);
220                                 break;
221                         }
222                         msg = DM_STEP_TO_NEXT(msg, dm_eventmsg_t *);
223                 }
224         }
225 out:
226         if (msgbuf != NULL)
227                 free(msgbuf);
228
229         migin_exit(0);
230 }
231
232 /*
233  * Fork and exec our worker bee to work on  the file. If 
234  * there is any error in fork/exec'ing the file, we have to
235  * supply the error return to the event. Once the child gets
236  * started, he/she/it will respond to the event for us.
237  */
238 void
239 spawn_kid(
240         dm_sessid_t      sid,
241         dm_token_t       token,
242         char            *action)
243 {
244         pid_t   pid;
245         char    sidbuf[sizeof(dm_sessid_t)];
246         char    tokenbuf[sizeof(dm_token_t)];
247
248         pid = fork();
249         if (pid == 0) {
250                 /*
251                  * We're in the child. Try and exec the worker bee
252                  */
253                 sprintf(sidbuf, "%d", sid);
254                 sprintf(tokenbuf, "%d", token);
255                 if (Verbose) {
256                         fprintf(stderr, "execl(%s, %s, %s, -s, %s, -t, %s, 0)\n",
257                                 WORKER_BEE, WORKER_BEE, action, sidbuf,
258                                 tokenbuf);
259                 }
260                 if (execl(WORKER_BEE, WORKER_BEE, action, "-s", sidbuf, 
261                         "-t", tokenbuf, NULL))
262                 {
263                         (void)dm_respond_event(sid, token, DM_RESP_ABORT, 
264                                                 errno, 0, 0);
265                         exit(1);
266                 }
267         }
268
269         if (pid < 0) {
270                 err_msg("Can't fork worker bee");
271                 (void)dm_respond_event(sid, token, DM_RESP_ABORT, errno,
272                                         0, 0);
273                 return;
274         }
275         return;
276
277 }
278
279
280 /*
281  * Set the event disposition of the managed region events
282  */
283 int
284 set_events(
285         dm_sessid_t      sid,
286         void            *fs_hanp,
287         size_t           fs_hlen)
288 {
289         dm_eventset_t   eventlist;
290
291         DMEV_ZERO(eventlist);
292         DMEV_SET(DM_EVENT_READ, eventlist);
293         DMEV_SET(DM_EVENT_WRITE, eventlist);
294         DMEV_SET(DM_EVENT_TRUNCATE, eventlist);
295
296         if (dm_set_disp(sid, fs_hanp, fs_hlen, DM_NO_TOKEN, &eventlist, 
297                         DM_EVENT_MAX) == -1) 
298         {
299                 errno_msg("Can't set event disposition");
300                 return(1);
301         }
302         return(0);
303 }
304
305
306
307
308 /*
309  * Dissassociate ourselves from our tty, and close all files
310  */
311 int
312 mk_daemon(
313         char    *logfile)
314 {
315         int                     fd;
316         int                     i;
317         struct rlimit           lim;
318         struct sigaction        act;
319
320 #ifdef NOTYET
321         if ((pid = fork()) == -1)
322                 return (-1);
323         if (pid)
324                 exit(0);
325
326         (void) setsid();
327
328         (void) chdir("/");
329
330 #endif /* NOTYET */
331         /*
332          * Determine how many open files we've got and close
333          * then all
334          */
335         if (getrlimit(RLIMIT_NOFILE, &lim) < 0 ) {
336                 errno_msg("Can't determine max number of open files");
337                 return(1);
338         }
339         for (i=0; i<lim.rlim_cur; i++)
340                 (void)close(i);
341
342         /*
343          * For error reporting, we re-direct stdout and stderr to a 
344          * logfile. 
345          */
346         if ((fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC, 0755)) < 0) {
347                 errno_msg("Can't open logfile %s", logfile);
348                 return(1);
349         }
350         (void)dup2(fd, STDOUT_FILENO);
351         (void)dup2(fd, STDERR_FILENO);
352         close(fd);
353
354         /*
355          * Set up signals so that we can wait for spawned children 
356          */
357         act.sa_handler = migin_exit;
358         act.sa_flags   = 0;
359         sigemptyset(&act.sa_mask);
360
361         (void)sigaction(SIGHUP, &act, NULL);
362         (void)sigaction(SIGINT, &act, NULL);
363         (void)sigaction(SIGQUIT, &act, NULL);
364         (void)sigaction(SIGTERM, &act, NULL);
365         (void)sigaction(SIGUSR1, &act, NULL);
366         (void)sigaction(SIGUSR1, &act, NULL);
367         (void)sigaction(SIGUSR2, &act, NULL);
368
369         return(0);
370 }
371
372 void
373 migin_exit(int x)
374 {
375         dm_sessid_t     *sidbuf, *sid;
376         void            *infobuf;
377         char            *cp;
378         u_int            nsessions, nret;
379         int              i, found, error;
380         size_t           buflen, retlen;
381
382         sidbuf  = NULL;
383         infobuf = NULL;
384         
385         /*
386          * We could try and kill off all our kids, but we're not
387          * 'Mr. Mean', so we just wait for them to die.
388          */
389         err_msg("%s: waiting for all children to die...", Progname);
390         while (wait3((int *)0, WNOHANG, (struct rusage *)0) > 0)
391                 ;
392
393         fprintf(stdout, "\n");
394
395         /*
396          * Now search for our session and try and shut it down. We
397          * could just as easily make the session ID a global, but
398          * this demonstrates how sessions can be queried
399          */
400         nsessions = 4;
401         sidbuf = (dm_sessid_t *)malloc(nsessions * sizeof(dm_sessid_t));
402         if (sidbuf == NULL) {
403                 err_msg("Can't alloc mem to shut down session");
404                 goto out;
405         }
406         error = dm_getall_sessions(nsessions, sidbuf, &nret);
407         if (error == -1) {
408                 if (errno != E2BIG) {
409                         errno_msg("Can't get list of active sessions");
410                         goto out;
411                 }
412                 free(sidbuf);
413                 nsessions = nret;
414                 sidbuf = (dm_sessid_t *)malloc(nsessions * sizeof(dm_sessid_t));
415                 if (sidbuf == NULL) {
416                         err_msg("Can't alloc mem to shut down session");
417                         goto out;
418                 }
419                 error = dm_getall_sessions(nsessions, sidbuf, &nret);
420                 if (error == -1) {
421                         errno_msg("Can't get list of active sessions");
422                         goto out;
423                 }
424         }
425
426         /*
427          * Now we have all the active sessions in our system.
428          * Query each one until we find ourselves.
429          */
430         sid    = sidbuf;
431         buflen = DM_SESSION_INFO_LEN;
432         infobuf = malloc(buflen);
433         if (infobuf == NULL) {
434                 err_msg("Can't alloc memory for session info buffer");
435                 goto out;
436         }
437
438         /*
439          * When we registered our session, we just hammered the last component
440          * of the path name, so that's all we look for here. This prevents
441          * mismatches when running at ./migin or some other such foo
442          */
443         cp = strrchr(Progname, '/');
444         if (cp)
445                 cp++;
446         else
447                 cp = Progname;
448
449
450         found = 0;
451         for (i=0; i<nret; i++) {
452                 error = dm_query_session(*sid, buflen, infobuf, &retlen);
453                 if (error == -1)
454                         continue;               /* We just punt on errors */
455
456                 if (strstr(infobuf, cp)) {
457                         found = 1;
458                         break;
459                 }
460                 sid++;
461         }
462
463         /*
464          * XXXX         FIXME           XXX
465          * 
466          *      Should do a set_disp to 0 and then drain the session
467          *      queue as well. On the SGI, we'll need to make the
468          *      filesystem handle global so that we can get at it
469          */
470
471         if (!found) {
472                 err_msg("Can't find session to shut down");
473                 goto out;
474         }
475         error = dm_destroy_session(*sid);
476         if (error == -1) {
477                 errno_msg("Can't shut down session");
478         }
479
480
481 out:
482         if (infobuf)
483                 free(infobuf);
484         if (sidbuf)
485                 free(sidbuf);
486
487         exit(0);
488 }
489