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

     1  package vsphere
     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  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"time"
    12  )
    13  
    14  func (p *VsphereProvider) CreateVolume(params types.CreateVolumeParams) (_ *types.Volume, err error) {
    15  	if _, volumeErr := p.GetImage(params.Name); volumeErr == nil {
    16  		return nil, errors.New("volume already exists", nil)
    17  	}
    18  	c := p.getClient()
    19  
    20  	localVmdkDir, err := ioutil.TempDir("", "localvmdkdir.")
    21  	if err != nil {
    22  		return nil, errors.New("creating tmp file", err)
    23  	}
    24  	defer os.RemoveAll(localVmdkDir)
    25  	localVmdkFile := filepath.Join(localVmdkDir, "data.vmdk")
    26  	logrus.WithField("raw-image", params.ImagePath).Infof("creating vmdk from raw image")
    27  	if err := common.ConvertRawImage(types.ImageFormat_RAW, types.ImageFormat_VMDK, params.ImagePath, localVmdkFile); err != nil {
    28  		return nil, errors.New("converting raw image to vmdk", err)
    29  	}
    30  
    31  	rawImageFile, err := os.Stat(localVmdkFile)
    32  	if err != nil {
    33  		return nil, errors.New("statting raw image file", err)
    34  	}
    35  	sizeMb := rawImageFile.Size() >> 20
    36  
    37  	vsphereVolumeDir := getVolumeDatastoreDir(params.Name)
    38  	if err := c.Mkdir(vsphereVolumeDir); err != nil {
    39  		return nil, errors.New("creating vsphere directory for volume", err)
    40  	}
    41  	defer func() {
    42  		if err != nil {
    43  			if params.NoCleanup {
    44  				logrus.Warnf("because --no-cleanup flag was provided, not cleaning up failed volume %s at %s", params.Name, vsphereVolumeDir)
    45  				return
    46  			}
    47  			logrus.WithError(err).Warnf("creating volume failed, cleaning up volume on datastore")
    48  			c.Rmdir(vsphereVolumeDir)
    49  		}
    50  	}()
    51  
    52  	if err := c.ImportVmdk(localVmdkFile, vsphereVolumeDir); err != nil {
    53  		return nil, errors.New("importing data.vmdk to vsphere datastore", err)
    54  	}
    55  
    56  	volume := &types.Volume{
    57  		Id:             params.Name,
    58  		Name:           params.Name,
    59  		SizeMb:         sizeMb,
    60  		Attachment:     "",
    61  		Infrastructure: types.Infrastructure_VSPHERE,
    62  		Created:        time.Now(),
    63  	}
    64  
    65  	if err := p.state.ModifyVolumes(func(volumes map[string]*types.Volume) error {
    66  		volumes[volume.Id] = volume
    67  		return nil
    68  	}); err != nil {
    69  		return nil, errors.New("modifying volume map in state", err)
    70  	}
    71  	return volume, nil
    72  }