050bd4f0e88f076fd79b64167fad060763e3553f
[dragonfly.git] / sbin / hammer / cmd_snapshot.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_snapshot.c,v 1.7 2008/07/10 18:47:22 mneumann Exp $
35  */
36
37 #include "hammer.h"
38
39 #define DEFAULT_SNAPSHOT_NAME "snap-%Y%m%d-%H%M"
40
41 static void snapshot_usage(int exit_code);
42 static void snapshot_add(int fd, const char *fsym, const char *tsym,
43                 const char *label, hammer_tid_t tid);
44 static void snapshot_ls(const char *path);
45 static void snapshot_del(int fsfd, hammer_tid_t tid);
46 static char *dirpart(const char *path);
47
48 /*
49  * hammer snap <path> [<note>]
50  *
51  * Path may be a directory, softlink, or non-existent (a softlink will be
52  * created).
53  */
54 void
55 hammer_cmd_snap(char **av, int ac, int tostdout, int fsbase)
56 {
57         struct hammer_ioc_synctid synctid;
58         struct hammer_ioc_version version;
59         char *dirpath;
60         char *fsym = NULL;
61         char *tsym = NULL;
62         struct stat st;
63         char note[64];
64         int fsfd;
65
66         if (ac == 0 || ac > 2) {
67                 snapshot_usage(1);
68                 /* not reached */
69         }
70
71         if (ac == 2)
72                 snprintf(note, sizeof(note), "%s", av[1]);
73         else
74                 note[0] = 0;
75
76         /*
77          * Figure out the softlink path and directory path
78          */
79         if (stat(av[0], &st) < 0) {
80                 dirpath = dirpart(av[0]);
81                 tsym = strdup(av[0]);
82         } else if (S_ISDIR(st.st_mode)) {
83                 time_t t = time(NULL);
84                 struct tm *tp;
85                 char extbuf[64];
86
87                 tp = localtime(&t);
88                 strftime(extbuf, sizeof(extbuf), DEFAULT_SNAPSHOT_NAME, tp);
89
90                 dirpath = strdup(av[0]);
91                 asprintf(&tsym, "%s/%s", dirpath, extbuf);
92         } else {
93                 err(2, "hammer snap: File %s exists and is not a directory\n",
94                     av[0]);
95                 /* not reached */
96         }
97
98         /*
99          * Get a handle on some directory in the filesystem for the
100          * ioctl (so it is stored in the correct PFS).
101          */
102         fsfd = open(dirpath, O_RDONLY);
103         if (fsfd < 0) {
104                 err(2, "hammer snap: Cannot open directory %s\n", dirpath);
105                 /* not reached */
106         }
107
108         /*
109          * Must be at least version 3 to use this command.
110          */
111         bzero(&version, sizeof(version));
112
113         if (ioctl(fsfd, HAMMERIOC_GET_VERSION, &version) < 0) {
114                 err(2, "Unable to create snapshot");
115                 /* not reached */
116         } else if (version.cur_version < 3) {
117                 errx(2, "Unable to create snapshot: This directive requires "
118                         "you to upgrade\n"
119                         "the filesystem to version 3.  "
120                         "Use 'hammer snapshot' for legacy operation.");
121                 /* not reached */
122         }
123
124         /*
125          * Synctid to get a transaction id for the snapshot.
126          */
127         bzero(&synctid, sizeof(synctid));
128         synctid.op = HAMMER_SYNCTID_SYNC2;
129         if (ioctl(fsfd, HAMMERIOC_SYNCTID, &synctid) < 0) {
130                 err(2, "hammer snap: Synctid %s failed",
131                     dirpath);
132         }
133         if (tostdout) {
134                 if (strcmp(dirpath, ".") == 0 || strcmp(dirpath, "..") == 0) {
135                         printf("%s/@@0x%016jx\n",
136                                 dirpath, (uintmax_t)synctid.tid);
137                 } else {
138                         printf("%s@@0x%016jx\n",
139                                 dirpath, (uintmax_t)synctid.tid);
140                 }
141                 fsym = NULL;
142                 tsym = NULL;
143         }
144
145         /*
146          * Contents of the symlink being created.
147          */
148         if (fsbase) {
149                 struct statfs buf;
150
151                 if (statfs(dirpath, &buf) < 0) {
152                         err(2, "hammer snap: Cannot determine mount for %s",
153                             dirpath);
154                 }
155                 asprintf(&fsym, "%s/@@0x%016jx",
156                          buf.f_mntonname, (uintmax_t)synctid.tid);
157         } else if (strcmp(dirpath, ".") == 0 || strcmp(dirpath, "..") == 0) {
158                 asprintf(&fsym, "%s/@@0x%016jx",
159                          dirpath, (uintmax_t)synctid.tid);
160         } else {
161                 asprintf(&fsym, "%s@@0x%016jx",
162                          dirpath, (uintmax_t)synctid.tid);
163         }
164
165         /*
166          * Create the snapshot.
167          */
168         snapshot_add(fsfd, fsym, tsym, note, synctid.tid);
169         free(dirpath);
170         free(fsym);
171         free(tsym);
172 }
173
174 /*
175  * hammer snapls [<path> ...]
176  *
177  * If no arguments are specified snapshots for the PFS containing the
178  * current directory are listed.
179  */
180 void
181 hammer_cmd_snapls(char **av, int ac)
182 {
183         int i;
184
185         for (i = 0; i < ac; ++i)
186                 snapshot_ls(av[i]);
187         if (ac == 0)
188                 snapshot_ls(".");
189 }
190
191 /*
192  * hammer snaprm <path> ...
193  * hammer snaprm <transid> ...
194  * hammer snaprm <filesystem> <transid> ...
195  */
196 void
197 hammer_cmd_snaprm(char **av, int ac)
198 {
199         struct stat st;
200         char linkbuf[1024];
201         intmax_t tid;
202         int fsfd = -1;
203         int i;
204         int delete;
205         enum snaprm_mode { none_m, path_m, tid_m } mode = none_m;
206         char *dirpath;
207         char *ptr, *ptr2;
208
209         if (ac == 0) {
210                 snapshot_usage(1);
211                 /* not reached */
212         }
213
214         for (i = 0; i < ac; ++i) {
215                 if (lstat(av[i], &st) < 0) {
216                         tid = strtoull(av[i], &ptr, 16);
217                         if (*ptr) {
218                                 err(2, "hammer snaprm: not a file or tid: %s",
219                                     av[i]);
220                                 /* not reached */
221                         }
222                         if (mode == path_m) {
223                                 snapshot_usage(1);
224                                 /* not reached */
225                         }
226                         mode = tid_m;
227                         if (fsfd < 0)
228                                 fsfd = open(".", O_RDONLY);
229                         snapshot_del(fsfd, tid);
230                 } else if (S_ISDIR(st.st_mode)) {
231                         if (i != 0 || ac < 2) {
232                                 snapshot_usage(1);
233                                 /* not reached */
234                         }
235                         if (fsfd >= 0)
236                                 close(fsfd);
237                         fsfd = open(av[i], O_RDONLY);
238                         if (fsfd < 0) {
239                                 err(2, "hammer snaprm: cannot open dir %s",
240                                     av[i]);
241                                 /* not reached */
242                         }
243                         mode = tid_m;
244                 } else if (S_ISLNK(st.st_mode)) {
245                         dirpath = dirpart(av[i]);
246                         bzero(linkbuf, sizeof(linkbuf));
247                         if (readlink(av[i], linkbuf, sizeof(linkbuf) - 1) < 0) {
248                                 err(2, "hammer snaprm: cannot read softlink: "
249                                        "%s", av[i]);
250                                 /* not reached */
251                         }
252                         if (linkbuf[0] == '/') {
253                                 free(dirpath);
254                                 dirpath = dirpart(linkbuf);
255                         } else {
256                                 asprintf(&ptr, "%s/%s", dirpath, linkbuf);
257                                 free(dirpath);
258                                 dirpath = dirpart(ptr);
259                                 free(ptr);
260                         }
261
262                         if (fsfd >= 0)
263                                 close(fsfd);
264                         fsfd = open(dirpath, O_RDONLY);
265                         if (fsfd < 0) {
266                                 err(2, "hammer snaprm: cannot open dir %s",
267                                     dirpath);
268                                 /* not reached */
269                         }
270
271                         delete = 1;
272                         if (i == 0 && ac > 1) {
273                                 mode = path_m;
274                                 if (lstat(av[1], &st) < 0) {
275                                         tid = strtoull(av[1], &ptr, 16);
276                                         if (*ptr == '\0') {
277                                                 delete = 0;
278                                                 mode = tid_m;
279                                         }
280                                 }
281                         } else {
282                                 if (mode == tid_m) {
283                                         snapshot_usage(1);
284                                         /* not reached */
285                                 }
286                                 mode = path_m;
287                         }
288                         if (delete && (ptr = strrchr(linkbuf, '@')) &&
289                             ptr > linkbuf && ptr[-1] == '@' && ptr[1]) {
290                                 tid = strtoull(ptr + 1, &ptr2, 16);
291                                 if (*ptr2 == '\0') {
292                                         snapshot_del(fsfd, tid);
293                                         remove(av[i]);
294                                 }
295                         }
296                         free(dirpath);
297                 } else {
298                         err(2, "hammer snaprm: not directory or snapshot "
299                                "softlink: %s", av[i]);
300                         /* not reached */
301                 }
302         }
303         if (fsfd >= 0)
304                 close(fsfd);
305 }
306
307 /*
308  * snapshot <softlink-dir>
309  * snapshot <filesystem> <softlink-dir> [<note>]
310  */
311 void
312 hammer_cmd_snapshot(char **av, int ac)
313 {
314         const char *filesystem;
315         const char *softlink_dir;
316         char *softlink_fmt;
317         struct statfs buf;
318         struct stat st;
319         struct hammer_ioc_synctid synctid;
320         char *from;
321         char *to;
322         char *note = NULL;
323
324         if (ac == 1) {
325                 filesystem = NULL;
326                 softlink_dir = av[0];
327         } else if (ac == 2) {
328                 filesystem = av[0];
329                 softlink_dir = av[1];
330         } else if (ac == 3) {
331                 filesystem = av[0];
332                 softlink_dir = av[1];
333                 note = av[2];
334         } else {
335                 snapshot_usage(1);
336                 /* not reached */
337                 softlink_dir = NULL;
338                 filesystem = NULL;
339         }
340
341         if (stat(softlink_dir, &st) == 0) {
342                 if (!S_ISDIR(st.st_mode))
343                         err(2, "File %s already exists", softlink_dir);
344
345                 if (filesystem == NULL) {
346                         if (statfs(softlink_dir, &buf) != 0) {
347                                 err(2, "Unable to determine filesystem of %s",
348                                     softlink_dir);
349                         }
350                         filesystem = buf.f_mntonname;
351                 }
352
353                 softlink_fmt = malloc(strlen(softlink_dir) + 1 + 1 +
354                                       sizeof(DEFAULT_SNAPSHOT_NAME));
355                 if (softlink_fmt == NULL)
356                         err(2, "Failed to allocate string");
357
358                 strcpy(softlink_fmt, softlink_dir);
359                 if (softlink_fmt[strlen(softlink_fmt)-1] != '/')
360                         strcat(softlink_fmt, "/");
361                 strcat(softlink_fmt, DEFAULT_SNAPSHOT_NAME);
362         } else {
363                 softlink_fmt = strdup(softlink_dir);
364
365                 if (filesystem == NULL) {
366                         /*
367                          * strip-off last '/path' segment to get the softlink
368                          * directory, which we need to determine the filesystem
369                          * we are on.
370                          */
371                         char *pos = strrchr(softlink_fmt, '/');
372                         if (pos != NULL)
373                                 *pos = '\0';
374
375                         if (stat(softlink_fmt, &st) != 0 ||
376                             !S_ISDIR(st.st_mode)) {
377                                 err(2, "Unable to determine softlink dir %s",
378                                     softlink_fmt);
379                         }
380                         if (statfs(softlink_fmt, &buf) != 0) {
381                                 err(2, "Unable to determine filesystem of %s",
382                                     softlink_fmt);
383                         }
384                         filesystem = buf.f_mntonname;
385
386                         /* restore '/' */
387                         if (pos != NULL)
388                                 *pos = '/';
389                 }
390         }
391
392         /*
393          * Synctid
394          */
395         bzero(&synctid, sizeof(synctid));
396         synctid.op = HAMMER_SYNCTID_SYNC2;
397
398         int fd = open(filesystem, O_RDONLY);
399         if (fd < 0)
400                 err(2, "Unable to open %s", filesystem);
401         if (ioctl(fd, HAMMERIOC_SYNCTID, &synctid) < 0)
402                 err(2, "Synctid %s failed", filesystem);
403
404         asprintf(&from, "%s/@@0x%016jx", filesystem, (uintmax_t)synctid.tid);
405         if (from == NULL)
406                 err(2, "Couldn't generate string");
407
408         int sz = strlen(softlink_fmt) + 50;
409         to = malloc(sz);
410         if (to == NULL)
411                 err(2, "Failed to allocate string");
412
413         time_t t = time(NULL);
414         if (strftime(to, sz, softlink_fmt, localtime(&t)) == 0)
415                 err(2, "String buffer too small");
416
417         asprintf(&from, "%s/@@0x%016jx", filesystem, (uintmax_t)synctid.tid);
418
419         snapshot_add(fd, from, to, note, synctid.tid);
420
421         close(fd);
422         printf("%s\n", to);
423
424         free(softlink_fmt);
425         free(from);
426         free(to);
427 }
428
429 static
430 void
431 snapshot_add(int fd, const char *fsym, const char *tsym, const char *label,
432              hammer_tid_t tid)
433 {
434         struct hammer_ioc_version version;
435         struct hammer_ioc_snapshot snapshot;
436
437         bzero(&version, sizeof(version));
438         bzero(&snapshot, sizeof(snapshot));
439
440         /*
441          * For HAMMER filesystem v3+ the snapshot is recorded in meta-data.
442          */
443         if (ioctl(fd, HAMMERIOC_GET_VERSION, &version) == 0 &&
444             version.cur_version >= 3) {
445                 snapshot.index = 0;
446                 snapshot.count = 1;
447                 snapshot.snaps[0].tid = tid;
448                 snapshot.snaps[0].ts = time(NULL) * 1000000ULL;
449                 if (label) {
450                         snprintf(snapshot.snaps[0].label,
451                                  sizeof(snapshot.snaps[0].label),
452                                  "%s",
453                                  label);
454                 }
455                 if (ioctl(fd, HAMMERIOC_ADD_SNAPSHOT, &snapshot) < 0) {
456                         err(2, "Unable to create snapshot");
457                 } else if (snapshot.head.error &&
458                            snapshot.head.error != EEXIST) {
459                         errx(2, "Unable to create snapshot: %s\n",
460                                 strerror(snapshot.head.error));
461                 }
462         }
463
464         /*
465          * Create a symlink for the snapshot.  If a file exists with the same
466          * name the new symlink will replace it.
467          */
468         if (fsym && tsym) {
469                 remove(tsym);
470                 if (symlink(fsym, tsym) < 0) {
471                         err(2, "Unable to create symlink %s", tsym);
472                 }
473         }
474 }
475
476 static
477 void
478 snapshot_ls(const char *path)
479 {
480         /*struct hammer_ioc_version version;*/
481         struct hammer_ioc_info info;
482         struct hammer_ioc_snapshot snapshot;
483         struct hammer_ioc_pseudofs_rw pfs;
484         struct hammer_pseudofs_data pfs_od;
485         struct hammer_snapshot_data *snap;
486         struct tm *tp;
487         time_t t;
488         uint32_t i;
489         int fd;
490         char snapts[64];
491         char *mntpoint;
492
493         fd = open(path, O_RDONLY);
494         if (fd < 0) {
495                 err(2, "hammer snapls: cannot open %s", path);
496                 /* not reached */
497         }
498
499         bzero(&pfs, sizeof(pfs));
500         bzero(&pfs_od, sizeof(pfs_od));
501         pfs.pfs_id = -1;
502         pfs.ondisk = &pfs_od;
503         pfs.bytes = sizeof(struct hammer_pseudofs_data);
504         if (ioctl(fd, HAMMERIOC_GET_PSEUDOFS, &pfs) < 0) {
505                 err(2, "hammer snapls: cannot retrieve PFS info on %s", path);
506                 /* not reached */
507         }
508
509         bzero(&info, sizeof(info));
510         if ((ioctl(fd, HAMMERIOC_GET_INFO, &info)) < 0) {
511                 err(2, "hammer snapls: cannot retrieve HAMMER info");
512                 /* not reached */
513         }
514
515         mntpoint = libhammer_find_pfs_mount(&pfs.ondisk->unique_uuid);
516
517         printf("Snapshots on %s\tPFS #%d\n",
518             mntpoint ? mntpoint : path, pfs.pfs_id);
519         printf("Transaction ID\t\tTimestamp\t\tNote\n");
520
521         if (mntpoint)
522                 free(mntpoint);
523
524         bzero(&snapshot, sizeof(snapshot));
525         do {
526                 if (ioctl(fd, HAMMERIOC_GET_SNAPSHOT, &snapshot) < 0) {
527                         err(2, "hammer snapls: %s: not HAMMER fs or "
528                                 "version < 3", path);
529                         /* not reached */
530                 }
531                 for (i = 0; i < snapshot.count; ++i) {
532                         snap = &snapshot.snaps[i];
533
534                         t = snap->ts / 1000000ULL;
535                         tp = localtime(&t);
536                         strftime(snapts, sizeof(snapts),
537                                  "%Y-%m-%d %H:%M:%S %Z", tp);
538                         printf("0x%016jx\t%s\t%s\n",
539                                 (uintmax_t)snap->tid, snapts,
540                                 strlen(snap->label) ? snap->label : "-");
541                 }
542         } while (snapshot.head.error == 0 && snapshot.count);
543 }
544
545 static
546 void
547 snapshot_del(int fsfd, hammer_tid_t tid)
548 {
549         struct hammer_ioc_snapshot snapshot;
550         struct hammer_ioc_version version;
551
552         bzero(&version, sizeof(version));
553
554         if (ioctl(fsfd, HAMMERIOC_GET_VERSION, &version) < 0) {
555                 err(2, "hammer snaprm 0x%016jx", (uintmax_t)tid);
556         }
557         if (version.cur_version < 3) {
558                 errx(2, "hammer snaprm 0x%016jx: You must upgrade to version "
559                         " 3 to use this directive", (uintmax_t)tid);
560         }
561
562         bzero(&snapshot, sizeof(snapshot));
563         snapshot.count = 1;
564         snapshot.snaps[0].tid = tid;
565
566         /*
567          * Do not abort if we are unable to remove the meta-data.
568          */
569         if (ioctl(fsfd, HAMMERIOC_DEL_SNAPSHOT, &snapshot) < 0) {
570                 err(2, "hammer snaprm 0x%016jx",
571                       (uintmax_t)tid);
572         } else if (snapshot.head.error == ENOENT) {
573                 fprintf(stderr, "Warning: hammer snaprm 0x%016jx: "
574                                 "meta-data not found\n",
575                         (uintmax_t)tid);
576         } else if (snapshot.head.error) {
577                 fprintf(stderr, "Warning: hammer snaprm 0x%016jx: %s\n",
578                         (uintmax_t)tid, strerror(snapshot.head.error));
579         }
580 }
581
582 static
583 void
584 snapshot_usage(int exit_code)
585 {
586         fprintf(stderr,
587     "hammer snap <path> [<note>]\t\tcreate snapshot & link, points to\n"
588                                 "\t\t\t\t\tbase of PFS mount\n"
589     "hammer snaplo <path> [<note>]\t\tcreate snapshot & link, points to\n"
590                                 "\t\t\t\t\ttarget dir\n"
591     "hammer snapq <dir> [<note>]\t\tcreate snapshot, output path to stdout\n"
592     "hammer snaprm <path> ...\t\tdelete snapshots; filesystem is CWD\n"
593     "hammer snaprm <transid> ...\t\tdelete snapshots\n"
594     "hammer snaprm <filesystem> <transid> ...\tdelete snapshots\n"
595     "hammer snapls [<path> ...]\t\tlist available snapshots\n"
596     "\n"
597     "NOTE: Snapshots are created in filesystem meta-data, any directory\n"
598     "      in a HAMMER filesystem or PFS may be specified.  If the path\n"
599     "      specified does not exist this function will also create a\n"
600     "      softlink.\n"
601     "\n"
602     "      When deleting snapshots transaction ids may be directly specified\n"
603     "      or file paths to snapshot softlinks may be specified.  If a\n"
604     "      softlink is specified the softlink will also be deleted.\n"
605     "\n"
606     "NOTE: The old 'hammer snapshot [<filesystem>] <snapshot-dir>' form\n"
607     "      is still accepted but is a deprecated form.  This form will\n"
608     "      work for older hammer versions.  The new forms only work for\n"
609     "      HAMMER version 3 or later filesystems.  HAMMER can be upgraded\n"
610     "      to version 3 in-place.\n"
611         );
612         exit(exit_code);
613 }
614
615 static
616 char *
617 dirpart(const char *path)
618 {
619         const char *ptr;
620         char *res;
621
622         ptr = strrchr(path, '/');
623         if (ptr) {
624                 while (ptr > path && ptr[-1] == '/')
625                         --ptr;
626                 if (ptr == path)
627                         ptr = NULL;
628         }
629         if (ptr == NULL) {
630                 path = ".";
631                 ptr = path + 1;
632         }
633         res = malloc(ptr - path + 1);
634         bcopy(path, res, ptr - path);
635         res[ptr - path] = 0;
636         return(res);
637 }