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