github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/juju/backups/download.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package backups 5 6 import ( 7 "fmt" 8 "io" 9 "os" 10 11 "github.com/juju/cmd" 12 "github.com/juju/errors" 13 "launchpad.net/gnuflag" 14 15 "github.com/juju/juju/state/backups" 16 ) 17 18 const downloadDoc = ` 19 "download" retrieves a backup archive file. 20 21 If --filename is not used, the archive is downloaded to a temporary 22 location and the filename is printed to stdout. 23 ` 24 25 // DownloadCommand is the sub-command for downloading a backup archive. 26 type DownloadCommand struct { 27 CommandBase 28 // Filename is where to save the downloaded archive. 29 Filename string 30 // ID is the backup ID to download. 31 ID string 32 } 33 34 // Info implements Command.Info. 35 func (c *DownloadCommand) Info() *cmd.Info { 36 return &cmd.Info{ 37 Name: "download", 38 Args: "<ID>", 39 Purpose: "get an archive file", 40 Doc: downloadDoc, 41 } 42 } 43 44 // SetFlags implements Command.SetFlags. 45 func (c *DownloadCommand) SetFlags(f *gnuflag.FlagSet) { 46 f.StringVar(&c.Filename, "filename", "", "download target") 47 } 48 49 // Init implements Command.Init. 50 func (c *DownloadCommand) Init(args []string) error { 51 if len(args) == 0 { 52 return errors.New("missing ID") 53 } 54 id, args := args[0], args[1:] 55 if err := cmd.CheckEmpty(args); err != nil { 56 return errors.Trace(err) 57 } 58 c.ID = id 59 return nil 60 } 61 62 // Run implements Command.Run. 63 func (c *DownloadCommand) Run(ctx *cmd.Context) error { 64 client, err := c.NewAPIClient() 65 if err != nil { 66 return errors.Trace(err) 67 } 68 defer client.Close() 69 70 // Download the archive. 71 resultArchive, err := client.Download(c.ID) 72 if err != nil { 73 return errors.Trace(err) 74 } 75 defer resultArchive.Close() 76 77 // Prepare the local archive. 78 filename := c.ResolveFilename() 79 archive, err := os.Create(filename) 80 if err != nil { 81 return errors.Annotate(err, "while creating local archive file") 82 } 83 defer archive.Close() 84 85 // Write out the archive. 86 _, err = io.Copy(archive, resultArchive) 87 if err != nil { 88 return errors.Annotate(err, "while creating local archive file") 89 } 90 91 // Print the local filename. 92 fmt.Fprintln(ctx.Stdout, filename) 93 return nil 94 } 95 96 // ResolveFilename returns the filename used by the command. 97 func (c *DownloadCommand) ResolveFilename() string { 98 filename := c.Filename 99 if filename == "" { 100 filename = backups.FilenamePrefix + c.ID + ".tar.gz" 101 } 102 return filename 103 }