-
Notifications
You must be signed in to change notification settings - Fork 62
/
utils.go
236 lines (209 loc) · 6.13 KB
/
utils.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
/*
Copyright 2015 Home Office All rights reserved.
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.
*/
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
"strings"
"time"
"os/exec"
"path/filepath"
"github.com/golang/glog"
"gopkg.in/yaml.v2"
)
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
// showUsage prints the command usage and exits
// message : an error message to display if exiting with an error
func showUsage(message string, args ...interface{}) {
flag.PrintDefaults()
if message != "" {
fmt.Printf("\n[error] "+message+"\n", args...)
os.Exit(1)
}
os.Exit(0)
}
// hasKey checks to see if a key is present
// key : the key we are looking for
// data : a map of strings to something we are looking at
func hasKey(key string, data map[string]interface{}) bool {
_, found := data[key]
return found
}
// getKeys retrieves a list of keys from the map
// data : the map which you wish to extract the keys from
func getKeys(data map[string]interface{}) []string {
var list []string
for key := range data {
list = append(list, key)
}
return list
}
// readConfigFile read in a configuration file
// filename : the path to the file
func readConfigFile(filename, fileFormat string) (*vaultAuthOptions, error) {
// step: check the file exists
if exists, err := fileExists(filename); !exists {
return nil, fmt.Errorf("the file: %s does not exist", filename)
} else if err != nil {
return nil, err
}
// step: we only read in json or yaml formats
suffix := path.Ext(filename)
switch suffix {
case ".yaml":
fallthrough
case ".yml":
return readYAMLFile(filename)
default:
return readJSONFile(filename, fileFormat)
}
}
// readJsonFile read in and unmarshall the data into a map
// filename : the path to the file container the json data
func readJSONFile(filename, format string) (*vaultAuthOptions, error) {
opts := &vaultAuthOptions{}
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
// unmarshall the data
err = json.Unmarshal(content, &opts)
if err != nil && format == "default" {
return nil, err
}
if err != nil {
return nil, err
}
if format == "kubernetes-vault" && opts.ClientToken != "" {
opts.Method = "token"
opts.Token = opts.ClientToken
}
return opts, nil
}
// readYAMLFile read in and unmarshall the data into a map
// filename : the path to the file container the yaml data
func readYAMLFile(filename string) (*vaultAuthOptions, error) {
o := &vaultAuthOptions{}
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(content, o)
if err != nil {
return nil, err
}
return o, nil
}
// getDurationWithin generate a random integer between min and max
// min : the smallest number we can accept
// max : the largest number we can accept
func getDurationWithin(min, max int) time.Duration {
jitter := max - min
if jitter <= 0 {
jitter = 1
}
duration := rand.Intn(jitter) + min
return time.Duration(duration) * time.Second
}
// getEnv checks to see if an environment variable exists otherwise uses the default
// env : the name of the environment variable you are checking for
// value : the default value to return if the value is not there
func getEnv(env, value string) string {
if v := os.Getenv(env); v != "" {
return v
}
return value
}
// fileExists checks to see if a file exists
// filename : the full path to the file you are checking for
func fileExists(filename string) (bool, error) {
if _, err := os.Stat(filename); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
// processResource is responsible for generating the specific content from the resource
// rn : a point to the vault resource
// data : a map of the related secret associated to the resource
func processResource(rn *VaultResource, data map[string]interface{}) (err error) {
// step: determine the resource path
filename := rn.GetFilename()
if !strings.HasPrefix(filename, "/") {
filename = fmt.Sprintf("%s/%s", options.outputDir, filepath.Base(filename))
}
// step: format and write the file
switch rn.format {
case "yaml":
fallthrough
case "yml":
err = writeYAMLFile(filename, data, rn.fileMode)
case "json":
err = writeJSONFile(filename, data, rn.fileMode)
case "ini":
err = writeIniFile(filename, data, rn.fileMode)
case "csv":
err = writeCSVFile(filename, data, rn.fileMode)
case "env":
err = writeEnvFile(filename, data, rn.fileMode)
case "cert":
err = writeCertificateFile(filename, data, rn.fileMode)
case "txt":
err = writeTxtFile(filename, data, rn.fileMode)
case "bundle":
err = writeCertificateBundleFile(filename, data, rn.fileMode)
case "credential":
err = writeCredentialFile(filename, data, rn.fileMode)
case "template":
err = writeTemplateFile(filename, data, rn.fileMode, rn.templateFile)
case "aws":
err = writeAwsCredentialFile(filename, data, rn.fileMode)
default:
return fmt.Errorf("unknown output format: %s", rn.format)
}
// step: check for an error
if err != nil {
return err
}
// step: check if we need to execute a command
if rn.execPath != "" {
glog.V(10).Infof("executing the command: %s for resource: %s", rn.execPath, filename)
parts := strings.Split(rn.execPath, " ")
var args []string
if len(parts) > 1 {
args = parts[1:]
} else {
args = []string{filename}
}
cmd := exec.Command(parts[0], args...)
cmd.Start()
timer := time.AfterFunc(options.execTimeout, func() {
if err = cmd.Process.Kill(); err != nil {
glog.Errorf("failed to kill the command, pid: %d, error: %s", cmd.Process.Pid, err)
}
})
// step: wait for the command to finish
err = cmd.Wait()
timer.Stop()
}
return err
}