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