github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/xen/create_volume.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 "github.com/solo-io/unik/pkg/types" 11 ) 12 13 func (p *XenProvider) CreateVolume(params types.CreateVolumeParams) (_ *types.Volume, err error) { 14 if _, volumeErr := p.GetImage(params.Name); volumeErr == nil { 15 return nil, errors.New("volume already exists", nil) 16 } 17 18 volumePath := getVolumePath(params.Name) 19 if err := os.MkdirAll(filepath.Dir(volumePath), 0755); err != nil { 20 return nil, errors.New("creating directory for volume file", err) 21 } 22 defer func() { 23 if err != nil { 24 if params.NoCleanup { 25 logrus.Warnf("because --no-cleanup flag was provided, not cleaning up failed volume %s at %s", params.Name, volumePath) 26 } else { 27 os.RemoveAll(filepath.Dir(volumePath)) 28 } 29 } 30 }() 31 logrus.WithField("raw-image", params.ImagePath).Infof("creating volume from raw image") 32 33 rawImageFile, err := os.Stat(params.ImagePath) 34 if err != nil { 35 return nil, errors.New("statting raw image file", err) 36 } 37 sizeMb := rawImageFile.Size() >> 20 38 39 if err := os.Rename(params.ImagePath, volumePath); err != nil { 40 return nil, errors.New("copying raw image from "+params.ImagePath+"to "+volumePath, err) 41 } 42 43 volume := &types.Volume{ 44 Id: params.Name, 45 Name: params.Name, 46 SizeMb: sizeMb, 47 Attachment: "", 48 Infrastructure: types.Infrastructure_XEN, 49 Created: time.Now(), 50 } 51 52 err = p.state.ModifyVolumes(func(volumes map[string]*types.Volume) error { 53 volumes[volume.Id] = volume 54 return nil 55 }) 56 if err != nil { 57 return nil, errors.New("modifying volume map in state", err) 58 } 59 return volume, nil 60 61 }