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