-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
335 lines (278 loc) · 7.92 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
type Config struct {
Action string
Dir string
// deployment service account token
Token string
// cloud run runtime info
Runtime string
Project string
Region string
SvcAccount string
Variant string
// deployed service config
ServiceName string
ImageName string
AllowUnauthenticated bool
Concurrency string
Memory string
Timeout string
Environment map[string]string
Secrets map[string]string
EnvSecrets []string
AdditionalFlags map[string]string
}
const (
TmpTokenFileLocation = "/tmp/token.json"
)
// using a var instead of const so tests can override this
var (
GCloudCommand = "gcloud"
)
var (
// populated by "go build"
BuildDate string
BuildHash string
BuildTag string
)
func getProjectFromToken(token string) string {
data := struct {
ProjectID string `json:"project_id"`
}{}
err := json.Unmarshal([]byte(token), &data)
if err != nil {
return ""
}
return data.ProjectID
}
func parseConfig() (*Config, error) {
cfg := Config{
Dir: filepath.Join(os.Getenv("DRONE_WORKSPACE"), os.Getenv("PLUGIN_DIR")),
Action: os.Getenv("PLUGIN_ACTION"),
Runtime: os.Getenv("PLUGIN_RUNTIME"),
Project: os.Getenv("PLUGIN_PROJECT"),
Region: os.Getenv("PLUGIN_REGION"),
SvcAccount: os.Getenv("PLUGIN_SVC_ACCOUNT"),
Token: os.Getenv("PLUGIN_TOKEN"),
Variant: os.Getenv("PLUGIN_VARIANT"),
ServiceName: os.Getenv("PLUGIN_SERVICE"),
ImageName: os.Getenv("PLUGIN_IMAGE"),
AllowUnauthenticated: os.Getenv("PLUGIN_ALLOW_UNAUTHENTICATED") == "true",
Concurrency: os.Getenv("PLUGIN_CONCURRENCY"),
Memory: os.Getenv("PLUGIN_MEMORY"),
Timeout: os.Getenv("PLUGIN_TIMEOUT"),
}
envStr := os.Getenv("PLUGIN_ENVIRONMENT")
if err := json.Unmarshal([]byte(envStr), &cfg.Environment); err != nil && envStr != "" {
log.Printf("json.Unmarshal() err: %s", err)
log.Printf("os.Getenv(PLUGIN_ENVIRONMENT): %s", envStr)
}
secretsStr := os.Getenv("PLUGIN_SECRETS")
if err := json.Unmarshal([]byte(secretsStr), &cfg.Secrets); err != nil && secretsStr != "" {
log.Printf("json.Unmarshal() err: %s", err)
log.Printf("os.Getenv(PLUGIN_SECRETS): %s", secretsStr)
}
addlFlagsStr := os.Getenv("PLUGIN_ADDL_FLAGS")
if err := json.Unmarshal([]byte(addlFlagsStr), &cfg.AdditionalFlags); err != nil && addlFlagsStr != "" {
log.Printf("json.Unmarshal() err: %s", err)
log.Printf("os.Getenv(PLUGIN_ADDL_FLAGS): %s", addlFlagsStr)
return nil, fmt.Errorf("failed to parse additional flags: [%s]", err)
}
PluginEnvSecretPrefix := "PLUGIN_ENV_SECRET_"
for _, e := range os.Environ() {
if s := strings.SplitN(e, "=", 2); len(s) > 0 && strings.HasPrefix(s[0], PluginEnvSecretPrefix) {
k := strings.TrimPrefix(s[0], PluginEnvSecretPrefix)
v := os.Getenv(s[0])
cfg.EnvSecrets = append(cfg.EnvSecrets, fmt.Sprintf(`%s=%s`, k, v))
}
}
if cfg.Action == "" {
return nil, fmt.Errorf("Missing action")
}
if cfg.Runtime == "" {
cfg.Runtime = "managed"
}
if cfg.ServiceName == "" {
return nil, fmt.Errorf("Missing service name")
}
if cfg.ImageName == "" {
// for Drone v0.8 compat. as 'image' clashes since settings are passed top-level
cfg.ImageName = os.Getenv("PLUGIN_DEPLOYMENT_IMAGE")
if cfg.ImageName == "" && cfg.Action == "deploy" {
return nil, fmt.Errorf("Missing image/deployment_image name")
}
}
if cfg.Token == "" {
cfg.Token = os.Getenv("TOKEN")
if cfg.Token == "" {
return nil, fmt.Errorf("Missing token")
}
}
if cfg.Project == "" {
cfg.Project = getProjectFromToken(cfg.Token)
if cfg.Project == "" {
return nil, fmt.Errorf("project id not found in token or param")
}
}
log.Printf("Using project ID: %s", cfg.Project)
return &cfg, nil
}
func CreateExecutionPlan(cfg *Config) ([]string, error) {
args := []string{
"--quiet",
}
if cfg.Variant != "" && (cfg.Variant == "alpha" || cfg.Variant == "beta") {
args = append(args, cfg.Variant)
}
args = append(args, "run")
switch cfg.Action {
case "deploy":
args = append(args, "deploy")
args = append(args, cfg.ServiceName)
args = append(args, "--image", cfg.ImageName)
// we're using ":||:" as the separator for args, let's hope no one puts that in an env or secret variable value
sep := ":||:"
if cfg.SvcAccount != "" {
args = append(args, "--service-account", cfg.SvcAccount)
}
if len(cfg.EnvSecrets) > 0 || len(cfg.Environment) > 0 {
e := make([]string, len(cfg.EnvSecrets))
copy(e, cfg.EnvSecrets)
for k, v := range cfg.Environment {
e = append(e, fmt.Sprintf(`%s=%s`, k, v))
}
envStr := strings.Join(e, sep)
envStr = "^" + sep + "^" + envStr
args = append(args, "--set-env-vars", envStr)
}
if len(cfg.Secrets) > 0 {
e := make([]string, 0)
for k, v := range cfg.Secrets {
e = append(e, fmt.Sprintf(`%s=%s`, k, v))
}
secretsStr := strings.Join(e, sep)
secretsStr = "^" + sep + "^" + secretsStr
args = append(args, "--set-secrets", secretsStr)
}
// If --quiet and none selected, GCP defaults to --no-allow-unauthenticated
if cfg.AllowUnauthenticated {
args = append(args, "--allow-unauthenticated")
} else {
args = append(args, "--no-allow-unauthenticated")
}
if cfg.Concurrency != "" {
args = append(args, "--concurrency", cfg.Concurrency)
}
if cfg.Memory != "" {
args = append(args, "--memory", cfg.Memory)
}
if cfg.Timeout != "" {
args = append(args, "--timeout", cfg.Timeout)
}
case "update-traffic":
args = append(args, "services", "update-traffic")
args = append(args, cfg.ServiceName)
default:
return []string{}, fmt.Errorf("action: %s not implemented yet", cfg.Action)
}
args = append(args, "--project", cfg.Project)
args = append(args, "--platform", cfg.Runtime)
if cfg.Region != "" {
args = append(args, "--region", cfg.Region)
}
for flg, argStr := range cfg.AdditionalFlags {
if argStr != "" {
args = append(args, fmt.Sprintf("--%s=%s", flg, argStr))
} else {
args = append(args, fmt.Sprintf("--%s", flg))
}
}
return args, nil
}
func ExecutePlan(e *Env, plan []string) error {
if err := e.Run(GCloudCommand, plan...); err != nil {
return fmt.Errorf("error: %s\n", err)
}
return nil
}
func runConfig(cfg *Config) error {
plan, err := CreateExecutionPlan(cfg)
if err != nil {
return err
}
e := NewEnv(cfg.Dir, os.Environ(), os.Stdout, os.Stderr, false)
if err := e.Run(GCloudCommand, "version"); err != nil {
return err
}
if err := e.Run(GCloudCommand, "auth", "activate-service-account", "--key-file", TmpTokenFileLocation); err != nil {
return err
}
return ExecutePlan(e, plan)
}
type Env struct {
dir string
env []string
stdout io.Writer
stderr io.Writer
dryRun bool
}
func NewEnv(dir string, env []string, stdout, stderr io.Writer, dryRun bool) *Env {
return &Env{
dir: dir,
env: env,
stdout: stdout,
stderr: stderr,
dryRun: dryRun,
}
}
func (e *Env) Run(name string, arg ...string) error {
log.Printf("Running: %s %#v", name, arg)
if e.dryRun {
return nil
}
cmd := exec.Command(name, arg...)
cmd.Dir = e.dir
cmd.Env = e.env
cmd.Stdout = e.stdout
cmd.Stderr = e.stderr
return cmd.Run()
}
func main() {
if BuildTag == "" {
BuildTag = "[not-tagged]"
}
log.Printf("drone-cloud-run plugin version: %s hash: %s date: %s", BuildTag, BuildHash, BuildDate)
showVersion := flag.Bool("v", false, "show version and exit")
flag.Parse()
if *showVersion {
os.Exit(0)
return
}
cfg, err := parseConfig()
if err != nil {
log.Fatalf("parseConfig() err: %s", err)
return
}
if err := ioutil.WriteFile(TmpTokenFileLocation, []byte(cfg.Token), 0600); err != nil {
log.Fatalf("Error writing token file: %s", err)
}
defer func() {
os.Remove(TmpTokenFileLocation)
}()
if err := runConfig(cfg); err != nil {
log.Fatalf("runConfig() err: %s", err)
return
}
}