-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
242 lines (211 loc) · 6.11 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/sethvargo/go-githubactions"
)
type EC2RunnerConfig struct {
EC2ImageID string
EC2InstanceType string
SubnetID string
SecurityGroupID string
IamInstanceRole string
AWSResourceTags []types.Tag
RepositoryURL string
SpotInstance bool
SpotProvisioningMode string
Region string
}
type GithubRunnerConfig struct {
GitHubToken string
GitHubTokenType string
GitHubOrgRunner bool
}
type RunnerConfig struct {
Mode string
GithubRunnerConfig *GithubRunnerConfig
EC2RunnerConfig *EC2RunnerConfig
}
type Runner struct {
ec2Client *AWSClient
githubClient *GitHubClient
config RunnerConfig
instanceID *string
runnerLabel string
}
func NewRunner(config RunnerConfig) (*Runner, error) {
// Initialize AWS client
awsClient := &AWSClient{}
awsClient = awsClient.NewAWSClient(config.EC2RunnerConfig)
// Initialize Github client
githubClient := &GitHubClient{}
githubClient, err := githubClient.NewGithubClient(config.GithubRunnerConfig)
if err != nil {
return nil, fmt.Errorf("failed to create GitHub client: %v", err)
}
return &Runner{
ec2Client: awsClient,
githubClient: githubClient,
config: config,
}, nil
}
func (r *Runner) StartRunner(ctx context.Context) error {
// create GitHub registration token
registrationToken, err := r.githubClient.CreateGitHubRegistrationToken(ctx, r.config.GithubRunnerConfig.GitHubTokenType)
if err != nil {
log.Fatalf("Failed to create GitHub registration token: %v", err)
}
// set registration token
r.githubClient.Action.RegistrationToken = registrationToken
// launch instance
r.instanceID, err = r.ec2Client.LaunchInstance(ctx, r.runnerLabel, *r.githubClient.Action.RegistrationToken.Token, r.githubClient.Action.OrgRunner)
if err != nil {
return fmt.Errorf("failed to launch instance: %v", err)
}
// runner created successfully
fmt.Println("Runner created successfully " + *r.instanceID)
// create a context with timeout for the waiting tasks
waitCtx, cancel := context.WithTimeout(ctx, 8*time.Minute)
defer cancel()
var wg sync.WaitGroup
errChan := make(chan error, 2)
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Waiting for instance to be ready...")
if err := r.ec2Client.WaitForState(waitCtx, *r.instanceID); err != nil {
errChan <- err
cancel()
}
}()
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Waiting for runner to register...")
if err := r.githubClient.WaitForRunnerRegistered(waitCtx, r.runnerLabel); err != nil {
errChan <- err
cancel()
}
}()
go func() {
wg.Wait()
close(errChan)
}()
for err := range errChan {
if err != nil {
return err
}
}
return nil
}
func (r *Runner) StopRunner(ctx context.Context) error {
if r.instanceID == nil {
return fmt.Errorf("no instance to terminate")
}
var wg sync.WaitGroup
errChan := make(chan error, 2)
ctx, cancel := context.WithTimeout(ctx, 8*time.Minute)
defer cancel()
tasks := []func() error{
func() error {
if err := r.ec2Client.TerminateInstance(ctx, *r.instanceID); err != nil {
return fmt.Errorf("failed to terminate instance: %v", err)
}
return nil
},
func() error {
if err := r.githubClient.RemoveGithubRunner(ctx, r.runnerLabel); err != nil {
return err
}
return nil
},
}
for _, task := range tasks {
wg.Add(1)
go func(task func() error) {
defer wg.Done()
if err := task(); err != nil {
errChan <- err
cancel()
}
}(task)
}
go func() {
wg.Wait()
close(errChan)
}()
for err := range errChan {
if err != nil {
return err
}
}
return nil
}
func main() {
// Retrieve configuration from environment variables
config := RunnerConfig{
Mode: githubactions.GetInput("mode"),
GithubRunnerConfig: &GithubRunnerConfig{
GitHubToken: githubactions.GetInput("github-token"),
GitHubTokenType: githubactions.GetInput("github-token-type"),
GitHubOrgRunner: githubactions.GetInput("github-org-runner") == "true",
},
EC2RunnerConfig: &EC2RunnerConfig{
EC2ImageID: githubactions.GetInput("ec2-image-id"),
EC2InstanceType: githubactions.GetInput("ec2-instance-type"),
SubnetID: githubactions.GetInput("subnet-id"),
SecurityGroupID: githubactions.GetInput("security-group-id"),
IamInstanceRole: githubactions.GetInput("iam-instance-role"),
RepositoryURL: os.Getenv("GITHUB_REPOSITORY"),
SpotInstance: githubactions.GetInput("spot-instance") == "true",
SpotProvisioningMode: githubactions.GetInput("spot-provisioning-mode"),
Region: githubactions.GetInput("spot-region"),
},
}
// Parse resource tags if provided
if tagsStr := githubactions.GetInput("aws-resource-tags"); tagsStr != "" {
if err := json.Unmarshal([]byte(tagsStr), &config.EC2RunnerConfig.AWSResourceTags); err != nil {
githubactions.Fatalf("Failed to parse AWS resource tags: %v", err)
}
}
//TODO: Validate configuration
// Create a context that can be cancelled
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Set up a signal handler to cancel the context on interrupt
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Create runner
runner, err := NewRunner(config)
if err != nil {
log.Fatalf("Failed to create runner: %v", err)
}
// Handle different modes
switch config.Mode {
case "start":
// Generate unique runner label
runner.runnerLabel = fmt.Sprintf("ec2-runner-%s", time.Now().Format("20060102150405"))
// Start runner
err := runner.StartRunner(ctx)
if err != nil {
log.Fatalf("Failed to start runner: %v", err)
}
// Output instance details for GitHub Actions
fmt.Printf("::set-output name=label::%s\n", runner.runnerLabel)
fmt.Printf("::set-output name=ec2-instance-id::%s\n", *runner.instanceID)
case "stop":
if err := runner.StopRunner(ctx); err != nil {
log.Fatalf("Failed to stop runner: %v", err)
}
default:
log.Fatalf("Invalid mode: %s", config.Mode)
}
}