HAMMER Utility - Fix snapshots migration for non-default directories
[dragonfly.git] / sbin / hammer / cmd_cleanup.c
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * $DragonFly: src/sbin/hammer/cmd_cleanup.c,v 1.6 2008/10/07 22:28:41 thomas Exp $
35  */
36 /*
37  * Clean up specific HAMMER filesystems or all HAMMER filesystems.
38  *
39  * If no filesystems are specified any HAMMER- or null-mounted hammer PFS's
40  * are cleaned.
41  *
42  * Each HAMMER filesystem may contain a configuration file.  If no
43  * configuration file is present one will be created with the following
44  * defaults:
45  *
46  *      snapshots 1d 60d        (0d 0d for /tmp, /var/tmp, /usr/obj)
47  *      prune     1d 5m
48  *      rebalance 1d 5m
49  *      reblock   1d 5m
50  *      recopy    30d 10m
51  *
52  * All hammer commands create and maintain cycle files in the snapshots
53  * directory.
54  *
55  * For HAMMER version 2- the configuration file is a named 'config' in
56  * the snapshots directory, which defaults to <pfs>/snapshots.
57  * For HAMMER version 3+ the configuration file is saved in filesystem
58  * meta-data. The snapshots directory defaults to /var/hammer/<pfs>
59  * (/var/hammer/root for root mount).
60  */
61
62 #include "hammer.h"
63
64 struct didpfs {
65         struct didpfs *next;
66         uuid_t          uuid;
67 };
68
69 static void do_cleanup(const char *path);
70 static void config_init(const char *path, struct hammer_ioc_config *config);
71 static void migrate_config(FILE *fp, struct hammer_ioc_config *config);
72 static void migrate_snapshots(int fd, const char *snapshots_path);
73 static void migrate_one_snapshot(int fd, const char *fpath,
74                         struct hammer_ioc_snapshot *snapshot);
75 static int strtosecs(char *ptr);
76 static const char *dividing_slash(const char *path);
77 static int check_period(const char *snapshots_path, const char *cmd, int arg1,
78                         time_t *savep);
79 static void save_period(const char *snapshots_path, const char *cmd,
80                         time_t savet);
81 static int check_softlinks(int fd, int new_config, const char *snapshots_path);
82 static void cleanup_softlinks(int fd, int new_config,
83                         const char *snapshots_path, int arg2, char *arg3);
84 static void delete_snapshots(int fd, struct hammer_ioc_snapshot *dsnapshot);
85 static int check_expired(const char *fpath, int arg2);
86
87 static int create_snapshot(const char *path, const char *snapshots_path);
88 static int cleanup_rebalance(const char *path, const char *snapshots_path,
89                         int arg1, int arg2);
90 static int cleanup_prune(const char *path, const char *snapshots_path,
91                         int arg1, int arg2, int snapshots_disabled);
92 static int cleanup_reblock(const char *path, const char *snapshots_path,
93                         int arg1, int arg2);
94 static int cleanup_recopy(const char *path, const char *snapshots_path,
95                         int arg1, int arg2);
96
97 static void runcmd(int *resp, const char *ctl, ...);
98
99 /*
100  * WARNING: Do not make the SNAPSHOTS_BASE "/var/snapshots" because
101  * it will interfere with the older HAMMER VERS < 3 snapshots directory
102  * for the /var PFS.
103  */
104 #define SNAPSHOTS_BASE  "/var/hammer"   /* HAMMER VERS >= 3 */
105 #define WS      " \t\r\n"
106
107 struct didpfs *FirstPFS;
108
109 void
110 hammer_cmd_cleanup(char **av, int ac)
111 {
112         char *fstype, *fs, *path;
113         struct statfs *stfsbuf;
114         int mntsize, i;
115
116         tzset();
117         if (ac == 0) {
118                 mntsize = getmntinfo(&stfsbuf, MNT_NOWAIT);
119                 if (mntsize > 0) {
120                         for (i=0; i < mntsize; i++) {
121                                 /*
122                                  * We will cleanup in the case fstype is hammer.
123                                  * If we have null-mounted PFS, we check the
124                                  * mount source. If it looks like a PFS, we
125                                  * proceed to cleanup also.
126                                  */
127                                 fstype = stfsbuf[i].f_fstypename;
128                                 fs = stfsbuf[i].f_mntfromname;
129                                 if ((strcmp(fstype, "hammer") == 0) ||
130                                     ((strcmp(fstype, "null") == 0) &&
131                                      (strstr(fs, "/@@0x") != NULL ||
132                                       strstr(fs, "/@@-1") != NULL))) {
133                                         path = stfsbuf[i].f_mntonname;
134                                         do_cleanup(path);
135                                 }
136                         }
137                 }
138
139         } else {
140                 while (ac) {
141                         do_cleanup(*av);
142                         --ac;
143                         ++av;
144                 }
145         }
146 }
147
148 static
149 void
150 do_cleanup(const char *path)
151 {
152         struct hammer_ioc_pseudofs_rw pfs;
153         struct hammer_ioc_config config;
154         struct hammer_ioc_version version;
155         union hammer_ioc_mrecord_any mrec_tmp;
156         char *snapshots_path = NULL;
157         char *config_path;
158         struct stat st;
159         char *cmd;
160         char *ptr;
161         int arg1;
162         int arg2;
163         char *arg3;
164         time_t savet;
165         char buf[256];
166         char *cbase;
167         char *cptr;
168         FILE *fp = NULL;
169         struct didpfs *didpfs;
170         int snapshots_disabled = 0;
171         int prune_warning = 0;
172         int new_config = 0;
173         int snapshots_from_pfs = 0;
174         int fd;
175         int r;
176         int found_rebal = 0;
177
178         bzero(&pfs, sizeof(pfs));
179         bzero(&mrec_tmp, sizeof(mrec_tmp));
180         pfs.ondisk = &mrec_tmp.pfs.pfsd;
181         pfs.bytes = sizeof(mrec_tmp.pfs.pfsd);
182         pfs.pfs_id = -1;
183
184         printf("cleanup %-20s -", path);
185         fd = open(path, O_RDONLY);
186         if (fd < 0) {
187                 printf(" unable to access directory: %s\n", strerror(errno));
188                 return;
189         }
190         if (ioctl(fd, HAMMERIOC_GET_PSEUDOFS, &pfs) < 0) {
191                 printf(" not a HAMMER filesystem: %s\n", strerror(errno));
192                 close(fd);
193                 return;
194         }
195         if (pfs.version != HAMMER_IOC_PSEUDOFS_VERSION) {
196                 printf(" unrecognized HAMMER version\n");
197                 close(fd);
198                 return;
199         }
200         bzero(&version, sizeof(version));
201         if (ioctl(fd, HAMMERIOC_GET_VERSION, &version) < 0) {
202                 printf(" HAMMER filesystem but couldn't retrieve version!\n");
203                 close(fd);
204                 return;
205         }
206
207         bzero(&config, sizeof(config));
208         if (version.cur_version >= 3) {
209                 if (ioctl(fd, HAMMERIOC_GET_CONFIG, &config) == 0 &&
210                     config.head.error == 0) {
211                         new_config = 1;
212                 }
213         }
214
215         /*
216          * Make sure we have not already handled this PFS.  Several nullfs
217          * mounts might alias the same PFS.
218          */
219         for (didpfs = FirstPFS; didpfs; didpfs = didpfs->next) {
220                 if (bcmp(&didpfs->uuid, &mrec_tmp.pfs.pfsd.unique_uuid, sizeof(uuid_t)) == 0) {
221                         printf(" PFS #%d already handled\n", pfs.pfs_id);
222                         close(fd);
223                         return;
224                 }
225         }
226         didpfs = malloc(sizeof(*didpfs));
227         didpfs->next = FirstPFS;
228         FirstPFS = didpfs;
229         didpfs->uuid = mrec_tmp.pfs.pfsd.unique_uuid;
230
231         /*
232          * Calculate the old snapshots directory for HAMMER VERSION < 3
233          *
234          * If the directory is explicitly specified in the PFS config
235          * we flag it and will not migrate it later.
236          */
237         if (mrec_tmp.pfs.pfsd.snapshots[0] == '/') {
238                 asprintf(&snapshots_path, "%s", mrec_tmp.pfs.pfsd.snapshots);
239                 snapshots_from_pfs = 1;
240         } else if (mrec_tmp.pfs.pfsd.snapshots[0]) {
241                 printf(" WARNING: pfs-slave's snapshots dir is not absolute\n");
242                 close(fd);
243                 return;
244         } else if (mrec_tmp.pfs.pfsd.mirror_flags & HAMMER_PFSD_SLAVE) {
245                 if (version.cur_version < 3) {
246                         printf(" WARNING: must configure snapshot dir for PFS slave\n");
247                         printf("\tWe suggest <fs>/var/slaves/<name> where "
248                                "<fs> is the base HAMMER fs\n");
249                         printf("\tcontaining the slave\n");
250                         close(fd);
251                         return;
252                 }
253         } else {
254                 asprintf(&snapshots_path,
255                          "%s%ssnapshots", path, dividing_slash(path));
256         }
257
258         /*
259          * Check for old-style config file
260          */
261         if (snapshots_path) {
262                 asprintf(&config_path, "%s/config", snapshots_path);
263                 fp = fopen(config_path, "r");
264         }
265
266         /*
267          * Handle upgrades to hammer version 3, move the config
268          * file into meta-data.
269          *
270          * For the old config read the file into the config structure,
271          * we will parse it out of the config structure regardless.
272          */
273         if (version.cur_version >= 3) {
274                 if (fp) {
275                         printf("(migrating) ");
276                         fflush(stdout);
277                         migrate_config(fp, &config);
278                         migrate_snapshots(fd, snapshots_path);
279                         fclose(fp);
280                         if (ioctl(fd, HAMMERIOC_SET_CONFIG, &config) < 0) {
281                                 printf(" cannot init meta-data config!\n");
282                                 close(fd);
283                                 return;
284                         }
285                         remove(config_path);
286                 } else if (new_config == 0) {
287                         config_init(path, &config);
288                         if (ioctl(fd, HAMMERIOC_SET_CONFIG, &config) < 0) {
289                                 printf(" cannot init meta-data config!\n");
290                                 close(fd);
291                                 return;
292                         }
293                 }
294                 new_config = 1;
295         } else {
296                 /*
297                  * Create missing snapshots directory for HAMMER VERSION < 3
298                  */
299                 if (stat(snapshots_path, &st) < 0) {
300                         if (mkdir(snapshots_path, 0755) != 0) {
301                                 free(snapshots_path);
302                                 printf(" unable to create snapshot dir \"%s\": %s\n",
303                                         snapshots_path, strerror(errno));
304                                 close(fd);
305                                 return;
306                         }
307                 }
308
309                 /*
310                  *  Create missing config file for HAMMER VERSION < 3
311                  */
312                 if (fp == NULL) {
313                         config_init(path, &config);
314                         fp = fopen(config_path, "w");
315                         if (fp) {
316                                 fwrite(config.config.text, 1,
317                                         strlen(config.config.text), fp);
318                                 fclose(fp);
319                         }
320                 } else {
321                         migrate_config(fp, &config);
322                         fclose(fp);
323                 }
324         }
325
326         /*
327          * If snapshots_from_pfs is not set we calculate the new snapshots
328          * directory default (in /var) for HAMMER VERSION >= 3 and migrate
329          * the old snapshots directory over.
330          *
331          * People who have set an explicit snapshots directory will have
332          * to migrate the data manually into /var/hammer, or not bother at
333          * all.  People running slaves may wish to migrate it and then
334          * clear the snapshots specification in the PFS config for the
335          * slave.
336          */
337         if (new_config && snapshots_from_pfs == 0) {
338                 char *npath;
339
340                 assert(path[0] == '/');
341                 if (strcmp(path, "/") == 0)
342                         asprintf(&npath, "%s/root", SNAPSHOTS_BASE);
343                 else
344                         asprintf(&npath, "%s/%s", SNAPSHOTS_BASE, path + 1);
345                 if (snapshots_path) {
346                         if (stat(npath, &st) < 0 && errno == ENOENT) {
347                                 if (stat(snapshots_path, &st) < 0 && errno == ENOENT) {
348                                         printf(" HAMMER UPGRADE: Creating snapshots\n"
349                                                "\tCreating snapshots in %s\n",
350                                                npath);
351                                         runcmd(&r, "mkdir -p %s", npath);
352                                 } else {
353                                         printf(" HAMMER UPGRADE: Moving snapshots\n"
354                                                "\tMoving snapshots from %s to %s\n",
355                                                snapshots_path, npath);
356                                         runcmd(&r, "mkdir -p %s", npath);
357                                         runcmd(&r, "cpdup %s %s", snapshots_path, npath);
358                                         if (r != 0) {
359                                     printf("Unable to move snapshots directory!\n");
360                                     printf("Please fix this critical error.\n");
361                                     printf("Aborting cleanup of %s\n", path);
362                                                 close(fd);
363                                                 return;
364                                         }
365                                         runcmd(&r, "rm -rf %s", snapshots_path);
366                                 }
367                         }
368                         free(snapshots_path);
369                 } else if (stat(npath, &st) < 0 && errno == ENOENT) {
370                         runcmd(&r, "mkdir -p %s", npath);
371                 }
372                 snapshots_path = npath;
373         }
374
375         /*
376          * Lock the PFS.  fd is the base directory of the mounted PFS.
377          */
378         if (flock(fd, LOCK_EX|LOCK_NB) == -1) {
379                 if (errno == EWOULDBLOCK)
380                         printf(" PFS #%d locked by other process\n", pfs.pfs_id);
381                 else
382                         printf(" can not lock %s: %s\n", config_path, strerror(errno));
383                 close(fd);
384                 return;
385         }
386
387         printf(" handle PFS #%d using %s\n", pfs.pfs_id, snapshots_path);
388
389         /*
390          * Process the config file
391          */
392         cbase = config.config.text;
393
394         while ((cptr = strchr(cbase, '\n')) != NULL) {
395                 bcopy(cbase, buf, cptr - cbase);
396                 buf[cptr - cbase] = 0;
397                 cbase = cptr + 1;
398
399                 cmd = strtok(buf, WS);
400                 if (cmd == NULL || cmd[0] == '#')
401                         continue;
402
403                 arg1 = 0;
404                 arg2 = 0;
405                 arg3 = NULL;
406                 if ((ptr = strtok(NULL, WS)) != NULL) {
407                         arg1 = strtosecs(ptr);
408                         if ((ptr = strtok(NULL, WS)) != NULL) {
409                                 arg2 = strtosecs(ptr);
410                                 arg3 = strtok(NULL, WS);
411                         }
412                 }
413
414                 printf("%20s - ", cmd);
415                 fflush(stdout);
416
417                 r = 1;
418                 if (strcmp(cmd, "snapshots") == 0) {
419                         if (arg1 == 0) {
420                                 if (arg2 &&
421                                     check_softlinks(fd, new_config,
422                                                     snapshots_path)) {
423                                         printf("only removing old snapshots\n");
424                                         prune_warning = 1;
425                                         cleanup_softlinks(fd, new_config,
426                                                           snapshots_path,
427                                                           arg2, arg3);
428                                 } else {
429                                         printf("disabled\n");
430                                         snapshots_disabled = 1;
431                                 }
432                         } else
433                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
434                                 printf("run\n");
435                                 cleanup_softlinks(fd, new_config,
436                                                   snapshots_path,
437                                                   arg2, arg3);
438                                 r = create_snapshot(path, snapshots_path);
439                         } else {
440                                 printf("skip\n");
441                         }
442                 } else if (arg1 == 0) {
443                         /*
444                          * The commands following this check can't handle
445                          * a period of 0, so call the feature disabled and
446                          * ignore the directive.
447                          */
448                         printf("disabled\n");
449                 } else if (strcmp(cmd, "prune") == 0) {
450                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
451                                 if (prune_warning) {
452                                         printf("run - WARNING snapshot "
453                                                "softlinks present "
454                                                "but snapshots disabled\n");
455                                 } else {
456                                         printf("run\n");
457                                 }
458                                 r = cleanup_prune(path, snapshots_path,
459                                               arg1, arg2, snapshots_disabled);
460                         } else {
461                                 printf("skip\n");
462                         }
463                 } else if (strcmp(cmd, "rebalance") == 0) {
464                         found_rebal = 1;
465                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
466                                 printf("run");
467                                 fflush(stdout);
468                                 if (VerboseOpt)
469                                         printf("\n");
470                                 r = cleanup_rebalance(path, snapshots_path,
471                                                 arg1, arg2);
472                         } else {
473                                 printf("skip\n");
474                         }
475                 } else if (strcmp(cmd, "reblock") == 0) {
476                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
477                                 printf("run");
478                                 fflush(stdout);
479                                 if (VerboseOpt)
480                                         printf("\n");
481                                 r = cleanup_reblock(path, snapshots_path,
482                                                 arg1, arg2);
483                         } else {
484                                 printf("skip\n");
485                         }
486                 } else if (strcmp(cmd, "recopy") == 0) {
487                         if (check_period(snapshots_path, cmd, arg1, &savet)) {
488                                 printf("run");
489                                 fflush(stdout);
490                                 if (VerboseOpt)
491                                         printf("\n");
492                                 r = cleanup_recopy(path, snapshots_path,
493                                                arg1, arg2);
494                         } else {
495                                 printf("skip\n");
496                         }
497                 } else {
498                         printf("unknown directive\n");
499                         r = 1;
500                 }
501                 if (r == 0)
502                         save_period(snapshots_path, cmd, savet);
503         }
504
505         /*
506          * Add new rebalance feature if the config doesn't have it.
507          * (old style config only).
508          */
509         if (new_config == 0 && found_rebal == 0) {
510                 if ((fp = fopen(config_path, "r+")) != NULL) {
511                         fseek(fp, 0L, 2);
512                         fprintf(fp, "rebalance 1d 5m\n");
513                         fclose(fp);
514                 }
515         }
516
517         /*
518          * Cleanup, and delay a little
519          */
520         close(fd);
521         usleep(1000);
522 }
523
524 /*
525  * Initialize new config data (new or old style)
526  */
527 static void
528 config_init(const char *path, struct hammer_ioc_config *config)
529 {
530         const char *snapshots;
531
532         if (strcmp(path, "/tmp") == 0 ||
533             strcmp(path, "/var/tmp") == 0 ||
534             strcmp(path, "/usr/obj") == 0) {
535                 snapshots = "snapshots 0d 0d\n";
536         } else {
537                 snapshots = "snapshots 1d 60d\n";
538         }
539         bzero(config->config.text, sizeof(config->config.text));
540         snprintf(config->config.text, sizeof(config->config.text) - 1, "%s%s",
541                 snapshots,
542                 "prune     1d 5m\n"
543                 "rebalance 1d 5m\n"
544                 "reblock   1d 5m\n"
545                 "recopy    30d 10m\n");
546 }
547
548 /*
549  * Migrate configuration data from the old snapshots/config
550  * file to the new meta-data format.
551  */
552 static void
553 migrate_config(FILE *fp, struct hammer_ioc_config *config)
554 {
555         int n;
556
557         n = fread(config->config.text, 1, sizeof(config->config.text) - 1, fp);
558         if (n >= 0)
559                 bzero(config->config.text + n, sizeof(config->config.text) - n);
560 }
561
562 /*
563  * Migrate snapshot softlinks in the snapshots directory to the
564  * new meta-data format.  The softlinks are left intact, but
565  * this way the pruning code won't lose track of them if you
566  * happen to blow away the snapshots directory.
567  */
568 static void
569 migrate_snapshots(int fd, const char *snapshots_path)
570 {
571         struct hammer_ioc_snapshot snapshot;
572         struct dirent *den;
573         struct stat st;
574         DIR *dir;
575         char *fpath;
576
577         bzero(&snapshot, sizeof(snapshot));
578
579         if ((dir = opendir(snapshots_path)) != NULL) {
580                 while ((den = readdir(dir)) != NULL) {
581                         if (den->d_name[0] == '.')
582                                 continue;
583                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
584                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode)) {
585                                 migrate_one_snapshot(fd, fpath, &snapshot);
586                         }
587                         free(fpath);
588                 }
589                 closedir(dir);
590         }
591         migrate_one_snapshot(fd, NULL, &snapshot);
592
593 }
594
595 /*
596  * Migrate a single snapshot.  If fpath is NULL the ioctl is flushed,
597  * otherwise it is flushed when it fills up.
598  */
599 static void
600 migrate_one_snapshot(int fd, const char *fpath,
601                      struct hammer_ioc_snapshot *snapshot)
602 {
603         if (fpath) {
604                 struct hammer_snapshot_data *snap;
605                 struct tm tm;
606                 time_t t;
607                 int year;
608                 int month;
609                 int day = 0;
610                 int hour = 0;
611                 int minute = 0;
612                 int r;
613                 char linkbuf[1024];
614                 const char *ptr;
615                 hammer_tid_t tid;
616
617                 t = (time_t)-1;
618                 tid = (hammer_tid_t)(int64_t)-1;
619
620                 /* fpath may contain directory components */
621                 if ((ptr = strrchr(fpath, '/')) != NULL)
622                         ++ptr;
623                 else
624                         ptr = fpath;
625                 while (*ptr && *ptr != '-' && *ptr != '.')
626                         ++ptr;
627                 if (*ptr)
628                         ++ptr;
629                 r = sscanf(ptr, "%4d%2d%2d-%2d%2d",
630                            &year, &month, &day, &hour, &minute);
631
632                 if (r >= 3) {
633                         bzero(&tm, sizeof(tm));
634                         tm.tm_isdst = -1;
635                         tm.tm_min = minute;
636                         tm.tm_hour = hour;
637                         tm.tm_mday = day;
638                         tm.tm_mon = month - 1;
639                         tm.tm_year = year - 1900;
640                         t = mktime(&tm);
641                 }
642                 bzero(linkbuf, sizeof(linkbuf));
643                 if (readlink(fpath, linkbuf, sizeof(linkbuf) - 1) > 0 &&
644                     (ptr = strrchr(linkbuf, '@')) != NULL &&
645                     ptr > linkbuf && ptr[-1] == '@') {
646                         tid = strtoull(ptr + 1, NULL, 16);
647                 }
648                 if (t != (time_t)-1 && tid != (hammer_tid_t)(int64_t)-1) {
649                         snap = &snapshot->snaps[snapshot->count];
650                         bzero(snap, sizeof(*snap));
651                         snap->tid = tid;
652                         snap->ts = (u_int64_t)t * 1000000ULL;
653                         snprintf(snap->label, sizeof(snap->label),
654                                  "migrated");
655                         ++snapshot->count;
656                 } else {
657                         printf("    non-canonical snapshot softlink: %s->%s\n",
658                                fpath, linkbuf);
659                 }
660         }
661
662         if ((fpath == NULL && snapshot->count) ||
663             snapshot->count == HAMMER_SNAPS_PER_IOCTL) {
664                 printf(" (%d snapshots)", snapshot->count);
665 again:
666                 if (ioctl(fd, HAMMERIOC_ADD_SNAPSHOT, snapshot) < 0) {
667                         printf("    Ioctl to migrate snapshots failed: %s\n",
668                                strerror(errno));
669                 } else if (snapshot->head.error == EALREADY) {
670                         ++snapshot->index;
671                         goto again;
672                 } else if (snapshot->head.error) {
673                         printf("    Ioctl to migrate snapshots failed: %s\n",
674                                strerror(snapshot->head.error));
675                 }
676                 printf("index %d\n", snapshot->index);
677                 snapshot->index = 0;
678                 snapshot->count = 0;
679                 snapshot->head.error = 0;
680         }
681 }
682
683 static
684 int
685 strtosecs(char *ptr)
686 {
687         int val;
688
689         val = strtol(ptr, &ptr, 0);
690         switch(*ptr) {
691         case 'd':
692                 val *= 24;
693                 /* fall through */
694         case 'h':
695                 val *= 60;
696                 /* fall through */
697         case 'm':
698                 val *= 60;
699                 /* fall through */
700         case 's':
701                 break;
702         default:
703                 errx(1, "illegal suffix converting %s\n", ptr);
704                 break;
705         }
706         return(val);
707 }
708
709 static const char *
710 dividing_slash(const char *path)
711 {
712         int len = strlen(path);
713         if (len && path[len-1] == '/')
714                 return("");
715         else
716                 return("/");
717 }
718
719 /*
720  * Check whether the desired period has elapsed since the last successful
721  * run.  The run may take a while and cross a boundary so we remember the
722  * current time_t so we can save it later on.
723  *
724  * Periods in minutes, hours, or days are assumed to have been crossed
725  * if the local time crosses a minute, hour, or day boundary regardless
726  * of how close the last operation actually was.
727  */
728 static int
729 check_period(const char *snapshots_path, const char *cmd, int arg1,
730         time_t *savep)
731 {
732         char *check_path;
733         struct tm tp1;
734         struct tm tp2;
735         FILE *fp;
736         time_t baset, lastt;
737         char buf[256];
738
739         time(savep);
740         localtime_r(savep, &tp1);
741
742         /*
743          * Retrieve the start time of the last successful operation.
744          */
745         asprintf(&check_path, "%s/.%s.period", snapshots_path, cmd);
746         fp = fopen(check_path, "r");
747         free(check_path);
748         if (fp == NULL)
749                 return(1);
750         if (fgets(buf, sizeof(buf), fp) == NULL) {
751                 fclose(fp);
752                 return(1);
753         }
754         fclose(fp);
755
756         lastt = strtol(buf, NULL, 0);
757         localtime_r(&lastt, &tp2);
758
759         /*
760          * Normalize the times.  e.g. if asked to do something on a 1-day
761          * interval the operation will be performed as soon as the day
762          * turns over relative to the previous operation, even if the previous
763          * operation ran a few seconds ago just before midnight.
764          */
765         if (arg1 % 60 == 0) {
766                 tp1.tm_sec = 0;
767                 tp2.tm_sec = 0;
768         }
769         if (arg1 % (60 * 60) == 0) {
770                 tp1.tm_min = 0;
771                 tp2.tm_min = 0;
772         }
773         if (arg1 % (24 * 60 * 60) == 0) {
774                 tp1.tm_hour = 0;
775                 tp2.tm_hour = 0;
776         }
777
778         baset = mktime(&tp1);
779         lastt = mktime(&tp2);
780
781 #if 0
782         printf("%lld vs %lld\n", (long long)(baset - lastt), (long long)arg1);
783 #endif
784
785         if ((int)(baset - lastt) >= arg1)
786                 return(1);
787         return(0);
788 }
789
790 /*
791  * Store the start time of the last successful operation.
792  */
793 static void
794 save_period(const char *snapshots_path, const char *cmd,
795                         time_t savet)
796 {
797         char *ocheck_path;
798         char *ncheck_path;
799         FILE *fp;
800
801         asprintf(&ocheck_path, "%s/.%s.period", snapshots_path, cmd);
802         asprintf(&ncheck_path, "%s/.%s.period.new", snapshots_path, cmd);
803         fp = fopen(ncheck_path, "w");
804         if (fp) {
805                 fprintf(fp, "0x%08llx\n", (long long)savet);
806                 if (fclose(fp) == 0)
807                         rename(ncheck_path, ocheck_path);
808                 remove(ncheck_path);
809         } else {
810                 fprintf(stderr, "hammer: Unable to create period-file %s: %s\n",
811                         ncheck_path, strerror(errno));
812         }
813 }
814
815 /*
816  * Simply count the number of softlinks in the snapshots dir
817  */
818 static int
819 check_softlinks(int fd, int new_config, const char *snapshots_path)
820 {
821         struct dirent *den;
822         struct stat st;
823         DIR *dir;
824         char *fpath;
825         int res = 0;
826
827         /*
828          * Old-style softlink-based snapshots
829          */
830         if ((dir = opendir(snapshots_path)) != NULL) {
831                 while ((den = readdir(dir)) != NULL) {
832                         if (den->d_name[0] == '.')
833                                 continue;
834                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
835                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode))
836                                 ++res;
837                         free(fpath);
838                 }
839                 closedir(dir);
840         }
841
842         /*
843          * New-style snapshots are stored as filesystem meta-data,
844          * count those too.
845          */
846         if (new_config) {
847                 struct hammer_ioc_snapshot snapshot;
848
849                 bzero(&snapshot, sizeof(snapshot));
850                 do {
851                         if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
852                                 err(2, "hammer cleanup: check_softlink "
853                                         "snapshot error");
854                                 /* not reached */
855                         }
856                         res += snapshot.count;
857                 } while (snapshot.head.error == 0 && snapshot.count);
858         }
859         return (res);
860 }
861
862 /*
863  * Clean up expired softlinks in the snapshots dir
864  */
865 static void
866 cleanup_softlinks(int fd, int new_config,
867                   const char *snapshots_path, int arg2, char *arg3)
868 {
869         struct dirent *den;
870         struct stat st;
871         DIR *dir;
872         char *fpath;
873         int anylink = 0;
874
875         if (arg3 != NULL && strstr(arg3, "any") != NULL)
876                 anylink = 1;
877
878         if ((dir = opendir(snapshots_path)) != NULL) {
879                 while ((den = readdir(dir)) != NULL) {
880                         if (den->d_name[0] == '.')
881                                 continue;
882                         asprintf(&fpath, "%s/%s", snapshots_path, den->d_name);
883                         if (lstat(fpath, &st) == 0 && S_ISLNK(st.st_mode) &&
884                             (anylink || strncmp(den->d_name, "snap-", 5) == 0)
885                         ) {
886                                 if (check_expired(den->d_name, arg2)) {
887                                         if (VerboseOpt) {
888                                                 printf("    expire %s\n",
889                                                         fpath);
890                                         }
891                                         remove(fpath);
892                                 }
893                         }
894                         free(fpath);
895                 }
896                 closedir(dir);
897         }
898
899         /*
900          * New-style snapshots are stored as filesystem meta-data,
901          * count those too.
902          */
903         if (new_config) {
904                 struct hammer_ioc_snapshot snapshot;
905                 struct hammer_ioc_snapshot dsnapshot;
906                 struct hammer_snapshot_data *snap;
907                 struct tm *tp;
908                 time_t t;
909                 time_t dt;
910                 char snapts[32];
911                 u_int32_t i;
912
913                 bzero(&snapshot, sizeof(snapshot));
914                 bzero(&dsnapshot, sizeof(dsnapshot));
915                 do {
916                         if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
917                                 err(2, "hammer cleanup: check_softlink "
918                                         "snapshot error");
919                                 /* not reached */
920                         }
921                         for (i = 0; i < snapshot.count; ++i) {
922                                 snap = &snapshot.snaps[i];
923                                 t = snap->ts / 1000000ULL;
924                                 dt = time(NULL) - t;
925                                 if ((int)dt > arg2 || snap->tid == 0) {
926                                         dsnapshot.snaps[dsnapshot.count++] =
927                                                 *snap;
928                                 }
929                                 if ((int)dt > arg2 && VerboseOpt) {
930                                         tp = localtime(&t);
931                                         strftime(snapts, sizeof(snapts),
932                                                  "%Y-%m-%d %H:%M:%S %Z", tp);
933                                         printf("    expire 0x%016jx %s %s\n",
934                                                (uintmax_t)snap->tid,
935                                                snapts,
936                                                snap->label);
937                                 }
938                                 if (dsnapshot.count == HAMMER_SNAPS_PER_IOCTL)
939                                         delete_snapshots(fd, &dsnapshot);
940                         }
941                 } while (snapshot.head.error == 0 && snapshot.count);
942
943                 if (dsnapshot.count)
944                         delete_snapshots(fd, &dsnapshot);
945         }
946 }
947
948 static void
949 delete_snapshots(int fd, struct hammer_ioc_snapshot *dsnapshot)
950 {
951         for (;;) {
952                 if (ioctl(fd, HAMMERIOC_DEL_SNAPSHOT, dsnapshot) < 0) {
953                         printf("    Ioctl to delete snapshots failed: %s\n",
954                                strerror(errno));
955                         break;
956                 }
957                 if (dsnapshot->head.error) {
958                         printf("    Ioctl to delete snapshots failed at "
959                                "snap=%016jx: %s\n",
960                                dsnapshot->snaps[dsnapshot->index].tid,
961                                strerror(dsnapshot->head.error));
962                         if (++dsnapshot->index < dsnapshot->count)
963                                 continue;
964                 }
965                 break;
966         }
967         dsnapshot->index = 0;
968         dsnapshot->count = 0;
969         dsnapshot->head.error = 0;
970 }
971
972 /*
973  * Take a softlink path in the form snap-yyyymmdd-hhmm and the
974  * expiration in seconds (arg2) and return non-zero if the softlink
975  * has expired.
976  */
977 static int
978 check_expired(const char *fpath, int arg2)
979 {
980         struct tm tm;
981         time_t t;
982         int year;
983         int month;
984         int day = 0;
985         int hour = 0;
986         int minute = 0;
987         int r;
988
989         while (*fpath && *fpath != '-' && *fpath != '.')
990                 ++fpath;
991         if (*fpath)
992                 ++fpath;
993
994         r = sscanf(fpath, "%4d%2d%2d-%2d%2d",
995                    &year, &month, &day, &hour, &minute);
996
997         if (r >= 3) {
998                 bzero(&tm, sizeof(tm));
999                 tm.tm_isdst = -1;
1000                 tm.tm_min = minute;
1001                 tm.tm_hour = hour;
1002                 tm.tm_mday = day;
1003                 tm.tm_mon = month - 1;
1004                 tm.tm_year = year - 1900;
1005                 t = mktime(&tm);
1006                 if (t == (time_t)-1)
1007                         return(0);
1008                 t = time(NULL) - t;
1009                 if ((int)t > arg2)
1010                         return(1);
1011         }
1012         return(0);
1013 }
1014
1015 /*
1016  * Issue a snapshot.
1017  */
1018 static int
1019 create_snapshot(const char *path, const char *snapshots_path)
1020 {
1021         int r;
1022
1023         runcmd(&r, "hammer snapshot %s %s", path, snapshots_path);
1024         return(r);
1025 }
1026
1027 static int
1028 cleanup_prune(const char *path __unused, const char *snapshots_path,
1029                   int arg1 __unused, int arg2, int snapshots_disabled)
1030 {
1031         /*
1032          * If snapshots have been disabled run prune-everything instead
1033          * of prune.
1034          */
1035         if (snapshots_disabled && arg2) {
1036                 runcmd(NULL, "hammer -c %s/.prune.cycle -t %d prune-everything %s",
1037                         snapshots_path, arg2, path);
1038         } else if (snapshots_disabled) {
1039                 runcmd(NULL, "hammer prune-everything %s", path);
1040         } else if (arg2) {
1041                 runcmd(NULL, "hammer -c %s/.prune.cycle -t %d prune %s",
1042                         snapshots_path, arg2, snapshots_path);
1043         } else {
1044                 runcmd(NULL, "hammer prune %s", snapshots_path);
1045         }
1046         return(0);
1047 }
1048
1049 static int
1050 cleanup_rebalance(const char *path, const char *snapshots_path,
1051                   int arg1 __unused, int arg2)
1052 {
1053         if (VerboseOpt == 0) {
1054                 printf(".");
1055                 fflush(stdout);
1056         }
1057
1058         runcmd(NULL,
1059                "hammer -c %s/.rebalance.cycle -t %d rebalance %s",
1060                snapshots_path, arg2, path);
1061         if (VerboseOpt == 0) {
1062                 printf(".");
1063                 fflush(stdout);
1064         }
1065         if (VerboseOpt == 0)
1066                 printf("\n");
1067         return(0);
1068 }
1069
1070 static int
1071 cleanup_reblock(const char *path, const char *snapshots_path,
1072                   int arg1 __unused, int arg2)
1073 {
1074         if (VerboseOpt == 0) {
1075                 printf(".");
1076                 fflush(stdout);
1077         }
1078
1079         /*
1080          * When reblocking the B-Tree always reblock everything in normal
1081          * mode.
1082          */
1083         runcmd(NULL,
1084                "hammer -c %s/.reblock-1.cycle -t %d reblock-btree %s",
1085                snapshots_path, arg2, path);
1086         if (VerboseOpt == 0) {
1087                 printf(".");
1088                 fflush(stdout);
1089         }
1090
1091         /*
1092          * When reblocking the inodes always reblock everything in normal
1093          * mode.
1094          */
1095         runcmd(NULL,
1096                "hammer -c %s/.reblock-2.cycle -t %d reblock-inodes %s",
1097                snapshots_path, arg2, path);
1098         if (VerboseOpt == 0) {
1099                 printf(".");
1100                 fflush(stdout);
1101         }
1102
1103         /*
1104          * When reblocking the directories always reblock everything in normal
1105          * mode.
1106          */
1107         runcmd(NULL,
1108                "hammer -c %s/.reblock-4.cycle -t %d reblock-dirs %s",
1109                snapshots_path, arg2, path);
1110         if (VerboseOpt == 0) {
1111                 printf(".");
1112                 fflush(stdout);
1113         }
1114
1115         /*
1116          * Do not reblock all the data in normal mode.
1117          */
1118         runcmd(NULL,
1119                "hammer -c %s/.reblock-3.cycle -t %d reblock-data %s 95",
1120                snapshots_path, arg2, path);
1121         if (VerboseOpt == 0)
1122                 printf("\n");
1123         return(0);
1124 }
1125
1126 static int
1127 cleanup_recopy(const char *path, const char *snapshots_path,
1128                   int arg1 __unused, int arg2)
1129 {
1130         if (VerboseOpt == 0) {
1131                 printf(".");
1132                 fflush(stdout);
1133         }
1134         runcmd(NULL,
1135                "hammer -c %s/.recopy-1.cycle -t %d reblock-btree %s",
1136                snapshots_path, arg2, path);
1137         if (VerboseOpt == 0) {
1138                 printf(".");
1139                 fflush(stdout);
1140         }
1141         runcmd(NULL,
1142                "hammer -c %s/.recopy-2.cycle -t %d reblock-inodes %s",
1143                snapshots_path, arg2, path);
1144         if (VerboseOpt == 0) {
1145                 printf(".");
1146                 fflush(stdout);
1147         }
1148         runcmd(NULL,
1149                "hammer -c %s/.recopy-4.cycle -t %d reblock-dirs %s",
1150                snapshots_path, arg2, path);
1151         if (VerboseOpt == 0) {
1152                 printf(".");
1153                 fflush(stdout);
1154         }
1155         runcmd(NULL,
1156                "hammer -c %s/.recopy-3.cycle -t %d reblock-data %s",
1157                snapshots_path, arg2, path);
1158         if (VerboseOpt == 0)
1159                 printf("\n");
1160         return(0);
1161 }
1162
1163 static
1164 void
1165 runcmd(int *resp, const char *ctl, ...)
1166 {
1167         va_list va;
1168         char *cmd;
1169         char *arg;
1170         char **av;
1171         int n;
1172         int nmax;
1173         int res;
1174         pid_t pid;
1175
1176         /*
1177          * Generate the command
1178          */
1179         va_start(va, ctl);
1180         vasprintf(&cmd, ctl, va);
1181         va_end(va);
1182         if (VerboseOpt)
1183                 printf("    %s\n", cmd);
1184
1185         /*
1186          * Break us down into arguments.  We do not just use system() here
1187          * because it blocks SIGINT and friends.
1188          */
1189         n = 0;
1190         nmax = 16;
1191         av = malloc(sizeof(char *) * nmax);
1192
1193         for (arg = strtok(cmd, WS); arg; arg = strtok(NULL, WS)) {
1194                 if (n == nmax - 1) {
1195                         nmax += 16;
1196                         av = realloc(av, sizeof(char *) * nmax);
1197                 }
1198                 av[n++] = arg;
1199         }
1200         av[n++] = NULL;
1201
1202         /*
1203          * Run the command.
1204          */
1205         RunningIoctl = 1;
1206         if ((pid = fork()) == 0) {
1207                 if (VerboseOpt < 2) {
1208                         int fd = open("/dev/null", O_RDWR);
1209                         dup2(fd, 1);
1210                         close(fd);
1211                 }
1212                 execvp(av[0], av);
1213                 _exit(127);
1214         } else if (pid < 0) {
1215                 res = 127;
1216         } else {
1217                 int status;
1218
1219                 while (waitpid(pid, &status, 0) != pid)
1220                         ;
1221                 res = WEXITSTATUS(status);
1222         }
1223         RunningIoctl = 0;
1224         if (DidInterrupt)
1225                 _exit(1);
1226
1227         free(cmd);
1228         free(av);
1229         if (resp)
1230                 *resp = res;
1231 }