github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/xen/stage.go (about) 1 package xen 2 3 import ( 4 "os" 5 "path/filepath" 6 "time" 7 8 "github.com/sirupsen/logrus" 9 "github.com/emc-advanced-dev/pkg/errors" 10 unikos "github.com/solo-io/unik/pkg/os" 11 "github.com/solo-io/unik/pkg/types" 12 ) 13 14 func (p *XenProvider) Stage(params types.StageImageParams) (_ *types.Image, err error) { 15 images, err := p.ListImages() 16 if err != nil { 17 return nil, errors.New("retrieving image list for existing image", err) 18 } 19 for _, image := range images { 20 if image.Name == params.Name { 21 if !params.Force { 22 return nil, errors.New("an image already exists with name '"+params.Name+"', try again with --force", nil) 23 } else { 24 logrus.WithField("image", image).Warnf("force: deleting previous image with name " + params.Name) 25 if err := p.DeleteImage(image.Id, true); err != nil { 26 logrus.Warn("failed to remove previously existing image", err) 27 } 28 } 29 } 30 } 31 32 imagePath := getImagePath(params.Name) 33 logrus.Debugf("making directory: %s", filepath.Dir(imagePath)) 34 if err := os.MkdirAll(filepath.Dir(imagePath), 0777); err != nil { 35 return nil, errors.New("creating directory for boot image", err) 36 } 37 defer func() { 38 if err != nil && !params.NoCleanup { 39 os.RemoveAll(filepath.Dir(imagePath)) 40 } 41 }() 42 43 if err := unikos.CopyFile(params.RawImage.LocalImagePath, getImagePath(params.Name)); err != nil { 44 return nil, errors.New("copying bootable image to image dir", err) 45 } 46 47 imagePathInfo, err := os.Stat(imagePath) 48 if err != nil { 49 return nil, errors.New("statting raw image file", err) 50 } 51 sizeMb := imagePathInfo.Size() >> 20 52 53 logrus.WithFields(logrus.Fields{ 54 "name": params.Name, 55 "id": params.Name, 56 "size": sizeMb, 57 }).Infof("copying raw boot image") 58 59 image := &types.Image{ 60 Id: params.Name, 61 Name: params.Name, 62 RunSpec: params.RawImage.RunSpec, 63 StageSpec: params.RawImage.StageSpec, 64 SizeMb: sizeMb, 65 Infrastructure: types.Infrastructure_XEN, 66 Created: time.Now(), 67 } 68 69 if err := p.state.ModifyImages(func(images map[string]*types.Image) error { 70 images[params.Name] = image 71 return nil 72 }); err != nil { 73 return nil, errors.New("modifying image map in state", err) 74 } 75 76 logrus.WithFields(logrus.Fields{"image": image}).Infof("image created succesfully") 77 return image, nil 78 }