]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/cli.py
"tahoe webopen": add --info flag, to get ?t=info
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / cli.py
1 import os.path, re, sys, fnmatch
2 from twisted.python import usage
3 from allmydata.scripts.common import BaseOptions, get_aliases
4
5 NODEURL_RE=re.compile("http://([^:]*)(:([1-9][0-9]*))?")
6
7 class VDriveOptions(BaseOptions, usage.Options):
8     optParameters = [
9         ["node-directory", "d", "~/.tahoe",
10          "Look here to find out which Tahoe node should be used for all "
11          "operations. The directory should either contain a full Tahoe node, "
12          "or a file named node.url which points to some other Tahoe node. "
13          "It should also contain a file named private/aliases which contains "
14          "the mapping from alias name to root dirnode URI."
15          ],
16         ["node-url", "u", None,
17          "URL of the tahoe node to use, a URL like \"http://127.0.0.1:3456\". "
18          "This overrides the URL found in the --node-directory ."],
19         ["dir-cap", None, None,
20          "Which dirnode URI should be used as the 'tahoe' alias."]
21         ]
22
23     def postOptions(self):
24         # compute a node-url from the existing options, put in self['node-url']
25         if self['node-directory']:
26             if sys.platform == 'win32' and self['node-directory'] == '~/.tahoe':
27                 from allmydata.windows import registry
28                 self['node-directory'] = registry.get_base_dir_path()
29             else:
30                 self['node-directory'] = os.path.expanduser(self['node-directory'])
31         if self['node-url']:
32             if (not isinstance(self['node-url'], basestring)
33                 or not NODEURL_RE.match(self['node-url'])):
34                 msg = ("--node-url is required to be a string and look like "
35                        "\"http://HOSTNAMEORADDR:PORT\", not: %r" %
36                        (self['node-url'],))
37                 raise usage.UsageError(msg)
38         else:
39             node_url_file = os.path.join(self['node-directory'], "node.url")
40             self['node-url'] = open(node_url_file, "r").read().strip()
41         if self['node-url'][-1] != "/":
42             self['node-url'] += "/"
43
44         aliases = get_aliases(self['node-directory'])
45         if self['dir-cap']:
46             aliases["tahoe"] = self['dir-cap']
47         self.aliases = aliases # maps alias name to dircap
48
49
50 class MakeDirectoryOptions(VDriveOptions):
51     def parseArgs(self, where=""):
52         self.where = where
53     longdesc = """Create a new directory, either unlinked or as a subdirectory."""
54
55 class AddAliasOptions(VDriveOptions):
56     def parseArgs(self, alias, cap):
57         self.alias = alias
58         self.cap = cap
59
60     def getSynopsis(self):
61         return "%s add-alias ALIAS DIRCAP" % (os.path.basename(sys.argv[0]),)
62
63     longdesc = """Add a new alias for an existing directory."""
64
65 class CreateAliasOptions(VDriveOptions):
66     def parseArgs(self, alias):
67         self.alias = alias
68
69     def getSynopsis(self):
70         return "%s create-alias ALIAS" % (os.path.basename(sys.argv[0]),)
71
72     longdesc = """Create a new directory and add an alias for it."""
73
74 class ListAliasOptions(VDriveOptions):
75     longdesc = """Display a table of all configured aliases."""
76
77 class ListOptions(VDriveOptions):
78     optFlags = [
79         ("long", "l", "Use long format: show file sizes, and timestamps"),
80         ("uri", "u", "Show file/directory URIs"),
81         ("readonly-uri", None, "Show readonly file/directory URIs"),
82         ("classify", "F", "Append '/' to directory names, and '*' to mutable"),
83         ("json", None, "Show the raw JSON output"),
84         ]
85     def parseArgs(self, where=""):
86         self.where = where
87
88     longdesc = """
89     List the contents of some portion of the grid.
90
91     When the -l or --long option is used, each line is shown in the
92     following format:
93
94     drwx <size> <date/time> <name in this directory>
95
96     where each of the letters on the left may be replaced by '-'.
97     If 'd' is present, it indicates that the object is a directory.
98     If the 'd' is replaced by a '?', the object type is unknown.
99     'rwx' is a Unix-like permissions mask: if the mask includes 'w',
100     then the object is writeable through its link in this directory
101     (note that the link might be replaceable even if the object is
102     not writeable through the current link).
103     The 'x' is a legacy of Unix filesystems. In Tahoe it is used
104     only to indicate that the contents of a directory can be listed.
105
106     Directories have no size, so their size field is shown as '-'.
107     Otherwise the size of the file, when known, is given in bytes.
108     The size of mutable files or unknown objects is shown as '?'.
109
110     The date/time shows when this link in the Tahoe filesystem was
111     last modified.
112     """
113
114 class GetOptions(VDriveOptions):
115     def parseArgs(self, arg1, arg2=None):
116         # tahoe get FOO |less            # write to stdout
117         # tahoe get tahoe:FOO |less      # same
118         # tahoe get FOO bar              # write to local file
119         # tahoe get tahoe:FOO bar        # same
120
121         self.from_file = arg1
122         self.to_file = arg2
123         if self.to_file == "-":
124             self.to_file = None
125
126     def getSynopsis(self):
127         return "%s get REMOTE_FILE LOCAL_FILE" % (os.path.basename(sys.argv[0]),)
128
129     longdesc = """
130     Retrieve a file from the grid and write it to the local filesystem. If
131     LOCAL_FILE is omitted or '-', the contents of the file will be written to
132     stdout."""
133
134     def getUsage(self, width=None):
135         t = VDriveOptions.getUsage(self, width)
136         t += """
137 Examples:
138  % tahoe get FOO |less            # write to stdout
139  % tahoe get tahoe:FOO |less      # same
140  % tahoe get FOO bar              # write to local file
141  % tahoe get tahoe:FOO bar        # same
142 """
143         return t
144
145 class PutOptions(VDriveOptions):
146     optFlags = [
147         ("mutable", "m", "Create a mutable file instead of an immutable one."),
148         ]
149
150     def parseArgs(self, arg1=None, arg2=None):
151         # see Examples below
152
153         if arg1 is not None and arg2 is not None:
154             self.from_file = arg1
155             self.to_file = arg2
156         elif arg1 is not None and arg2 is None:
157             self.from_file = arg1 # might be "-"
158             self.to_file = None
159         else:
160             self.from_file = None
161             self.to_file = None
162         if self.from_file == "-":
163             self.from_file = None
164
165     def getSynopsis(self):
166         return "%s put LOCAL_FILE REMOTE_FILE" % (os.path.basename(sys.argv[0]),)
167
168     longdesc = """
169     Put a file into the grid, copying its contents from the local filesystem.
170     If REMOTE_FILE is missing, upload the file but do not link it into a
171     directory; also print the new filecap to stdout. If LOCAL_FILE is missing
172     or '-', data will be copied from stdin. REMOTE_FILE is assumed to start
173     with tahoe: unless otherwise specified."""
174
175     def getUsage(self, width=None):
176         t = VDriveOptions.getUsage(self, width)
177         t += """
178 Examples:
179  % cat FILE | tahoe put                # create unlinked file from stdin
180  % cat FILE | tahoe -                  # same
181  % tahoe put bar                       # create unlinked file from local 'bar'
182  % cat FILE | tahoe put - FOO          # create tahoe:FOO from stdin
183  % tahoe put bar FOO                   # copy local 'bar' to tahoe:FOO
184  % tahoe put bar tahoe:FOO             # same
185  % tahoe put bar MUTABLE-FILE-WRITECAP # modify the mutable file in-place
186 """
187         return t
188
189 class CpOptions(VDriveOptions):
190     optFlags = [
191         ("recursive", "r", "Copy source directory recursively."),
192         ("verbose", "v", "Be noisy about what is happening."),
193         ("caps-only", None,
194          "When copying to local files, write out filecaps instead of actual "
195          "data (only useful for debugging and tree-comparison purposes)."),
196         ]
197     def parseArgs(self, *args):
198         if len(args) < 2:
199             raise usage.UsageError("cp requires at least two arguments")
200         self.sources = args[:-1]
201         self.destination = args[-1]
202     def getSynopsis(self):
203         return "Usage: tahoe [options] cp FROM.. TO"
204     longdesc = """
205     Use 'tahoe cp' to copy files between a local filesystem and a Tahoe grid.
206     Any FROM/TO arguments that begin with an alias indicate Tahoe-side
207     files or non-file arguments. Directories will be copied recursively.
208     New Tahoe-side directories will be created when necessary. Assuming that
209     you have previously set up an alias 'home' with 'tahoe create-alias home',
210     here are some examples:
211
212     tahoe cp ~/foo.txt home:  # creates tahoe-side home:foo.txt
213
214     tahoe cp ~/foo.txt /tmp/bar.txt home:  # copies two files to home:
215
216     tahoe cp ~/Pictures home:stuff/my-pictures  # copies directory recursively
217
218     You can also use a dircap as either FROM or TO target:
219
220     tahoe cp URI:DIR2-RO:j74uhg25nwdpjpacl6rkat2yhm:kav7ijeft5h7r7rxdp5bgtlt3viv32yabqajkrdykozia5544jqa/wiki.html ./   # copy Zooko's wiki page to a local file
221
222     This command still has some limitations: symlinks, special files (device
223     nodes, named pipes), and non-ASCII filenames are not handled very well.
224     Arguments should probably not have trailing slashes. 'tahoe cp' does not
225     behave as much like /bin/cp as you would wish, especially with respect to
226     trailing slashes.
227     """
228
229 class RmOptions(VDriveOptions):
230     def parseArgs(self, where):
231         self.where = where
232
233     def getSynopsis(self):
234         return "%s rm REMOTE_FILE" % (os.path.basename(sys.argv[0]),)
235
236 class MvOptions(VDriveOptions):
237     def parseArgs(self, frompath, topath):
238         self.from_file = frompath
239         self.to_file = topath
240
241     def getSynopsis(self):
242         return "%s mv FROM TO" % (os.path.basename(sys.argv[0]),)
243     longdesc = """
244     Use 'tahoe mv' to move files that are already on the grid elsewhere on
245     the grid, e.g., 'tahoe mv alias:some_file alias:new_file'.
246
247     If moving a remote file into a remote directory, you'll need to append a
248     '/' to the name of the remote directory, e.g., 'tahoe mv tahoe:file1
249     tahoe:dir/', not 'tahoe mv tahoe:file1 tahoe:dir'.
250
251     Note that it is not possible to use this command to move local files to
252     the grid -- use 'tahoe cp' for that.
253     """
254
255 class LnOptions(VDriveOptions):
256     def parseArgs(self, frompath, topath):
257         self.from_file = frompath
258         self.to_file = topath
259
260     def getSynopsis(self):
261         return "%s ln FROM TO" % (os.path.basename(sys.argv[0]),)
262
263 class BackupConfigurationError(Exception):
264     pass
265
266 class BackupOptions(VDriveOptions):
267     optFlags = [
268         ("verbose", "v", "Be noisy about what is happening."),
269         ("ignore-timestamps", None, "Do not use backupdb timestamps to decide whether a local file is unchanged."),
270         ]
271
272     vcs_patterns = ('CVS', 'RCS', 'SCCS', '.git', '.gitignore', '.cvsignore',
273                     '.svn', '.arch-ids','{arch}', '=RELEASE-ID',
274                     '=meta-update', '=update', '.bzr', '.bzrignore',
275                     '.bzrtags', '.hg', '.hgignore', '_darcs')
276
277     def __init__(self):
278         super(BackupOptions, self).__init__()
279         self['exclude'] = set()
280
281     def parseArgs(self, localdir, topath):
282         self.from_dir = localdir
283         self.to_dir = topath
284
285     def getSynopsis(Self):
286         return "%s backup FROM ALIAS:TO" % os.path.basename(sys.argv[0])
287
288     def opt_exclude(self, pattern):
289         """Ignore files matching a glob pattern. You may give multiple
290         '--exclude' options."""
291         g = pattern.strip()
292         if g:
293             exclude = self['exclude']
294             exclude.add(g)
295
296     def opt_exclude_from(self, filepath):
297         """Ignore file matching glob patterns listed in file, one per
298         line."""
299         try:
300             exclude_file = file(filepath)
301         except:
302             raise BackupConfigurationError('Error opening exclude file %r.' % filepath)
303         try:
304             for line in exclude_file:
305                 self.opt_exclude(line)
306         finally:
307             exclude_file.close()
308
309     def opt_exclude_vcs(self):
310         """Exclude files and directories used by following version control
311         systems: CVS, RCS, SCCS, Git, SVN, Arch, Bazaar(bzr), Mercurial,
312         Darcs."""
313         for pattern in self.vcs_patterns:
314             self.opt_exclude(pattern)
315
316     def filter_listdir(self, listdir):
317         """Yields non-excluded childpaths in path."""
318         exclude = self['exclude']
319         exclude_regexps = [re.compile(fnmatch.translate(pat)) for pat in exclude]
320         for filename in listdir:
321             for regexp in exclude_regexps:
322                 if regexp.match(filename):
323                     break
324             else:
325                 yield filename
326
327     longdesc = """
328     Add a versioned backup of the local FROM directory to a timestamped
329     subdirectory of the TO/Archives directory on the grid, sharing as many
330     files and directories as possible with earlier backups. Create TO/Latest
331     as a reference to the latest backup. Behaves somewhat like 'rsync -a
332     --link-dest=TO/Archives/(previous) FROM TO/Archives/(new); ln -sf
333     TO/Archives/(new) TO/Latest'."""
334
335 class WebopenOptions(VDriveOptions):
336     optFlags = [
337         ("info", "i", "Open the t=info page for the file"),
338         ]
339     def parseArgs(self, where=''):
340         self.where = where
341
342     def getSynopsis(self):
343         return "%s webopen [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
344
345     longdesc = """Open a web browser to the contents of some file or
346     directory on the grid. When run without arguments, open the Welcome
347     page."""
348
349 class ManifestOptions(VDriveOptions):
350     optFlags = [
351         ("storage-index", "s", "Only print storage index strings, not pathname+cap"),
352         ("verify-cap", None, "Only print verifycap, not pathname+cap"),
353         ("repair-cap", None, "Only print repaircap, not pathname+cap"),
354         ("raw", "r", "Display raw JSON data instead of parsed"),
355         ]
356     def parseArgs(self, where=''):
357         self.where = where
358
359     def getSynopsis(self):
360         return "%s manifest [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
361
362     longdesc = """Print a list of all files and directories reachable from
363     the given starting point."""
364
365 class StatsOptions(VDriveOptions):
366     optFlags = [
367         ("raw", "r", "Display raw JSON data instead of parsed"),
368         ]
369     def parseArgs(self, where=''):
370         self.where = where
371
372     def getSynopsis(self):
373         return "%s stats [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
374
375     longdesc = """Print statistics about of all files and directories
376     reachable from the given starting point."""
377
378 class CheckOptions(VDriveOptions):
379     optFlags = [
380         ("raw", None, "Display raw JSON data instead of parsed"),
381         ("verify", None, "Verify all hashes, instead of merely querying share presence"),
382         ("repair", None, "Automatically repair any problems found"),
383         ("add-lease", None, "Add/renew lease on all shares"),
384         ]
385     def parseArgs(self, where=''):
386         self.where = where
387
388     def getSynopsis(self):
389         return "%s check [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
390
391     longdesc = """
392     Check a single file or directory: count how many shares are available and
393     verify their hashes. Optionally repair the file if any problems were
394     found."""
395
396 class DeepCheckOptions(VDriveOptions):
397     optFlags = [
398         ("raw", None, "Display raw JSON data instead of parsed"),
399         ("verify", None, "Verify all hashes, instead of merely querying share presence"),
400         ("repair", None, "Automatically repair any problems found"),
401         ("add-lease", None, "Add/renew lease on all shares"),
402         ("verbose", "v", "Be noisy about what is happening."),
403         ]
404     def parseArgs(self, where=''):
405         self.where = where
406
407     def getSynopsis(self):
408         return "%s deep-check [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
409
410     longdesc = """
411     Check all files and directories reachable from the given starting point
412     (which must be a directory), like 'tahoe check' but for multiple files.
413     Optionally repair any problems found."""
414
415 subCommands = [
416     ["mkdir", None, MakeDirectoryOptions, "Create a new directory"],
417     ["add-alias", None, AddAliasOptions, "Add a new alias cap"],
418     ["create-alias", None, CreateAliasOptions, "Create a new alias cap"],
419     ["list-aliases", None, ListAliasOptions, "List all alias caps"],
420     ["ls", None, ListOptions, "List a directory"],
421     ["get", None, GetOptions, "Retrieve a file from the grid."],
422     ["put", None, PutOptions, "Upload a file into the grid."],
423     ["cp", None, CpOptions, "Copy one or more files."],
424     ["rm", None, RmOptions, "Unlink a file or directory on the grid."],
425     ["mv", None, MvOptions, "Move a file within the grid."],
426     ["ln", None, LnOptions, "Make an additional link to an existing file."],
427     ["backup", None, BackupOptions, "Make target dir look like local dir."],
428     ["webopen", None, WebopenOptions, "Open a web browser to a grid file or directory."],
429     ["manifest", None, ManifestOptions, "List all files/directories in a subtree"],
430     ["stats", None, StatsOptions, "Print statistics about all files/directories in a subtree"],
431     ["check", None, CheckOptions, "Check a single file or directory"],
432     ["deep-check", None, DeepCheckOptions, "Check all files/directories reachable from a starting point"],
433     ]
434
435 def mkdir(options):
436     from allmydata.scripts import tahoe_mkdir
437     rc = tahoe_mkdir.mkdir(options)
438     return rc
439
440 def add_alias(options):
441     from allmydata.scripts import tahoe_add_alias
442     rc = tahoe_add_alias.add_alias(options)
443     return rc
444
445 def create_alias(options):
446     from allmydata.scripts import tahoe_add_alias
447     rc = tahoe_add_alias.create_alias(options)
448     return rc
449
450 def list_aliases(options):
451     from allmydata.scripts import tahoe_add_alias
452     rc = tahoe_add_alias.list_aliases(options)
453     return rc
454
455 def list(options):
456     from allmydata.scripts import tahoe_ls
457     rc = tahoe_ls.list(options)
458     return rc
459
460 def get(options):
461     from allmydata.scripts import tahoe_get
462     rc = tahoe_get.get(options)
463     if rc == 0:
464         if options.to_file is None:
465             # be quiet, since the file being written to stdout should be
466             # proof enough that it worked, unless the user is unlucky
467             # enough to have picked an empty file
468             pass
469         else:
470             print >>options.stderr, "%s retrieved and written to %s" % \
471                   (options.from_file, options.to_file)
472     return rc
473
474 def put(options):
475     from allmydata.scripts import tahoe_put
476     rc = tahoe_put.put(options)
477     return rc
478
479 def cp(options):
480     from allmydata.scripts import tahoe_cp
481     rc = tahoe_cp.copy(options)
482     return rc
483
484 def rm(options):
485     from allmydata.scripts import tahoe_rm
486     rc = tahoe_rm.rm(options)
487     return rc
488
489 def mv(options):
490     from allmydata.scripts import tahoe_mv
491     rc = tahoe_mv.mv(options, mode="move")
492     return rc
493
494 def ln(options):
495     from allmydata.scripts import tahoe_mv
496     rc = tahoe_mv.mv(options, mode="link")
497     return rc
498
499 def backup(options):
500     from allmydata.scripts import tahoe_backup
501     rc = tahoe_backup.backup(options)
502     return rc
503
504 def webopen(options, opener=None):
505     from allmydata.scripts import tahoe_webopen
506     rc = tahoe_webopen.webopen(options, opener=opener)
507     return rc
508
509 def manifest(options):
510     from allmydata.scripts import tahoe_manifest
511     rc = tahoe_manifest.manifest(options)
512     return rc
513
514 def stats(options):
515     from allmydata.scripts import tahoe_manifest
516     rc = tahoe_manifest.stats(options)
517     return rc
518
519 def check(options):
520     from allmydata.scripts import tahoe_check
521     rc = tahoe_check.check(options)
522     return rc
523
524 def deepcheck(options):
525     from allmydata.scripts import tahoe_check
526     rc = tahoe_check.deepcheck(options)
527     return rc
528
529 dispatch = {
530     "mkdir": mkdir,
531     "add-alias": add_alias,
532     "create-alias": create_alias,
533     "list-aliases": list_aliases,
534     "ls": list,
535     "get": get,
536     "put": put,
537     "cp": cp,
538     "rm": rm,
539     "mv": mv,
540     "ln": ln,
541     "backup": backup,
542     "webopen": webopen,
543     "manifest": manifest,
544     "stats": stats,
545     "check": check,
546     "deep-check": deepcheck,
547     }