-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.go
313 lines (291 loc) · 7.8 KB
/
app.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
package main
import (
"fmt"
"github.com/cloudfoundry-community/gautocloud"
"github.com/cloudfoundry-community/gautocloud/cloudenv"
"github.com/cloudfoundry-community/gautocloud/connectors/generic"
"github.com/cloudfoundry-community/gautocloud/interceptor/cli/urfave"
"github.com/cloudfoundry-community/gautocloud/interceptor/configfile"
"github.com/cloudfoundry-community/gautocloud/loader"
"github.com/orange-cloudfoundry/cloud-sidecars"
"github.com/orange-cloudfoundry/cloud-sidecars/config"
"github.com/orange-cloudfoundry/cloud-sidecars/starter"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var cliInterceptor *urfave.CliInterceptor
var confFileIntercept *configfile.ConfigFileInterceptor
const configFileName = "sidecars-config.yml"
func init() {
log.SetOutput(os.Stdout)
os.Setenv(cloudenv.LOCAL_CONFIG_ENV_KEY, configFileName)
confFileIntercept = configfile.NewConfigFile()
cliInterceptor = urfave.NewCli()
gautocloud.RegisterConnector(generic.NewConfigGenericConnector(
config.Sidecars{},
confFileIntercept,
cliInterceptor,
))
}
type CloudSidecarApp struct {
*cli.App
}
func NewApp(version string) *CloudSidecarApp {
app := &CloudSidecarApp{cli.NewApp()}
app.Name = "cloud-sidecar"
app.Version = version
app.Usage = "Cloud sidecar cli"
app.ErrWriter = os.Stderr
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "config-path, c",
Value: "sidecars-config.yml",
Usage: "Path to the config file (This file will not be used in a cloud env like Cloud Foundry, Heroku or kubernetes)",
EnvVar: cloudenv.LOCAL_CONFIG_ENV_KEY,
},
cli.StringFlag{
Name: "dir, d",
Value: "",
Usage: "Set directory where to perform commands",
},
cli.StringFlag{
Name: "log-level, l",
Usage: "Log level to use",
},
cli.StringFlag{
Name: "cloud-env",
Usage: "Force cloud env detection",
},
cli.BoolFlag{
Name: "log-json, j",
Usage: "Write log in json",
},
cli.BoolFlag{
Name: "no-color",
Usage: "Logger will not display colors",
},
cli.StringFlag{
Name: "profile-dir",
Usage: "Set path where to put profiled files",
Value: "",
},
cli.IntFlag{
Name: "app-port",
Usage: "App listen port by default when not found from starter",
Value: 8080,
},
}
app.Commands = []cli.Command{
{
Name: "launch",
Usage: "launch all sidecar and main process, must be run as start command",
Action: launchRun,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "no-starter",
Usage: "Main process will not be started",
},
},
},
{
Name: "vendor",
Usage: "Vendor all sidecars in local for offline app",
Action: vendorRun,
},
{
Name: "setup",
Usage: "Download sidecars if needed and create profiled files, this should be run by a staging lifecycle (e.g.: cloud foundry buildpack lifecycle)",
Action: setupRun,
},
{
Name: "sha1",
Usage: "See sha1 corresponding to your artifacts",
Action: sha1Run,
},
}
return app
}
func sha1Run(c *cli.Context) error {
log.SetOutput(os.Stderr)
loadLogConfig(&config.Sidecars{
LogJson: c.GlobalBool("log-json"),
LogLevel: "ERROR",
NoColor: c.GlobalBool("no-color"),
})
fmt.Fprint(os.Stderr, "Retrieving sha1 for all of your sidecars ...\n")
l, err := createLauncher(c, false)
if err != nil {
return err
}
return l.ShowSidecarsSha1()
}
func setupRun(c *cli.Context) error {
initApp(c)
l, err := createLauncher(c, false)
if err != nil {
return err
}
return l.Setup()
}
func launchRun(c *cli.Context) error {
initApp(c)
l, err := createLauncher(c, true)
if err != nil {
return err
}
return l.Launch()
}
func vendorRun(c *cli.Context) error {
initApp(c)
l, err := createLauncher(c, false)
if err != nil {
return err
}
return l.DownloadArtifacts()
}
func initApp(c *cli.Context) {
loadLogConfig(&config.Sidecars{
LogJson: c.GlobalBool("log-json"),
LogLevel: c.GlobalString("log-level"),
NoColor: c.GlobalBool("no-color"),
})
}
func createLauncher(c *cli.Context, failWhenNoStarter bool) (*sidecars.Launcher, error) {
entry := log.WithField("component", "cli")
entry.Debug("Creating launcher ...")
conf, err := retrieveConfig(c)
if err != nil {
return nil, err
}
loadLogConfig(conf)
baseDir := c.GlobalString("dir")
profileDir := c.GlobalString("profile-dir")
if profileDir == "" {
profileDir = filepath.Join(baseDir, "profile.d")
}
var cStarter starter.Starter
if !c.Bool("no-starter") {
entry.Debug("Loading starter ...")
sidecarEnv := c.GlobalString("cloud-env")
for _, s := range starter.Retrieve() {
if s.Name() == sidecarEnv {
log.Infof("Starter for %s is loading", s.Name())
cStarter = s
break
}
if s.Detect() && sidecarEnv == "" {
log.Infof("Starter for %s is loading", s.Name())
cStarter = s
break
}
}
if cStarter == nil && failWhenNoStarter {
details := ""
if sidecarEnv != "" {
details = fmt.Sprintf("for cloud-env %s", sidecarEnv)
}
return nil, fmt.Errorf("Could not found starter %s", details)
}
entry.Debug("Finished loading starter.")
}
defaultPort := c.GlobalInt("app-port")
l := sidecars.NewLauncher(*conf, cStarter, profileDir, os.Stdout, os.Stderr, defaultPort)
entry.Debug("Finished creating launcher.")
return l, nil
}
func retrieveConfig(c *cli.Context) (*config.Sidecars, error) {
// Has been modified in init, reset it after loading config for possible env var usage in sidecars
defer os.Unsetenv(cloudenv.LOCAL_CONFIG_ENV_KEY)
log.WithField("component", "cli").Debug("Loading configuration ...")
cliInterceptor.SetContext(c)
confPath, baseDir := findConfPathAndDir(c)
confFileIntercept.SetConfigPath(confPath)
conf := &config.Sidecars{}
err := gautocloud.Inject(conf)
if _, ok := err.(loader.ErrGiveService); ok {
log.Warnf("Cannot found configuration from gautocloud, fallback to %s file", confPath)
var b []byte
b, err = ioutil.ReadFile(confPath)
if err != nil {
return nil, fmt.Errorf("configuration loading from %s error: %s", confPath, err.Error())
}
err = yaml.Unmarshal(b, conf)
if err != nil {
return nil, fmt.Errorf("configuration loading from %s error: %s", confPath, err.Error())
}
}
conf.Dir = baseDir
log.WithField("component", "cli").Debug("Finished loading configuration.")
return conf, err
}
func findConfPathAndDir(c *cli.Context) (confPath string, dir string) {
dir = c.GlobalString("dir")
if dir == "" {
dir, _ = os.Getwd()
}
confPath = filepath.Join(dir, c.GlobalString("config-path"))
if _, err := os.Stat(confPath); os.IsNotExist(err) {
confPath = filepath.Join(dir, sidecars.PathSidecarsWd, configFileName)
log.Warnf(
"Config file not found on %s, trying to find config file at %s .",
c.GlobalString("config-path"),
confPath,
)
}
if _, err := os.Stat(confPath); os.IsNotExist(err) {
log.Warnf(
"Config file not found on %s, trying to auto-find on first sub folder .",
confPath,
)
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
if !file.IsDir() {
continue
}
tmpConfPath := filepath.Join(dir, file.Name(), sidecars.PathSidecarsWd, configFileName)
if _, err := os.Stat(tmpConfPath); err == nil {
confPath = tmpConfPath
dir = filepath.Join(dir, file.Name())
log.Warnf("Config file found at %s", confPath)
}
}
}
return
}
func loadLogConfig(c *config.Sidecars) {
if c.LogJson {
log.SetFormatter(&log.JSONFormatter{})
} else {
log.SetFormatter(&log.TextFormatter{
DisableColors: c.NoColor,
})
}
if c.LogLevel == "" {
return
}
switch strings.ToUpper(c.LogLevel) {
case "ERROR":
log.SetLevel(log.ErrorLevel)
return
case "WARN":
log.SetLevel(log.WarnLevel)
return
case "DEBUG":
log.SetLevel(log.DebugLevel)
return
case "PANIC":
log.SetLevel(log.PanicLevel)
return
case "FATAL":
log.SetLevel(log.FatalLevel)
return
}
}