github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/virtualbox/create_volume.go (about)

     1  package virtualbox
     2  
     3  import (
     4  	"github.com/sirupsen/logrus"
     5  	"github.com/emc-advanced-dev/pkg/errors"
     6  	"github.com/solo-io/unik/pkg/providers/common"
     7  	"github.com/solo-io/unik/pkg/types"
     8  	"os"
     9  	"path/filepath"
    10  	"time"
    11  )
    12  
    13  func (p *VirtualboxProvider) 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  	volumePath := getVolumePath(params.Name)
    18  	if err := os.MkdirAll(filepath.Dir(volumePath), 0755); err != nil {
    19  		return nil, errors.New("creating directory for volume file", err)
    20  	}
    21  	defer func() {
    22  		if params.NoCleanup {
    23  			logrus.Warnf("because --no-cleanup flag was provided, not cleaning up failed volume %s at %s", params.Name, volumePath)
    24  			return
    25  		}
    26  		if err != nil {
    27  			os.RemoveAll(filepath.Dir(volumePath))
    28  		}
    29  	}()
    30  	logrus.WithField("raw-image", params.ImagePath).Infof("creating volume from raw image")
    31  	if err := common.ConvertRawImage(types.ImageFormat_RAW, types.ImageFormat_VMDK, params.ImagePath, volumePath); err != nil {
    32  		return nil, errors.New("converting raw image to vmdk", err)
    33  	}
    34  
    35  	rawImageFile, err := os.Stat(params.ImagePath)
    36  	if err != nil {
    37  		return nil, errors.New("statting raw image file", err)
    38  	}
    39  	sizeMb := rawImageFile.Size() >> 20
    40  
    41  	volume := &types.Volume{
    42  		Id:             params.Name,
    43  		Name:           params.Name,
    44  		SizeMb:         sizeMb,
    45  		Attachment:     "",
    46  		Infrastructure: types.Infrastructure_VIRTUALBOX,
    47  		Created:        time.Now(),
    48  	}
    49  
    50  	if err := p.state.ModifyVolumes(func(volumes map[string]*types.Volume) error {
    51  		volumes[volume.Id] = volume
    52  		return nil
    53  	}); err != nil {
    54  		return nil, errors.New("modifying volume map in state", err)
    55  	}
    56  	return volume, nil
    57  }