-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
243 lines (199 loc) · 6.63 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/hashicorp/go-plugin"
pb "github.com/whywaita/myshoes/api/proto"
"github.com/whywaita/myshoes/pkg/datastore"
"google.golang.org/grpc"
)
// Environment key values
const (
EnvAWSImageID = "AWS_IMAGE_ID"
EnvAWSResourceTypeMapping = "AWS_RESOURCE_TYPE_MAPPING"
DefaultImageID = "ami-02868af3c3df4b3aa" // us-west-2 focal 20.04 LTS amd64 hvm:ebs-ssd
)
func main() {
handshake := plugin.HandshakeConfig{
ProtocolVersion: 1,
MagicCookieKey: "SHOES_PLUGIN_MAGIC_COOKIE",
MagicCookieValue: "are_you_a_shoes?",
}
pluginMap := map[string]plugin.Plugin{
"shoes_grpc": &AWSPlugin{},
}
plugin.Serve(&plugin.ServeConfig{
HandshakeConfig: handshake,
Plugins: pluginMap,
GRPCServer: plugin.DefaultGRPCServer,
})
}
// AWSPlugin is plugin implement for AWS
type AWSPlugin struct {
plugin.Plugin
}
// GRPCServer is server of gRPC
func (p *AWSPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error {
ctx := context.Background()
server, err := newServer(ctx, "")
if err != nil {
return fmt.Errorf("failed to initialize server: %w", err)
}
pb.RegisterShoesServer(s, *server)
return nil
}
func newServer(ctx context.Context, endpoint string) (*AWS, error) {
cfg, err := config.LoadDefaultConfig(ctx, config.WithEndpointResolverWithOptions(mockEndpointResolver(endpoint)))
if err != nil {
return nil, fmt.Errorf("failed to load SDK config: %w", err)
}
service := ec2.NewFromConfig(cfg)
imageID, mapping, err := loadConfig()
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
server := &AWS{
client: service,
imageID: imageID,
resourceMapping: mapping,
}
return server, nil
}
// GRPCClient is client of gRPC
func (p *AWSPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
return nil, nil
}
// AWS is interface of Amazon Web Service
type AWS struct {
pb.UnimplementedShoesServer
client *ec2.Client
imageID string
resourceMapping map[pb.ResourceType]string
}
func (a AWS) generateInput(script string, rt pb.ResourceType) *ec2.RunInstancesInput {
instanceCount := int32(1)
return &ec2.RunInstancesInput{
MaxCount: &instanceCount,
MinCount: &instanceCount,
ImageId: aws.String(a.imageID),
InstanceType: types.InstanceType(a.resourceMapping[rt]),
UserData: aws.String(script),
}
}
// AddInstance create an instance from AWS
func (a AWS) AddInstance(ctx context.Context, req *pb.AddInstanceRequest) (*pb.AddInstanceResponse, error) {
instanceID, ip, err := a.createRunnerInstance(ctx, req.RunnerName, req.SetupScript, req.ResourceType)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create a runner instance: %+v", err)
}
return &pb.AddInstanceResponse{
CloudId: instanceID,
ShoesType: "aws",
IpAddress: ip,
}, nil
}
func (a AWS) createRunnerInstance(ctx context.Context, runnerName, script string, resourceType pb.ResourceType) (string, string, error) {
input := a.generateInput(script, resourceType)
result, err := a.client.RunInstances(ctx, input)
if err != nil {
return "", "", fmt.Errorf("failed to create instance: %w", err)
}
instanceID := *result.Instances[0].InstanceId
ip := *result.Instances[0].PublicIpAddress
if _, err := a.client.CreateTags(ctx, &ec2.CreateTagsInput{
Resources: []string{instanceID},
Tags: []types.Tag{
{
Key: aws.String("Name"),
Value: aws.String(runnerName),
},
},
}); err != nil {
return "", "", fmt.Errorf("failed to attach tag: %w", err)
}
if _, err := a.client.StartInstances(ctx, &ec2.StartInstancesInput{
InstanceIds: []string{instanceID},
}); err != nil {
return "", "", fmt.Errorf("failed to start instance (id: %s): %w", instanceID, err)
}
return instanceID, ip, nil
}
// DeleteInstance delete an instance from AWS
func (a AWS) DeleteInstance(ctx context.Context, req *pb.DeleteInstanceRequest) (*pb.DeleteInstanceResponse, error) {
if err := a.deleteRunnerInstance(ctx, req.CloudId); err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete runner instance: %+v", err)
}
return &pb.DeleteInstanceResponse{}, nil
}
func (a AWS) deleteRunnerInstance(ctx context.Context, instanceID string) error {
if _, err := a.client.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []string{instanceID},
}); err != nil {
return fmt.Errorf("failed to terminate instance (id: %s): %w", instanceID, err)
}
waiter := ec2.NewInstanceTerminatedWaiter(a.client)
if err := waiter.Wait(ctx, &ec2.DescribeInstancesInput{
InstanceIds: []string{instanceID},
}, 5*time.Minute); err != nil {
return fmt.Errorf("failed to wait terminating instance (id: %s): %w", instanceID, err)
}
return nil
}
func loadConfig() (string, map[pb.ResourceType]string, error) {
var imageID string
if os.Getenv(EnvAWSImageID) != "" {
imageID = os.Getenv(EnvAWSImageID)
} else {
imageID = DefaultImageID
}
if os.Getenv(EnvAWSResourceTypeMapping) == "" {
return "", nil, fmt.Errorf("must be set %s", EnvAWSResourceTypeMapping)
}
m, err := readResourceTypeMapping(os.Getenv(EnvAWSResourceTypeMapping))
if err != nil {
return "", nil, fmt.Errorf("failed to read %s: %w", EnvAWSResourceTypeMapping, err)
}
return imageID, m, nil
}
func readResourceTypeMapping(env string) (map[pb.ResourceType]string, error) {
var mapping map[string]string
if err := json.Unmarshal([]byte(env), &mapping); err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
}
r := map[pb.ResourceType]string{}
for key, value := range mapping {
rt := datastore.UnmarshalResourceType(key)
if rt == datastore.ResourceTypeUnknown {
return nil, fmt.Errorf("%s is invalid resource type", key)
}
r[rt.ToPb()] = value
}
return r, nil
}
// mockEndpointResolver set endpoint to localhost localstack for testing.
func mockEndpointResolver(endpoint string) aws.EndpointResolverWithOptionsFunc {
return func(service, region string, options ...interface{}) (aws.Endpoint, error) {
if endpoint == "" {
return aws.Endpoint{}, &aws.EndpointNotFoundError{}
}
//if service == ec2.ServiceID && region == "shoes-aws-testing-region" {
if strings.Contains(endpoint, "localhost") {
return aws.Endpoint{
PartitionID: "aws",
URL: endpoint,
SigningRegion: "us-east-1",
}, nil
}
return aws.Endpoint{}, &aws.EndpointNotFoundError{}
}
}