forked from LOQ9/drone-nomad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
205 lines (175 loc) · 6.25 KB
/
plugin.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
package main
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"time"
"drone-nomad/nomad"
)
const (
// SanitizeSuffix used when matching vars to sanitize
SanitizeSuffix = "_SANITIZE"
)
type (
// Repo contains information related to the repository
Repo struct {
Owner string `json:"owner" env:"DRONE_REPO_OWNER"`
Name string `json:"name" env:"DRONE_REPO_NAME"`
}
// Build contains information related to the build
Build struct {
Tag string `json:"tag" env:"DRONE_TAG"`
Event string `json:"event" env:"DRONE_BUILD_EVENT"`
Number int `json:"number" env:"DRONE_BUILD_NUMBER"`
Parent int `json:"parent" env:"DRONE_BUILD_PARENT"`
Commit string `json:"commit" env:"DRONE_COMMIT_SHA"`
Ref string `json:"ref" env:"DRONE_COMMIT_REF"`
Branch string `json:"branch" env:"DRONE_COMMIT_BRANCH"`
Author string `json:"author" env:"DRONE_COMMIT_AUTHOR"`
Message string `json:"message" env:"DRONE_COMMIT_MESSAGE"`
Status string `json:"status" env:"DRONE_BUILD_STATUS"`
Link string `json:"link" env:"DRONE_BUILD_LINK"`
Started int64 `json:"started" env:"DRONE_BUILD_STARTED"`
Created int64 `json:"created" env:"DRONE_BUILD_CREATED"`
}
// Job ...
Job struct {
Started int64 `json:"created" env:"DRONE_JOB_STARTED"`
}
// Config ...
Config struct {
Address string `json:"address" env:"PLUGIN_ADDR"`
Token string `json:"token" env:"PLUGIN_TOKEN"`
ConsulToken string `json:"consul_token" env:"PLUGIN_CONSUL_TOKEN"`
Region string `json:"region" env:"PLUGIN_REGION"`
Namespace string `json:"namespace" env:"PLUGIN_NAMESPACE"`
Template string `json:"template" env:"PLUGIN_TEMPLATE"`
TLSCACert string `json:"tls_ca_cert" env:"PLUGIN_TLS_CA_CERT"`
TLSCACertPem string `json:"tls_ca_cert_pem" env:"PLUGIN_TLS_CA_CERT_PEM"`
TLSCAPath string `json:"tls_ca_path" env:"PLUGIN_TLS_CA_PATH"`
TLSClientCert string `json:"tls_client_cert" env:"PLUGIN_TLS_CLIENT_CERT"`
TLSClientCertPem string `json:"tls_client_cert_pem" env:"PLUGIN_TLS_CLIENT_CERT_PEM"`
TLSClientKey string `json:"tls_client_key" env:"PLUGIN_TLS_CLIENT_KEY"`
TLSClientKeyPem string `json:"tls_client_key_pem" env:"PLUGIN_TLS_CLIENT_KEY_PEM"`
TLSServerName string `json:"tls_servername" env:"PLUGIN_TLS_SERVERNAME"`
TLSInsecure bool `json:"tls_insecure" env:"PLUGIN_TLS_INSECURE"`
PreserveCounts bool `json:"preserve_counts" env:"PLUGIN_PRESERVE_COUNTS"`
Debug bool `json:"debug" env:"PLUGIN_DEBUG"`
DryRun bool `json:"dry_run" env:"PLUGIN_DRY_RUN"`
WatchDeployment bool `json:"watch_deployment" env:"PLUGIN_WATCH_DEPLOYMENT"`
WatchDeploymentTimeout time.Duration `json:"watch_deployment_timeout" env:"PLUGIN_WATCH_DEPLOYMENT_TIMEOUT"`
}
// Plugin ...
Plugin struct {
Repo Repo
Build Build
Config Config
Job Job
}
)
// Exec initiates the plugin execution
func (p Plugin) Exec() error {
nomadClient := &nomad.Client{
Address: p.Config.Address,
Region: p.Config.Region,
Namespace: p.Config.Namespace,
Token: p.Config.Token,
TLSConfig: &nomad.ClientTLSConfig{
CACert: p.Config.TLSCACert,
CACertPEM: []byte(p.Config.TLSCACertPem),
CAPath: p.Config.TLSCAPath,
ClientCert: p.Config.TLSClientCert,
ClientCertPEM: []byte(p.Config.TLSClientCertPem),
ClientKey: p.Config.TLSClientKey,
ClientKeyPEM: []byte(p.Config.TLSClientKeyPem),
TLSServerName: p.Config.TLSServerName,
Insecure: p.Config.TLSInsecure,
},
}
// Connect to Nomad
nomad, err := nomad.New(nomadClient)
if err != nil {
return err
}
// Read Template File
nomadTemplateFile, err := ioutil.ReadFile(p.Config.Template)
if err != nil {
return fmt.Errorf("Could not read nomad template file")
}
// Perform substitions
nomadTemplateSubst := p.replaceEnv(string(nomadTemplateFile))
// Parse template
nomadTemplate, err := nomad.ParseTemplate(nomadTemplateSubst)
if err != nil {
return err
}
// Set consul ACL token
if p.Config.ConsulToken != "" {
*nomadTemplate.ConsulToken = p.Config.ConsulToken
}
// Log template to STDOUT when debugging is enabled
if p.Config.Debug {
fmt.Println("Nomad template:")
fmt.Println(nomadTemplateSubst)
}
// Plan deployment
_, err = nomad.PlanJob(nomadTemplate)
if err != nil {
return err
}
if !p.Config.DryRun {
// Launch deployment
nomadJob, err := nomad.RegisterJob(nomadTemplate, p.Config.PreserveCounts)
if err != nil {
return err
}
if len(nomadJob.Warnings) > 0 {
fmt.Printf("Nomad job deployed with %d warning(s)\n", len(nomadJob.Warnings))
fmt.Printf("%s\n", nomadJob.Warnings)
} else if p.Config.WatchDeployment {
if p.Config.WatchDeploymentTimeout == 0 {
p.Config.WatchDeploymentTimeout = time.Minute * 5
}
// block and watch deployment
if err = nomad.WatchDeployment(nomadJob, p.Config.WatchDeploymentTimeout); err != nil {
return err
}
} else {
fmt.Printf("Nomad job deployed successfuly!\n")
}
}
return nil
}
// replaceEnv changes vars from template
func (p Plugin) replaceEnv(template string) string {
// Regular expression matching var expression ${...}
reVars := regexp.MustCompile(`(?m)\$\{(.+?)\}`)
// Replace all matches of regular expression and check if it can be replaced
template = reVars.ReplaceAllStringFunc(template, func(s string) string {
// Find the exact var name inside match, e.g. ${DRONE_TAG=latest} becomes "DRONE_TAG=latest"
matches := reVars.FindStringSubmatch(s)
// Do not replace NOMAD_ variables
if strings.HasPrefix(matches[1], "NOMAD_") {
return matches[1]
}
envName := ""
envValue := ""
// Check string sufix
if strings.HasSuffix(matches[1], SanitizeSuffix) {
// Remove Suffix
envName = strings.TrimSuffix(matches[1], SanitizeSuffix)
// Get var content
envValue = strings.ToLower(os.Getenv(envName))
} else {
envName = matches[1]
envValue = os.Getenv(envName)
}
if p.Config.Debug {
fmt.Printf("Replacing (var: %s, value: %s)", envName, envValue)
}
return envValue
})
return template
}