-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
238 lines (198 loc) · 5.81 KB
/
main.go
File metadata and controls
238 lines (198 loc) · 5.81 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
compute "cloud.google.com/go/compute/apiv1"
"cloud.google.com/go/compute/apiv1/computepb"
"go.uber.org/zap"
"google.golang.org/api/option"
)
type Config struct {
Port string
Zone string
Project string
VMNames []string
CredentialsKey string
Logger *zap.SugaredLogger
}
// ActiveJobWebhook represents the payload sent to customer webhooks
type ActiveJobWebhook struct {
Event string `json:"event"`
Owner string `json:"owner"`
Timestamp time.Time `json:"timestamp"`
}
type VMBooter struct {
config *Config
client *compute.InstancesClient
logger *zap.SugaredLogger
}
func main() {
// Initialize logger
logger, _ := zap.NewProduction()
defer logger.Sync()
sugar := logger.Sugar()
// Load configuration
config := loadConfig(sugar)
// Initialize VM manager
vmManager, err := NewVMBooter(config)
if err != nil {
sugar.Fatalw("Failed to initialize VM manager", "error", err)
}
defer vmManager.Close()
// Setup HTTP server
http.HandleFunc("/webhook", vmManager.handleWebhook)
http.HandleFunc("/health", handleHealth)
sugar.Infow("Starting server",
"port", config.Port,
"zone", config.Zone,
"project", config.Project,
"vms", config.VMNames,
)
if err := http.ListenAndServe(":"+config.Port, nil); err != nil {
sugar.Fatalw("Server failed to start", "error", err)
}
}
func loadConfig(logger *zap.SugaredLogger) *Config {
port := getEnvOrDefault("PORT", "8080")
zone := getEnvOrDefault("ZONE", "")
project := getEnvOrDefault("PROJECT", "")
vmNamesStr := getEnvOrDefault("VM_NAMES", "")
credentialsKey := getEnvOrDefault("GOOGLE_APPLICATION_CREDENTIALS_JSON", "")
if zone == "" {
logger.Fatal("ZONE environment variable is required")
}
if project == "" {
logger.Fatal("PROJECT environment variable is required")
}
if vmNamesStr == "" {
logger.Fatal("VM_NAMES environment variable is required")
}
vmNames := strings.Split(vmNamesStr, ",")
for i, name := range vmNames {
vmNames[i] = strings.TrimSpace(name)
}
return &Config{
Port: port,
Zone: zone,
Project: project,
VMNames: vmNames,
CredentialsKey: credentialsKey,
Logger: logger,
}
}
func getEnvOrDefault(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func NewVMBooter(config *Config) (*VMBooter, error) {
ctx := context.Background()
var client *compute.InstancesClient
var err error
// If running outside GCP, use static credentials
if config.CredentialsKey != "" {
config.Logger.Info("Using static credentials from GOOGLE_APPLICATION_CREDENTIALS_JSON")
client, err = compute.NewInstancesRESTClient(ctx, option.WithCredentialsJSON([]byte(config.CredentialsKey)))
} else {
// Use inherited VM permissions (default credentials from metadata service)
config.Logger.Info("Using default credentials (VM service account or ambient environment)")
client, err = compute.NewInstancesRESTClient(ctx)
}
if err != nil {
return nil, fmt.Errorf("failed to create compute client: %w", err)
}
config.Logger.Info("Successfully initialized GCP Compute client")
return &VMBooter{
config: config,
client: client,
logger: config.Logger,
}, nil
}
func (vm *VMBooter) Close() {
if vm.client != nil {
vm.client.Close()
}
}
func (vm *VMBooter) handleWebhook(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var webhook ActiveJobWebhook
if err := json.NewDecoder(r.Body).Decode(&webhook); err != nil {
vm.logger.Errorw("Failed to decode webhook request", "error", err)
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
vm.logger.Infow("Received webhook", "event", webhook.Event, "owner", webhook.Owner, "timestamp", webhook.Timestamp)
// Start all configured VMs
for _, vmName := range vm.config.VMNames {
if err := vm.startVM(vmName); err != nil {
vm.logger.Errorw("Failed to start VM", "vm", vmName, "error", err)
http.Error(w, fmt.Sprintf("Failed to start VM %s: %v", vmName, err), http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"status": "success",
"message": "Processed event",
})
}
func (vm *VMBooter) startVM(vmName string) error {
ctx := context.Background()
// First, get the current status of the VM
getInstance := &computepb.GetInstanceRequest{
Project: vm.config.Project,
Zone: vm.config.Zone,
Instance: vmName,
}
instance, err := vm.client.Get(ctx, getInstance)
if err != nil {
return fmt.Errorf("failed to get VM status: %w", err)
}
currentStatus := instance.GetStatus()
// If VM is already running, just log and return
if currentStatus == "RUNNING" {
vm.logger.Infow("VM is already running", "vm", vmName)
return nil
}
// If VM is stopped, start it
if currentStatus == "TERMINATED" || currentStatus == "STOPPED" {
startReq := &computepb.StartInstanceRequest{
Project: vm.config.Project,
Zone: vm.config.Zone,
Instance: vmName,
}
op, err := vm.client.Start(ctx, startReq)
if err != nil {
return fmt.Errorf("failed to start VM: %w", err)
}
vm.logger.Infow("VM start initiated",
"vm", vmName,
"status", "starting",
)
st := time.Now()
go func() {
ctx := context.Background()
op.Wait(ctx)
vm.logger.Infow("VM was started successfully", "vm", vmName, "duration", time.Since(st))
}()
return nil
}
// VM is in some other state (STAGING, STOPPING, etc.)
vm.logger.Infow("VM is in transitional state", "vm", vmName, "status", currentStatus)
return nil
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"status": "healthy",
})
}