-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmage.go
297 lines (268 loc) · 7.92 KB
/
mage.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
//+build mage
package main
import (
b64 "encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/briggysmalls/detectordag/shared"
"github.com/briggysmalls/detectordag/shared/iot"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
// mage:import
_ "github.com/briggysmalls/detectordag/shared/mage"
)
// Build constants
const (
// Directory for build outputs
buildDir = "./build"
applicationName = "detectordag-edge"
awsProvisioningTemplate = "./config/thing.json"
balenaVersion = "v2.54.2+rev1"
deviceType = "raspberrypi"
certFile = "thing.cert.pem"
keyFile = "thing.private.key"
deviceIDEnvVar = "DDAG_DEVICE_ID"
imageFile = "detectordag-edge.img"
)
// Build nearly-constants (derived from constants)
var vanillaImageFile = fmt.Sprintf("%s/detectordag-edge.img", buildDir)
type Generate mg.Namespace
type Provision mg.Namespace
var path string
func init() {
var err error
path, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
}
func createBuildDir() error {
// Create a new one
return sh.Run("mkdir", "-p", buildDir)
}
func deviceBuildDir() error {
mg.Deps(createBuildDir)
// Get configuration argument
deviceID, err := getEnvVar(deviceIDEnvVar)
if err != nil {
return err
}
// Ensure build directory is present
return sh.Run("mkdir", "-p", fmt.Sprintf("%s/%s", buildDir, deviceID))
}
// Generates the OpenAPI specification from the api
func (Generate) Spec() error {
return sh.Run("docker", "run", "--rm", "-v", fmt.Sprintf("%s:/app", path), "quay.io/goswagger/swagger", "generate", "spec", "-w", "/app/api", "-o", "/app/api.yml")
}
func ValidateSpec() error {
return sh.Run("docker", "run", "--rm", "-v", fmt.Sprintf("%s:/local", path), "openapitools/openapi-generator-cli", "validate", "-i", "/local/api.yml")
}
// Generates the javascript API client from the OpenAPI specification
func (Generate) Lib() error {
// Remove any existing content
const libDir = "frontend/lib/client"
err := sh.Run("rm", "-rf", libDir)
if err != nil {
return err
}
return sh.Run("docker", "run", "--rm", "-v", fmt.Sprintf("%s:/local", path), "openapitools/openapi-generator-cli", "generate", "-i", "/local/api.yml", "-g", "typescript-axios", "-o", fmt.Sprintf("/local/%s", libDir))
}
// Generates documentation from the OpenAPI specification
func (Generate) Docs() error {
// Remove any existing content
const docsDir = "build/docs"
err := sh.Run("rm", "-rf", docsDir)
if err != nil {
return err
}
return sh.Run("docker", "run", "--rm", "-v", fmt.Sprintf("%s:/local", path), "broothie/redoc-cli", "bundle", "/local/api.yml", "-o", fmt.Sprintf("/local/%s/index.html", docsDir))
}
// Start a mock API from the OpenAPI specification
func MockApi() error {
return sh.Run("docker", "run", "--init", "--rm", "-v", fmt.Sprintf("%s:/local", path), "-p", "3000:4010", "stoplight/prism:4", "mock", "-h", "0.0.0.0", "/local/api.yml")
}
// Download the BalenaOS image for an edge device
func DownloadImg() error {
// Ensure we have a build directory
mg.Deps(createBuildDir)
// Download the OS image
return sh.Run("balena", "os", "download", deviceType, "--version", balenaVersion, "--output", vanillaImageFile)
}
// Configure the BalenaOS image for use in the detectordag application
func ConfigureImg() error {
mg.Deps(
deviceBuildDir, // We need a build dir to output into
RegisterBalena, // We need the device to be registered
)
var err error
// Ensure the vanilla image is present
if _, err = os.Stat(vanillaImageFile); os.IsNotExist(err) {
mg.Deps(DownloadImg)
}
// Get configuration argument
deviceID, err := getEnvVar(deviceIDEnvVar)
if err != nil {
return err
}
balenaDeviceID := toBalenaUUID(deviceID)
// Copy it in preparation for a new device
err = sh.Copy(getDeviceImageFile(deviceID), vanillaImageFile)
if err != nil {
return err
}
// Create application configuration
configFile := fmt.Sprintf("%s/config.json", getDeviceBuildDir(deviceID))
err = sh.Run("balena", "config", "generate",
"--version", balenaVersion,
"--device", balenaDeviceID,
"--network", "ethernet",
"--appUpdatePollInterval", "10",
"--output", configFile,
)
if err != nil {
return err
}
// Apply the application configuration to it
return sh.Run("balena", "os", "configure",
"--config-network", "ethernet",
"--config", configFile,
"--device", balenaDeviceID,
getDeviceImageFile(deviceID))
}
// Register a new 'thing' on AWS
func RegisterAWS() error {
mg.Deps(deviceBuildDir)
// Get some configuration
deviceID, err := getEnvVar(deviceIDEnvVar)
if err != nil {
return err
}
accountID, err := getEnvVar("DDAG_ACCOUNT_ID")
if err != nil {
return err
}
// Create the IoT client
sesh := shared.CreateSession(aws.Config{})
client, err := iot.New(sesh)
if err != nil {
return err
}
// Register the new device
_, certificates, err := client.RegisterThing(accountID, deviceID)
if err != nil {
return err
}
// Write the certificates to the build directory
if err := writeFile(fmt.Sprintf("%s/%s/%s", buildDir, deviceID, certFile), certificates.Certificate); err != nil {
return err
}
if err := writeFile(fmt.Sprintf("%s/%s/%s", buildDir, deviceID, keyFile), certificates.Private); err != nil {
return err
}
return nil
}
// Register a device on BalenaCloud
func RegisterBalena() error {
mg.Deps(
RegisterAWS, // We need the certificates
)
deviceID, err := getEnvVar(deviceIDEnvVar)
if err != nil {
return err
}
if err := sh.Run("balena", "device", "register", applicationName, "--uuid", toBalenaUUID(deviceID)); err != nil {
return err
}
// Sleep a bit to make sure the device is available
time.Sleep(100 * time.Millisecond)
// Read in the certificates
certFileText, err := readCertFile(deviceID, certFile)
if err != nil {
return err
}
keyFileText, err := readCertFile(deviceID, keyFile)
if err != nil {
return err
}
// Set certificate environment variables
envVars := map[string]string{
"AWS_THING_CERT": certFileText,
"AWS_THING_KEY": keyFileText,
"AWS_THING_NAME": deviceID,
}
for key, value := range envVars {
// Add the environment variable
err = sh.Run("balena", "env", "add", "--device", toBalenaUUID(deviceID), key, value)
if err != nil {
return err
}
}
return nil
}
// Provision a device on Balena, AWS, and create an image to burn
func ProvisionDevice() error {
mg.Deps(
RegisterBalena, // Create the balena device
ConfigureImg, // Configure an image using the device
RegisterAWS, // Register an AWS device with the same name
)
return nil
}
// Write the BalenaOS image to an external drive
func WriteImage() error {
// Assume caller has set drive
drv, err := getEnvVar("DDAG_DRIVE")
if err != nil {
return err
}
return sh.Run("balena", "os", "initialize", imageFile, "--type", deviceType, "--drive", drv, "--yes")
}
func getEnvVar(varName string) (string, error) {
env := os.Getenv(varName)
if env == "" {
return "", fmt.Errorf("%s not set", varName)
}
return env, nil
}
func GenerateDeviceID() error {
return sh.Run("openssl", "rand", "-hex", "16")
}
func getDeviceBuildDir(deviceID string) string {
return fmt.Sprintf("%s/%s", buildDir, deviceID)
}
func readCertFile(deviceID, file string) (string, error) {
// Build the filename
fileName := fmt.Sprintf("%s/%s", getDeviceBuildDir(deviceID), file)
// Read the file
dat, err := ioutil.ReadFile(fileName)
if err != nil {
return "", err
}
// Convert to base64
return string(b64.StdEncoding.EncodeToString(dat)), nil
}
func getDeviceImageFile(deviceID string) string {
return fmt.Sprintf("%s/%s", getDeviceBuildDir(deviceID), imageFile)
}
func writeFile(file, content string) error {
// Create a new file
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
// Write all the content to it
_, err2 := f.WriteString(content)
if err2 != nil {
return err
}
return nil
}
func toBalenaUUID(uuid string) string {
return strings.ReplaceAll(uuid, "-", "")
}