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

     1  package aws
     2  
     3  import (
     4  	"github.com/sirupsen/logrus"
     5  	"github.com/aws/aws-sdk-go/aws"
     6  	"github.com/aws/aws-sdk-go/service/ec2"
     7  	"github.com/emc-advanced-dev/pkg/errors"
     8  	"github.com/solo-io/unik/pkg/providers/common"
     9  	"github.com/solo-io/unik/pkg/types"
    10  )
    11  
    12  func (p *AwsProvider) AttachVolume(id, instanceId, mntPoint string) error {
    13  	volume, err := p.GetVolume(id)
    14  	if err != nil {
    15  		return errors.New("retrieving volume "+id, err)
    16  	}
    17  	if volume.Attachment != "" {
    18  		return errors.New("volume is already attached to instance "+volume.Attachment, nil)
    19  	}
    20  	instance, err := p.GetInstance(instanceId)
    21  	if err != nil {
    22  		return errors.New("retrieving instance "+instanceId, err)
    23  	}
    24  	image, err := p.GetImage(instance.ImageId)
    25  	if err != nil {
    26  		return errors.New("retrieving image for instance", err)
    27  	}
    28  	if err := common.VerifyMntsInput(p, image, map[string]string{mntPoint: id}); err != nil {
    29  		return errors.New("invalid mapping for volume", err)
    30  	}
    31  	deviceName, err := common.GetDeviceNameForMnt(image, mntPoint)
    32  	if err != nil {
    33  		logrus.WithFields(logrus.Fields{"image": image.Id, "mappings": image.RunSpec.DeviceMappings, "mount point": mntPoint}).Errorf("given mapping was not found for image")
    34  		return err
    35  	}
    36  	param := &ec2.AttachVolumeInput{
    37  		VolumeId:   aws.String(volume.Id),
    38  		InstanceId: aws.String(instance.Id),
    39  		Device:     aws.String(deviceName),
    40  	}
    41  	if _, err := p.newEC2().AttachVolume(param); err != nil {
    42  		return errors.New("failed to attach volume "+volume.Id, err)
    43  	}
    44  	if err := p.state.ModifyVolumes(func(volumes map[string]*types.Volume) error {
    45  		volume, ok := volumes[volume.Id]
    46  		if !ok {
    47  			return errors.New("no record of "+volume.Id+" in the state", nil)
    48  		}
    49  		volume.Attachment = instance.Id
    50  		return nil
    51  	}); err != nil {
    52  		return errors.New("modifying volume map in state", err)
    53  	}
    54  	return nil
    55  }