Skip to content

Commit 372ecfe

Browse files
committed
buildlet: add an AWS buildlet client
This change adds an AWS buildlet client which allows us to create EC2 instances on AWS. With this change we have also moved a portion of the gce creation logic into a helper function which allows multiple clients to use it. Metadata for the instances are stored in the user data fields. The creation of a buildlet pool and modifications to rundocker buildlet be made in order to enable this change. Updates golang/go#36841 Change-Id: Ice03e1520513d51a02b9d66542e00012453bf0d9 Reviewed-on: https://go-review.googlesource.com/c/build/+/232077 Run-TryBot: Carlos Amedee <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Alexander Rakoczy <[email protected]>
1 parent c34742b commit 372ecfe

File tree

9 files changed

+1277
-92
lines changed

9 files changed

+1277
-92
lines changed

buildenv/envs.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,18 @@ type Environment struct {
7474
// other fields.
7575
ControlZone string
7676

77+
// PreferredAvailabilityZone is the preffered AWS availability zone.
78+
PreferredAvailabilityZone string
79+
7780
// VMZones are the GCE zones that the VMs will be deployed to. These
7881
// GCE zones will be periodically cleaned by deleting old VMs. The zones
7982
// should all exist within a single region.
8083
VMZones []string
8184

85+
// VMAvailabilityZones are the AWS availability zones that the VMs will be deployed to.
86+
// The availability zones should all exist within a single region.
87+
VMAvailabilityZones []string
88+
8289
// StaticIP is the public, static IP address that will be attached to the
8390
// coordinator instance. The zero value means the address will be looked
8491
// up by name. This field is optional.
@@ -151,6 +158,16 @@ func (e Environment) RandomVMZone() string {
151158
return e.VMZones[rand.Intn(len(e.VMZones))]
152159
}
153160

161+
// RandomAWSVMZone returns a randomly selected zone from the zones in
162+
// VMAvailabilityZones. The PreferredAvailabilityZone value will be
163+
// returned if VMAvailabilityZones is not set.
164+
func (e Environment) RandomAWSVMZone() string {
165+
if len(e.VMAvailabilityZones) == 0 {
166+
return e.PreferredAvailabilityZone
167+
}
168+
return e.VMAvailabilityZones[rand.Intn(len(e.VMZones))]
169+
}
170+
154171
// Region returns the GCE region, derived from its zone.
155172
func (e Environment) Region() string {
156173
return e.ControlZone[:strings.LastIndex(e.ControlZone, "-")]

buildlet/aws.go

Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
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

Comments
 (0)