-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
main.go
387 lines (321 loc) · 9.52 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright 2019 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The package provides a transparent pass-through
// for the Custodian CLI to a Custodian Docker Image
package main
import (
"context"
"crypto/sha1"
"encoding/hex"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strings"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/stdcopy"
"github.com/mattn/go-isatty"
"github.com/thoas/go-funk"
)
const containerHome string = "/home/custodian/"
const defaultImageName string = "cloudcustodian/c7n:latest"
const imageOverrideEnv = "CUSTODIAN_IMAGE"
const updateInterval = time.Hour * 12
var version string
func main() {
// Select image from env or default
activeImage := getDockerImageName()
fmt.Printf("Custodian Cask %v (%v)\n", version, activeImage)
ctx := context.Background()
// Create a docker client
dockerClient := getClient()
// Update docker image if needed
update(ctx, "docker.io/"+activeImage, dockerClient)
// Create container
id := create(ctx, activeImage, dockerClient)
// Create signal channel and register notify
handleSignals(ctx, id, dockerClient)
// Run
run(ctx, id, dockerClient)
}
// getClient Creates a docker client using the host environment variables
func getClient() *client.Client {
dockerClient, err := client.NewEnvClient()
if err != nil {
log.Fatalf("Unable to create docker client. %v", err)
}
return dockerClient
}
// update Pulls the latest docker image and creates
// a marker file so it is not pulled again until
// the specified time elapses or the file is deleted.
func update(ctx context.Context, image string, dockerClient *client.Client) {
updateMarker := updateMarkerFilename(image)
now := time.Now()
// Check if there is a marker indicating last pull for this image
info, err := os.Stat(updateMarker)
// If the marker file is not expired
if err == nil && info.ModTime().Add(updateInterval).After(now) {
// Query the existing image list for matches
listFilters := filters.NewArgs()
listFilters.Add("reference", defaultImageName)
listOptions := types.ImageListOptions{
All: true,
Filters: listFilters,
}
images, err := dockerClient.ImageList(ctx, listOptions)
if err != nil {
log.Printf("Failed to enumerate docker images. %v", err)
}
// Skip image pull if we have an image already
if len(images) > 0 {
return
}
}
// Pull the image
out, err := dockerClient.ImagePull(ctx, image, types.ImagePullOptions{})
if err != nil {
log.Printf("Image Pull failed, will use cached image if available. %v", err)
} else {
isTerm := isatty.IsTerminal(os.Stdout.Fd())
_ = jsonmessage.DisplayJSONMessagesStream(out, os.Stdout, 1, isTerm, nil)
}
// Touch the marker file
if _, err := os.Stat(updateMarker); err == nil {
if err := os.Chtimes(updateMarker, now, now); err != nil {
log.Printf("Unable to update cache marker file. %v", err)
}
} else {
if _, err = os.OpenFile(updateMarker, os.O_RDWR|os.O_CREATE, 0666); err != nil {
log.Printf("Unable to write to temporary directory. %v", err)
}
}
}
// create a container with appropriate arguments.
// Includes creating mounts and updating paths.
func create(ctx context.Context, image string, dockerClient *client.Client) string {
// Prepare configuration
args := os.Args[1:]
processOutputArgs(&args)
binds := generateBinds(args)
envs := generateEnvs()
// Create container
cont, err := dockerClient.ContainerCreate(
ctx,
&container.Config{
Image: image,
Cmd: args,
Env: envs,
},
&container.HostConfig{
Binds: binds,
NetworkMode: "host",
},
nil,
nil,
"")
if err != nil {
log.Fatal(err)
}
return cont.ID
}
// run container and wait for it to complete.
// Copy log output to stdout and stderr.
func run(ctx context.Context, id string, dockerClient *client.Client) {
// Docker Run
err := dockerClient.ContainerStart(ctx, id, types.ContainerStartOptions{})
if err != nil {
log.Fatal(err)
}
// Output
out, err := dockerClient.ContainerLogs(ctx, id, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true})
if err != nil {
log.Fatal(err)
}
_, err = stdcopy.StdCopy(os.Stdout, os.Stdout, out)
if err != nil {
log.Fatal(err)
}
err = dockerClient.ContainerRemove(
ctx, id, types.ContainerRemoveOptions{RemoveVolumes: true})
if err != nil {
log.Fatal(err)
}
}
// generateBinds Create the bind mounts for input/output
func generateBinds(args []string) []string {
var binds []string
// Loop through all args looking for paths
// so we can create bind mounts and rewrite the arg
for i, arg := range args {
if isPath(arg) {
containerPath := containerHome + filepath.Base(arg)
absPath, err := filepath.Abs(arg)
if err == nil {
binds = append(binds, absPath+":"+containerHome+filepath.Base(absPath)+":rw")
}
args[i] = containerPath
}
}
// Azure CLI support
azureCliConfig := getAzureCliConfigPath()
if azureCliConfig != "" {
// Bind as RW for token refreshes
binds = append(binds, azureCliConfig+":"+containerHome+".azure:rw")
}
// AWS config
awsConfig := getAwsConfigPath()
if awsConfig != "" {
binds = append(binds, awsConfig+":"+containerHome+".aws:ro")
}
// Default cache location
if !funk.Any(funk.Intersect(args, []string{"-f", "--cache"})) {
cacheDefault := getFolderFromHome(".cache")
binds = append(binds, cacheDefault+":"+containerHome+".cache:rw")
}
return binds
}
func processOutputArgs(argsp *[]string) {
var outputPath string
args := *argsp
for i, arg := range args {
if strings.HasPrefix(arg, "-s") || strings.HasPrefix(arg, "--output-dir") {
// normalize argument separator
if strings.HasPrefix(arg, "-s=") || strings.HasPrefix(arg, "--output-dir=") {
outputPath = strings.Split(arg, "=")[1]
args[i] = "-s"
args = append(args, "")
copy(args[i+1:], args[i:])
args[i+1] = outputPath
}
// make absolute path and ensure exists
outputPath, err := filepath.Abs(args[i+1])
if err != nil {
log.Fatal(err)
}
err = os.MkdirAll(outputPath, 0700)
if err != nil {
log.Fatal(err)
}
args[i+1] = outputPath
}
}
*argsp = args
}
// generateEnvs Get list of environment variables
func generateEnvs() []string {
var envs []string
// Bulk include matching variables
var re = regexp.MustCompile(`^AWS|^AZURE_|^MSI_|^TENCENTCLOUD_|^GOOGLE|CLOUDSDK`)
for _, s := range os.Environ() {
if re.MatchString(s) {
envs = append(envs, s)
}
}
return envs
}
// getAzureCliConfigPath Find Azure CLI Config if available so
// we can mount it on the container.
func getAzureCliConfigPath() string {
// Check for override location
azureCliConfig := os.Getenv("AZURE_CONFIG_DIR")
if azureCliConfig != "" {
return filepath.Join(azureCliConfig, "config")
}
// Check for default location
configPath := getFolderFromHome(".azure")
if _, err := os.Stat(configPath); err == nil {
return configPath
}
return ""
}
// getAwsConfigPath Find AWS Config if available so
// we can mount it on the container.
func getAwsConfigPath() string {
configPath := getFolderFromHome(".aws")
if _, err := os.Stat(configPath); err == nil {
return configPath
}
return ""
}
// getFolderFromHome helps us get a
// folder in the users home directory
func getFolderFromHome(subdir string) string {
var configPath string
if runtime.GOOS == "windows" {
configPath = os.Getenv("USERPROFILE")
} else {
configPath = os.Getenv("HOME")
}
return filepath.Join(configPath, subdir)
}
func isLocalStorage(output string) bool {
return !(strings.HasPrefix(output, "s3://") ||
strings.HasPrefix(output, "azure://") ||
strings.HasPrefix(output, "gs://"))
}
// isPath attempts to confirm if an argument
// is a path, and thus needs a bind
func isPath(arg string) bool {
_, err := os.Stat(arg)
if os.IsNotExist(err) {
return false
}
return true
}
func getDockerImageName() string {
image := os.Getenv(imageOverrideEnv)
if len(image) == 0 {
return defaultImageName
}
return image
}
func updateMarkerFilename(image string) string {
sha := sha1.New()
sha.Write([]byte(image))
hash := hex.EncodeToString(sha.Sum(nil))
userCacheDir, err := os.UserCacheDir()
if err != nil {
log.Fatalf("Unable to get user cache directory. %v", err)
}
cacheDir := filepath.Join(userCacheDir, "custodian-cask")
err = os.Mkdir(cacheDir, 0750)
if err != nil && !os.IsExist(err) {
log.Fatalf("Unable to create user cache directory. %v", err)
}
return filepath.Join(cacheDir, "cask-update-"+hash[0:5])
}
func handleSignals(ctx context.Context, id string, dockerClient *client.Client) {
gracefulExit := make(chan os.Signal, 1)
signal.Notify(gracefulExit, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-gracefulExit
fmt.Printf("Received %v, stopping container\n", sig)
timeout := 0
err := dockerClient.ContainerStop(ctx, id, container.StopOptions{Timeout: &timeout})
if err != nil {
fmt.Printf("Error stopping container: %v\n", err)
}
}()
}