-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
256 lines (230 loc) · 7.59 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
package main
import (
"fmt"
"os"
"regexp"
"net/http"
"encoding/json"
"code.cloudfoundry.org/cli/plugin"
"code.cloudfoundry.org/cli/cf/terminal"
"code.cloudfoundry.org/cli/cf/trace"
"github.com/parnurzeal/gorequest"
"github.com/simonleung8/flags"
"github.com/xiwenc/cf-fastpush-controller/lib"
"io/ioutil"
"strings"
)
/*
* This is the struct implementing the interface defined by the core CLI. It can
* be found at "github.com/cloudfoundry/cli/plugin/plugin.go"
*
*/
type FastPushPlugin struct {
ui terminal.UI
}
type VCAPApplication struct {
VCAP_APPLICATION struct {
ApplicationID string `json:"application_id"`
ApplicationVersion string `json:"application_version"`
} `json:"VCAP_APPLICATION"`
}
/*
* This function must be implemented by any plugin because it is part of the
* plugin interface defined by the core CLI.
*
* Run(....) is the entry point when the core CLI is invoking a command defined
* by a plugin. The first parameter, plugin.CliConnection, is a struct that can
* be used to invoke cli commands. The second paramter, args, is a slice of
* strings. args[0] will be the name of the command, and will be followed by
* any additional arguments a cli user typed in.
*
* Any error handling should be handled with the plugin itself (this means printing
* user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
* 1 should the plugin exits nonzero.
*/
func (c *FastPushPlugin) Run(cliConnection plugin.CliConnection, args []string) {
// Ensure that the user called the command fast-push
// alias fp is auto mapped
var dryRun bool
traceLogger := trace.NewLogger(os.Stdout, true, os.Getenv("CF_TRACE"), "")
c.ui = terminal.NewUI(os.Stdin, os.Stdout, terminal.NewTeePrinter(os.Stdout), traceLogger)
cliLogged, err := cliConnection.IsLoggedIn()
if err != nil {
c.ui.Failed(err.Error())
}
if cliLogged == false {
panic("Cannot perform fast-push without being logged in to CF")
}
if args[0] == "fast-push" || args[0] == "fp" {
if len(args) == 1 {
c.showUsage(args)
return
}
// set flag for dry run
fc := flags.New()
fc.NewBoolFlag("dry", "d", "bool dry run flag")
err := fc.Parse(args[1:]...)
if err != nil {
c.ui.Failed(err.Error())
}
// check if the user asked for a dry run or not
if fc.IsSet("dry") {
dryRun = fc.Bool("dry")
} else {
c.ui.Warn("warning: dry run not set, commencing fast push")
}
c.ui.Say("Running the fast-push command")
c.ui.Say("Target app: %s \n", args[1])
c.FastPush(cliConnection, args[1], dryRun)
} else if args[0] == "fast-push-status" || args[0] == "fps" {
c.FastPushStatus(cliConnection, args[1])
} else {
return
}
}
func (c *FastPushPlugin) GetAuthToken(cliConnection plugin.CliConnection, appName string) string {
app, err := cliConnection.GetApp(appName)
if err != nil {
panic(err)
}
return app.Guid
}
func (c *FastPushPlugin) FastPushStatus(cliConnection plugin.CliConnection, appName string) {
authToken := c.GetAuthToken(cliConnection, appName)
apiEndpoint := c.GetApiEndpoint(cliConnection, appName)
status := lib.Status{}
request := gorequest.New()
_, body, err := request.Get(apiEndpoint + "/status").Set("x-auth-token", authToken).End()
if err != nil {
panic(err)
}
json.Unmarshal([]byte(body), &status)
c.ui.Say(status.Health)
}
func (c *FastPushPlugin) FastPush(cliConnection plugin.CliConnection, appName string, dryRun bool) {
// Please check what GetApp returns here
// https://github.com/cloudfoundry/cli/blob/master/plugin/models/get_app.go
authToken := c.GetAuthToken(cliConnection, appName)
if dryRun {
// NEED TO HANDLE DRY RUN
c.ui.Warn("warning: No changes will be applied, this is a dry run !!")
}
apiEndpoint := c.GetApiEndpoint(cliConnection, appName)
request := gorequest.New()
response, body, err := request.Get(apiEndpoint + "/files").Set("x-auth-token", authToken).End()
if err != nil {
panic(err)
}
if response.StatusCode != http.StatusOK {
panic("Unexpected status code received while retrieving filelist")
}
remoteFiles := map[string]*lib.FileEntry{}
json.Unmarshal([]byte(body), &remoteFiles)
localFiles := lib.ListFiles()
filesToUpload := c.ComputeFilesToUpload(localFiles, remoteFiles)
payload, _ := json.Marshal(filesToUpload)
_, body, err = request.Put(apiEndpoint+"/files").Set("x-auth-token", authToken).Send(string(payload)).End()
if err != nil {
panic(err)
}
status := lib.Status{}
json.Unmarshal([]byte(body), &status)
c.ui.Say(status.Health)
}
/*
* This function must be implemented as part of the plugin interface
* defined by the core CLI.
*
* GetMetadata() returns a PluginMetadata struct. The first field, Name,
* determines the name of the plugin which should generally be without spaces.
* If there are spaces in the name a user will need to properly quote the name
* during uninstall otherwise the name will be treated as seperate arguments.
* The second value is a slice of Command structs. Our slice only contains one
* Command Struct, but could contain any number of them. The first field Name
* defines the command `cf basic-plugin-command` once installed into the CLI. The
* second field, HelpText, is used by the core CLI to display help information
* to the user in the core commands `cf help`, `cf`, or `cf -h`.
*/
func (c *FastPushPlugin) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "FastPushPlugin",
Version: plugin.VersionType{
Major: 1,
Minor: 1,
Build: 0,
},
MinCliVersion: plugin.VersionType{
Major: 6,
Minor: 28,
Build: 0,
},
Commands: []plugin.Command{
plugin.Command{
Name: "fast-push",
Alias: "fp",
HelpText: "fast-push removes the need to deploy your app again for a small change",
UsageDetails: plugin.Usage{
Usage: "cf fast-push APP_NAME\n cf fp APP_NAME",
Options: map[string]string{
"dry": "--dry, dry run for fast-push",
},
},
},
plugin.Command{
Name: "fast-push-status",
Alias: "fps",
HelpText: "fast-push-status shows the current state of your application",
UsageDetails: plugin.Usage{
Usage: "cf fast-push-status APP_NAME\n cf fps APP_NAME",
},
},
},
}
}
/*
* Unlike most Go programs, the `Main()` function will not be used to run all of the
* commands provided in your plugin. Main will be used to initialize the plugin
* process, as well as any dependencies you might require for your
* plugin.
*/
func main() {
plugin.Start(new(FastPushPlugin))
}
func (c *FastPushPlugin) showUsage(args []string) {
for _, cmd := range c.GetMetadata().Commands {
if cmd.Name == args[0] {
fmt.Println("Invalid Usage: \n", cmd.UsageDetails.Usage)
}
}
}
func (c *FastPushPlugin) GetApiEndpoint(cliConnection plugin.CliConnection, appName string) string {
results, err := cliConnection.CliCommandWithoutTerminalOutput("app", appName)
if err != nil {
c.ui.Failed(err.Error())
}
for _, line := range results {
match, _ := regexp.MatchString("^urls:.*", line)
if match {
parts := strings.Fields(line)
if len(parts) > 1 {
return "https://" + parts[1] + "/_fastpush"
}
}
}
panic("Could not find usable route for this app. Make sure at least one route is mapped to this app")
}
func (c *FastPushPlugin) ComputeFilesToUpload(local map[string]*lib.FileEntry, remote map[string]*lib.FileEntry) map[string]*lib.FileEntry {
filesToUpload := map[string]*lib.FileEntry{}
for path, f := range local {
if remote[path] == nil {
c.ui.Say("[NEW] " + path)
f.Content, _ = ioutil.ReadFile(path)
filesToUpload[path] = f
} else if remote[path].Checksum != f.Checksum {
c.ui.Say("[MOD] " + path)
f.Content, _ = ioutil.ReadFile(path)
filesToUpload[path] = f
}
}
return filesToUpload
}