|
| 1 | +// Copyright 2020 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package buildlet |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "encoding/json" |
| 10 | + "errors" |
| 11 | + "fmt" |
| 12 | + "log" |
| 13 | + "net" |
| 14 | + "time" |
| 15 | + |
| 16 | + "golang.org/x/build/buildenv" |
| 17 | + "golang.org/x/build/dashboard" |
| 18 | + |
| 19 | + "github.com/aws/aws-sdk-go/aws" |
| 20 | + "github.com/aws/aws-sdk-go/aws/credentials" |
| 21 | + "github.com/aws/aws-sdk-go/aws/request" |
| 22 | + "github.com/aws/aws-sdk-go/aws/session" |
| 23 | + "github.com/aws/aws-sdk-go/service/ec2" |
| 24 | +) |
| 25 | + |
| 26 | +// AWSUserData is stored in the user data for each EC2 instance. This is |
| 27 | +// used to store metadata about the running instance. The buildlet will retrieve |
| 28 | +// this on EC2 instances before allowing connections from the coordinator. |
| 29 | +type AWSUserData struct { |
| 30 | + BuildletBinaryURL string `json:"buildlet_binary_url,omitempty"` |
| 31 | + BuildletHostType string `json:"buildlet_host_type,omitempty"` |
| 32 | + Metadata map[string]string `json:"metadata,omitempty"` |
| 33 | + TLSCert string `json:"tls_cert,omitempty"` |
| 34 | + TLSKey string `json:"tls_key,omitempty"` |
| 35 | + TLSPassword string `json:"tls_password,omitempty"` |
| 36 | +} |
| 37 | + |
| 38 | +// ec2Client represents the EC2 specific calls made durring the |
| 39 | +// lifecycle of a buildlet. |
| 40 | +type ec2Client interface { |
| 41 | + DescribeInstancesWithContext(context.Context, *ec2.DescribeInstancesInput, ...request.Option) (*ec2.DescribeInstancesOutput, error) |
| 42 | + RunInstancesWithContext(context.Context, *ec2.RunInstancesInput, ...request.Option) (*ec2.Reservation, error) |
| 43 | + TerminateInstancesWithContext(context.Context, *ec2.TerminateInstancesInput, ...request.Option) (*ec2.TerminateInstancesOutput, error) |
| 44 | + WaitUntilInstanceExistsWithContext(context.Context, *ec2.DescribeInstancesInput, ...request.WaiterOption) error |
| 45 | +} |
| 46 | + |
| 47 | +// AWSClient is the client used to create and destroy buildlets on AWS. |
| 48 | +type AWSClient struct { |
| 49 | + client ec2Client |
| 50 | +} |
| 51 | + |
| 52 | +// NewAWSClient creates a new AWSClient. |
| 53 | +func NewAWSClient(region, keyID, accessKey string) (*AWSClient, error) { |
| 54 | + s, err := session.NewSession(&aws.Config{ |
| 55 | + Region: aws.String(region), |
| 56 | + Credentials: credentials.NewStaticCredentials(keyID, accessKey, ""), // Token is only required for STS |
| 57 | + }) |
| 58 | + if err != nil { |
| 59 | + return nil, fmt.Errorf("failed to create AWS session: %v", err) |
| 60 | + } |
| 61 | + return &AWSClient{ |
| 62 | + client: ec2.New(s), |
| 63 | + }, nil |
| 64 | +} |
| 65 | + |
| 66 | +// StartNewVM boots a new VM on EC2, waits until the client is accepting connections |
| 67 | +// on the configured port and returns a buildlet client configured communicate with it. |
| 68 | +func (c *AWSClient) StartNewVM(ctx context.Context, buildEnv *buildenv.Environment, hconf *dashboard.HostConfig, vmName, hostType string, opts *VMOpts) (*Client, error) { |
| 69 | + // check required params |
| 70 | + if opts == nil || opts.TLS.IsZero() { |
| 71 | + return nil, errors.New("TLS keypair is not set") |
| 72 | + } |
| 73 | + if buildEnv == nil { |
| 74 | + return nil, errors.New("invalid build enviornment") |
| 75 | + } |
| 76 | + if hconf == nil { |
| 77 | + return nil, errors.New("invalid host configuration") |
| 78 | + } |
| 79 | + if vmName == "" || hostType == "" { |
| 80 | + return nil, fmt.Errorf("invalid vmName: %q and hostType: %q", vmName, hostType) |
| 81 | + } |
| 82 | + |
| 83 | + // configure defaults |
| 84 | + if opts.Description == "" { |
| 85 | + opts.Description = fmt.Sprintf("Go Builder for %s", hostType) |
| 86 | + } |
| 87 | + if opts.Zone == "" { |
| 88 | + opts.Zone = buildEnv.RandomAWSVMZone() |
| 89 | + } |
| 90 | + if opts.DeleteIn == 0 { |
| 91 | + opts.DeleteIn = 30 * time.Minute |
| 92 | + } |
| 93 | + |
| 94 | + vmConfig := c.configureVM(buildEnv, hconf, vmName, hostType, opts) |
| 95 | + vmID, err := c.createVM(ctx, vmConfig, opts) |
| 96 | + if err != nil { |
| 97 | + return nil, err |
| 98 | + } |
| 99 | + if err = c.WaitUntilVMExists(ctx, vmID, opts); err != nil { |
| 100 | + return nil, err |
| 101 | + } |
| 102 | + vm, err := c.RetrieveVMInfo(ctx, vmID) |
| 103 | + if err != nil { |
| 104 | + return nil, err |
| 105 | + } |
| 106 | + buildletURL, ipPort, err := ec2BuildletParams(vm, opts) |
| 107 | + if err != nil { |
| 108 | + return nil, err |
| 109 | + } |
| 110 | + return buildletClient(ctx, buildletURL, ipPort, opts) |
| 111 | +} |
| 112 | + |
| 113 | +// createVM submits a request for the creation of a VM. |
| 114 | +func (c *AWSClient) createVM(ctx context.Context, vmConfig *ec2.RunInstancesInput, opts *VMOpts) (string, error) { |
| 115 | + runResult, err := c.client.RunInstancesWithContext(ctx, vmConfig) |
| 116 | + if err != nil { |
| 117 | + return "", fmt.Errorf("unable to create instance: %w", err) |
| 118 | + } |
| 119 | + condRun(opts.OnInstanceRequested) |
| 120 | + return *runResult.Instances[0].InstanceId, nil |
| 121 | +} |
| 122 | + |
| 123 | +// WaitUntilVMExists submits a request which waits until an instance exists before returning. |
| 124 | +func (c *AWSClient) WaitUntilVMExists(ctx context.Context, instID string, opts *VMOpts) error { |
| 125 | + err := c.client.WaitUntilInstanceExistsWithContext(ctx, &ec2.DescribeInstancesInput{ |
| 126 | + InstanceIds: []*string{aws.String(instID)}, |
| 127 | + }) |
| 128 | + if err != nil { |
| 129 | + return fmt.Errorf("failed waiting for vm instance: %w", err) |
| 130 | + } |
| 131 | + condRun(opts.OnInstanceCreated) |
| 132 | + return err |
| 133 | +} |
| 134 | + |
| 135 | +// RetrieveVMInfo retrives the information about a VM. |
| 136 | +func (c *AWSClient) RetrieveVMInfo(ctx context.Context, instID string) (*ec2.Instance, error) { |
| 137 | + instances, err := c.client.DescribeInstancesWithContext(ctx, &ec2.DescribeInstancesInput{ |
| 138 | + InstanceIds: []*string{aws.String(instID)}, |
| 139 | + }) |
| 140 | + if err != nil { |
| 141 | + return nil, fmt.Errorf("unable to retrieve instance %q information: %w", instID, err) |
| 142 | + } |
| 143 | + |
| 144 | + instance, err := ec2Instance(instances) |
| 145 | + if err != nil { |
| 146 | + return nil, fmt.Errorf("failed to read instance description: %w", err) |
| 147 | + } |
| 148 | + return instance, err |
| 149 | +} |
| 150 | + |
| 151 | +// configureVM creates a configuration for an EC2 VM instance. |
| 152 | +func (c *AWSClient) configureVM(buildEnv *buildenv.Environment, hconf *dashboard.HostConfig, vmName, hostType string, opts *VMOpts) *ec2.RunInstancesInput { |
| 153 | + vmConfig := &ec2.RunInstancesInput{ |
| 154 | + ImageId: aws.String(hconf.VMImage), |
| 155 | + InstanceType: aws.String(hconf.MachineType()), |
| 156 | + MinCount: aws.Int64(1), |
| 157 | + MaxCount: aws.Int64(1), |
| 158 | + Placement: &ec2.Placement{ |
| 159 | + AvailabilityZone: aws.String(opts.Zone), |
| 160 | + }, |
| 161 | + InstanceInitiatedShutdownBehavior: aws.String("terminate"), |
| 162 | + TagSpecifications: []*ec2.TagSpecification{ |
| 163 | + &ec2.TagSpecification{ |
| 164 | + Tags: []*ec2.Tag{ |
| 165 | + &ec2.Tag{ |
| 166 | + Key: aws.String("Name"), |
| 167 | + Value: aws.String(vmName), |
| 168 | + }, |
| 169 | + &ec2.Tag{ |
| 170 | + Key: aws.String("Description"), |
| 171 | + Value: aws.String(opts.Description), |
| 172 | + }, |
| 173 | + }, |
| 174 | + }, |
| 175 | + }, |
| 176 | + } |
| 177 | + |
| 178 | + // add custom metadata to the user data. |
| 179 | + ud := AWSUserData{ |
| 180 | + BuildletBinaryURL: hconf.BuildletBinaryURL(buildEnv), |
| 181 | + BuildletHostType: hostType, |
| 182 | + TLSCert: opts.TLS.CertPEM, |
| 183 | + TLSKey: opts.TLS.KeyPEM, |
| 184 | + TLSPassword: opts.TLS.Password(), |
| 185 | + Metadata: make(map[string]string), |
| 186 | + } |
| 187 | + for k, v := range opts.Meta { |
| 188 | + ud.Metadata[k] = v |
| 189 | + } |
| 190 | + jsonUserData, err := json.Marshal(ud) |
| 191 | + if err != nil { |
| 192 | + log.Printf("unable to marshal user data: %v", err) |
| 193 | + } |
| 194 | + return vmConfig.SetUserData(string(jsonUserData)) |
| 195 | +} |
| 196 | + |
| 197 | +// DestroyVM submits a request to destroy a VM. |
| 198 | +func (c *AWSClient) DestroyVM(ctx context.Context, vmID string) error { |
| 199 | + _, err := c.client.TerminateInstancesWithContext(ctx, &ec2.TerminateInstancesInput{ |
| 200 | + InstanceIds: []*string{aws.String(vmID)}, |
| 201 | + }) |
| 202 | + if err != nil { |
| 203 | + return fmt.Errorf("unable to destroy vm: %w", err) |
| 204 | + } |
| 205 | + return err |
| 206 | +} |
| 207 | + |
| 208 | +// ec2Instance extracts the first instance found in the the describe instances output. |
| 209 | +func ec2Instance(dio *ec2.DescribeInstancesOutput) (*ec2.Instance, error) { |
| 210 | + if dio == nil || dio.Reservations == nil || dio.Reservations[0].Instances == nil { |
| 211 | + return nil, errors.New("describe instances output does not contain a valid instance") |
| 212 | + } |
| 213 | + return dio.Reservations[0].Instances[0], nil |
| 214 | +} |
| 215 | + |
| 216 | +// ec2InstanceIPs returns the internal and external ip addresses for the VM. |
| 217 | +func ec2InstanceIPs(inst *ec2.Instance) (intIP, extIP string, err error) { |
| 218 | + if inst.PrivateIpAddress == nil || *inst.PrivateIpAddress == "" { |
| 219 | + return "", "", errors.New("internal IP address is not set") |
| 220 | + } |
| 221 | + if inst.PublicIpAddress == nil || *inst.PublicIpAddress == "" { |
| 222 | + return "", "", errors.New("external IP address is not set") |
| 223 | + } |
| 224 | + return *inst.PrivateIpAddress, *inst.PublicIpAddress, nil |
| 225 | +} |
| 226 | + |
| 227 | +// ec2BuildletParams returns the necessary information to connect to an EC2 buildlet. A |
| 228 | +// buildlet URL and an IP address port are required to connect to a buildlet. |
| 229 | +func ec2BuildletParams(inst *ec2.Instance, opts *VMOpts) (string, string, error) { |
| 230 | + _, extIP, err := ec2InstanceIPs(inst) |
| 231 | + if err != nil { |
| 232 | + return "", "", fmt.Errorf("failed to retrieve IP addresses: %w", err) |
| 233 | + } |
| 234 | + buildletURL := fmt.Sprintf("https://%s", extIP) |
| 235 | + ipPort := net.JoinHostPort(extIP, "443") |
| 236 | + |
| 237 | + if opts.OnGotEC2InstanceInfo != nil { |
| 238 | + opts.OnGotEC2InstanceInfo(inst) |
| 239 | + } |
| 240 | + return buildletURL, ipPort, err |
| 241 | +} |
0 commit comments