-
Notifications
You must be signed in to change notification settings - Fork 24
/
utils.go
251 lines (206 loc) · 6.2 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package utils
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
)
var InvalidBlueprintURIError = fmt.Errorf("Inavlid blueprint URI")
var NameExceedsMaxLengthError = fmt.Errorf("Name exceeds the max length of 128 characters")
var NameContainsInvalidCharactersError = fmt.Errorf("Name contains invalid characters characters must be either a-z, A-Z, 0-9, -, _")
// ValidateName ensures that the name for a resource is within certain boundaries
// Valid characters: [a-z] [A-Z] _ - [0-9]
// Max length: 128
func ValidateName(name string) (bool, error) {
// check the length
if len(name) > 128 {
return false, NameExceedsMaxLengthError
}
r := regexp.MustCompile(`^[a-zA-Z0-9\-_]+$`)
ok := r.MatchString(name)
if !ok {
return false, NameContainsInvalidCharactersError
}
return true, nil
}
// ReplaceNonURIChars replaces any characters in the resrouce name which
// can not be used in a URI
func ReplaceNonURIChars(s string) (string, error) {
reg, err := regexp.Compile(`[^a-zA-Z0-9\-\.]+`)
if err != nil {
return "", err
}
return reg.ReplaceAllString(s, "-"), nil
}
// FQDN generates the full qualified name for a container
func FQDN(name, typeName string) string {
// ensure that the name is valid for URI schema
cleanName, err := ReplaceNonURIChars(name)
if err != nil {
panic(err)
}
fqdn := fmt.Sprintf("%s.%s.shipyard.run", cleanName, typeName)
return fqdn
}
// FQDNVolumeName creates a full qualified volume name
func FQDNVolumeName(name string) string {
// ensure that the name is valid for URI schema
cleanName, err := ReplaceNonURIChars(name)
if err != nil {
panic(err)
}
return fmt.Sprintf("%s.volume.shipyard.run", cleanName)
}
// CreateKubeConfigPath creates the file path for the KubeConfig file when
// using Kubernetes cluster
func CreateKubeConfigPath(name string) (dir, filePath string, dockerPath string) {
dir = fmt.Sprintf("%s/.shipyard/config/%s", HomeFolder(), name)
filePath = fmt.Sprintf("%s/kubeconfig.yaml", dir)
dockerPath = fmt.Sprintf("%s/kubeconfig-docker.yaml", dir)
// create the folders
err := os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
return
}
// CreateNomadConfigPath creates the file path for the Nomad config file when
// using Kubernetes cluster
func CreateNomadConfigPath(name string) (dir, filePath string) {
dir = fmt.Sprintf("%s/.shipyard/config/%s", HomeFolder(), name)
filePath = fmt.Sprintf("%s/nomad.json", dir)
// create the folders
err := os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
return
}
// HomeFolder returns the users homefolder this will be $HOME on windows and mac and
// USERPROFILE on windows
func HomeFolder() string {
if runtime.GOOS == "windows" {
return os.Getenv("USERPROFILE")
}
return os.Getenv("HOME")
}
// ShipyardHome returns the location of the shipyard
// folder, usually $HOME/.shipyard
func ShipyardHome() string {
return fmt.Sprintf("%s/.shipyard", HomeFolder())
}
// ShipyardTemp returns a temporary folder
func ShipyardTemp() string {
dir := filepath.Join(ShipyardHome(), "/tmp")
err := os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
return dir
}
// StateDir returns the location of the shipyard
// state, usually $HOME/.shipyard/state
func StateDir() string {
return fmt.Sprintf("%s/state", ShipyardHome())
}
// StatePath returns the full path for the state file
func StatePath() string {
return fmt.Sprintf("%s/state.json", StateDir())
}
// IsLocalFolder tests if the given path is a localfolder and can
// exist in the current filesystem
// TODO make more robust with error messages
// to improve UX
func IsLocalFolder(path string) bool {
if strings.HasPrefix(path, "/") || strings.HasPrefix(path, "./") {
// test to see if the folder or file exists
f, err := os.Open(path)
if err != nil || f == nil {
return false
}
return true
}
return false
}
// IsHCLFile tests if the given path resolves to a HCL config file
func IsHCLFile(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
if s.IsDir() {
return false
}
if filepath.Ext(s.Name()) != ".hcl" {
return false
}
return true
}
// GetBlueprintFolder parses a blueprint uri and returns the top level
// blueprint folder
// if the URI is not a blueprint will return an error
func GetBlueprintFolder(blueprint string) (string, error) {
// get the folder for the blueprint
parts := strings.Split(blueprint, "//")
if parts == nil || len(parts) != 2 {
fmt.Println(parts)
return "", InvalidBlueprintURIError
}
return parts[1], nil
}
// GetBlueprintLocalFolder returns the full storage path
// for the given blueprint URI
func GetBlueprintLocalFolder(blueprint string) string {
return filepath.Join(ShipyardHome(), "blueprints", blueprint)
}
// GetDockerSock returns the location of the Docker sock depending on the platform
func GetDockerSock() string {
//TODO: need to think about what happens if Docker is running at a TCP address rather than a socket
/*
if dh := os.Getenv("DOCKER_HOST"); dh != "" {
return dh
}
*/
return "/var/run/docker.sock"
}
// CheckVersion checks the current version against the latest online version
// if an update is required the function returns a string with the upgrade text
// and a boolean value set to false.
// If no upgrade is reuquired then the boolean will be set to true and the string
// will be empty.
func CheckVersion(current string) (string, bool) {
// try and get the latest version
resp, err := http.DefaultClient.Get("https://shipyard.run/latest")
if err != nil || resp.StatusCode != http.StatusOK {
// if we fail just return
return "", true
}
defer resp.Body.Close()
// get the version
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", true
}
ver := strings.TrimSpace(string(d))
// check the version
if current != ver {
return fmt.Sprintf(
fmt.Sprintf("\033[1;31m%s\033[0m", updateText),
ver, current,
), false
}
return "", true
}
var updateText = `
########################################################
SHIPYARD UPDATE
########################################################
The current version of shipyard is "%s", you have "%s".
To upgrade Shipyard please use your package manager or,
see the documentation at:
https://shipyard.run/docs/install for other options.
`