github.com/coreos/rocket@v1.30.1-0.20200224141603-171c416fac02/rkt/image_export.go (about) 1 // Copyright 2015 The rkt Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "fmt" 19 "io" 20 "os" 21 22 "github.com/rkt/rkt/store/imagestore" 23 24 "github.com/spf13/cobra" 25 ) 26 27 var ( 28 cmdImageExport = &cobra.Command{ 29 Use: "export IMAGE OUTPUT_ACI_FILE", 30 Short: "Export a stored image to an ACI file", 31 Long: `IMAGE should be a string referencing an image: either an ID or an image name. 32 33 Note that images must be fetched prior to running export and that this command 34 always returns uncompressed ACIs`, 35 Run: runWrapper(runImageExport), 36 } 37 flagOverwriteACI bool 38 ) 39 40 func init() { 41 cmdImage.AddCommand(cmdImageExport) 42 cmdImageExport.Flags().BoolVar(&flagOverwriteACI, "overwrite", false, "overwrite output ACI") 43 } 44 45 func runImageExport(cmd *cobra.Command, args []string) (exit int) { 46 if len(args) != 2 { 47 cmd.Usage() 48 return 254 49 } 50 51 s, err := imagestore.NewStore(storeDir()) 52 if err != nil { 53 stderr.PrintE("cannot open store", err) 54 return 254 55 } 56 57 key, err := getStoreKeyFromAppOrHash(s, args[0]) 58 if err != nil { 59 stderr.Error(err) 60 return 254 61 } 62 63 aci, err := s.ReadStream(key) 64 if err != nil { 65 stderr.PrintE("error reading image", err) 66 return 254 67 } 68 defer aci.Close() 69 70 mode := os.O_CREATE | os.O_WRONLY 71 if flagOverwriteACI { 72 mode |= os.O_TRUNC 73 } else { 74 mode |= os.O_EXCL 75 } 76 f, err := os.OpenFile(args[1], mode, 0644) 77 if err != nil { 78 if os.IsExist(err) { 79 stderr.Print("output ACI file exists (try --overwrite)") 80 } else { 81 stderr.PrintE(fmt.Sprintf("unable to open output ACI file %s", args[1]), err) 82 } 83 return 254 84 } 85 defer func() { 86 err := f.Close() 87 if err != nil { 88 stderr.PrintE("error closing output ACI file", err) 89 exit = 1 90 } 91 }() 92 93 _, err = io.Copy(f, aci) 94 if err != nil { 95 stderr.PrintE("error writing to output ACI file", err) 96 return 254 97 } 98 99 return 0 100 }