This repository has been archived by the owner on Jun 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 397
/
up.go
231 lines (200 loc) · 6.03 KB
/
up.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
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"github.com/ghodss/yaml"
"github.com/rjeczalik/notify"
"github.com/spf13/cobra"
"k8s.io/helm/pkg/ignore"
"github.com/Azure/draft/pkg/draft"
"github.com/Azure/draft/pkg/draft/manifest"
"github.com/Azure/draft/pkg/draft/pack"
)
const upDesc = `
This command archives the current directory into a tar archive and uploads it to
the draft server.
Adding the "watch" option to draft.toml makes draft automatically archive and
upload whenever local files are saved. Draft delays a couple seconds to ensure
that changes have stopped before uploading, but that can be altered by the
"watch_delay" option.
`
const (
environmentEnvVar = "DRAFT_ENV"
ignoreFileName = ".draftignore"
)
type upCmd struct {
Client *draft.Client
Out io.Writer
Manifest *manifest.Manifest
src string
}
func newUpCmd(out io.Writer) *cobra.Command {
var (
up = &upCmd{
Out: out,
Manifest: manifest.New(),
}
runningEnvironment string
)
cmd := &cobra.Command{
Use: "up [path]",
Short: "upload the current directory to the draft server for deployment",
Long: upDesc,
PreRunE: setupConnection,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
up.src = args[0]
}
up.Client = ensureDraftClient(up.Client)
up.Manifest = manifest.New()
if up.src == "" || up.src == "." {
var err error
up.src, err = os.Getwd()
if err != nil {
return err
}
}
draftToml, err := ioutil.ReadFile(filepath.Join(up.src, "draft.toml"))
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
if err = toml.Unmarshal(draftToml, up.Manifest); err != nil {
return fmt.Errorf("could not unmarshal draft.toml: %v", err)
}
}
return up.run(runningEnvironment)
},
}
f := cmd.Flags()
f.StringVarP(&runningEnvironment, "environment", "e", defaultDraftEnvironment(), "the environment (development, staging, qa, etc) that draft will run under")
return cmd
}
func vals(e *manifest.Environment, cwd string) ([]byte, error) {
base := map[string]interface{}{}
// load $PWD/chart/values.yaml as the base config
valuesPath := filepath.Join(cwd, pack.ChartDir, pack.ValuesfileName)
if _, err := os.Stat(valuesPath); os.IsNotExist(err) {
return []byte{}, errors.New("Could not detect a proper helm chart\nTry running a `draft create` first")
}
bytes, err := ioutil.ReadFile(valuesPath)
if err != nil {
return []byte{}, err
}
if err := yaml.Unmarshal(bytes, &base); err != nil {
return []byte{}, fmt.Errorf("failed to parse %s: %s", valuesPath, err)
}
return yaml.Marshal(base)
}
func (u *upCmd) run(environment string) (err error) {
env := u.Manifest.Environments[environment]
cwd := u.src
u.Client.OptionWait = env.Wait
rawVals, err := vals(env, cwd)
if err != nil {
return err
}
if err = u.doUp(environment, cwd, rawVals); err != nil {
return err
}
// if `--watch=false`, return now
if !env.Watch {
return nil
}
fmt.Fprintln(u.Out, "Watching local files for changes...")
notifyPath := filepath.Join(cwd, "...")
log.Debugf("NOTIFY PATH: %s", notifyPath)
// make a buffered channel of filesystem notification events
ch := make(chan notify.EventInfo, 1)
// watch the current directory and everything under it, sending events to the channel
if err := notify.Watch(notifyPath, ch, notify.All); err != nil {
log.Fatalf("could not watch local filesystem for changes: %v", err)
}
defer notify.Stop(ch)
r, err := ignore.ParseFile(ignoreFileName)
if err != nil {
// only fail if file can't be parsed but exists
if _, err := os.Stat(ignoreFileName); os.IsExist(err) {
log.Fatalf("could not load ignore watch list %v", err)
}
}
// create a timer to enforce a "quiet period" before deploying the app
timer := time.NewTimer(time.Hour)
timer.Stop()
delay := time.Duration(env.WatchDelay) * time.Second
for {
select {
case evt := <-ch:
log.Debugf("Event %s", evt)
p := strings.TrimPrefix(evt.Path(), cwd+"/")
fi, err := os.Stat(evt.Path())
if err != nil {
// create dummy file info for removed file or directory
fi = removedFileInfo(filepath.Base(evt.Path()))
}
// only rebuild if the changed file isn't in our ignore list
if r != nil && r.Ignore(p, fi) {
continue
}
// ignore manually everything inside the .git/ directory as
// helm ignore file doesn't have directory and whole content
// (subdir of subdir) ignore support yet.
if filepath.HasPrefix(p, ".git/") {
continue
}
// reset the timer when files have changed
timer.Reset(delay)
case <-timer.C:
if err = u.doUp(environment, cwd, rawVals); err != nil {
return err
}
fmt.Fprintln(u.Out, "Watching local files for changes...")
}
}
}
func (u *upCmd) doUp(environment string, cwd string, vals []byte) (err error) {
env := u.Manifest.Environments[environment]
if env.BuildTarPath != "" && env.ChartTarPath != "" {
buildTar, e := os.Open(env.BuildTarPath)
if e != nil {
return e
}
chartTar, e := os.Open(env.ChartTarPath)
if e != nil {
return e
}
err = u.Client.Up(env.Name, env.Namespace, u.Out, buildTar, chartTar, vals)
} else {
err = u.Client.UpFromDir(env.Name, env.Namespace, u.Out, cwd, vals)
}
// format error before returning
if err != nil {
err = fmt.Errorf("there was an error running 'draft up': %v", err)
}
return
}
func defaultDraftEnvironment() string {
env := os.Getenv(environmentEnvVar)
if env == "" {
env = manifest.DefaultEnvironmentName
}
return env
}
// removedFileInfo fake file info for
// ignore library only use IsDir() in negative pattern
type removedFileInfo string
func (n removedFileInfo) Name() string { return string(n) }
func (removedFileInfo) Size() int64 { return 0 }
func (removedFileInfo) Mode() os.FileMode { return 0 }
func (removedFileInfo) ModTime() time.Time { return time.Time{} }
func (removedFileInfo) IsDir() bool { return false }
func (removedFileInfo) Sys() interface{} { return nil }