-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcf_get_events.go
267 lines (235 loc) · 7.73 KB
/
cf_get_events.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
// Copyright (c) 2016 ECS Team, Inc. - All Rights Reserved
// https://github.com/ECSTeam/cloudfoundry-top-plugin
//
// 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 (
"fmt"
"github.com/cloudfoundry/cli/plugin"
"time"
"os"
"regexp"
"strings"
"github.com/simonleung8/flags"
"bytes"
"encoding/json"
)
// Events represents Buildpack Usage CLI interface
type Events struct{}
// Metadata is the data retrived from the response json
type Metadata struct {
GUID string `json:"guid"`
}
// Inputs represent the parsed input args
type Inputs struct {
fromDate time.Time
toDate time.Time
isCsv bool
isJson bool
}
// GetMetadata provides the Cloud Foundry CLI with metadata to provide user about how to use `get-events` command
func (c *Events) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "get-events",
Version: plugin.VersionType{
Major: 0,
Minor: 6,
Build: 0,
},
Commands: []plugin.Command{
{
Name: "get-events",
HelpText: "Get microservice events (by [email protected])",
UsageDetails: plugin.Usage {
Usage: UsageText(),
},
},
},
}
}
func main() {
plugin.Start(new(Events))
}
// Run is what is executed by the Cloud Foundry CLI when the get-events command is specified
func (c Events) Run(cli plugin.CliConnection, args []string) {
var ins Inputs
switch args[0] {
case "get-events":
ins = c.buildClientOptions(args)
case "example-alternate-command":
default:
return
}
orgs := c.GetOrgs(cli)
spaces := c.GetSpaces(cli)
apps := c.GetAppData(cli)
events := c.GetEventsData(cli, ins)
results := c.FilterResults(cli, ins, orgs, spaces, apps, events)
if (ins.isCsv) {
c.EventsInCSVFormat(results)
} else {
c.EventsInJsonFormat(results)
}
}
func Usage(code int) {
fmt.Println("\nUsage: ", UsageText())
os.Exit(code)
}
func UsageText() (string) {
usage := "cf get-events [options]" +
"\n where options include: " +
"\n --today : get all events for today (till now)" +
"\n --yesterday : get events for yesterday only" +
"\n --yesterday-on : get events from yesterday onwards (till now)" +
"\n --all : get all events (defaults to last 90 days)" +
"\n --json : list output in json format (default is csv)\n" +
"\n --from <yyyymmdd> : get events from given date onwards (till now)" +
"\n --from <yyyymmddhhmmss> : get events from given date and time onwards (till now)" +
"\n --to <yyyymmdd> : get events till given date" +
"\n --to <yyyymmddhhmmss> : get events till given date and time\n" +
"\n --from <yyyymmdd> --to <yyyymmdd>" +
"\n --from <yyyymmddhhmmss> --to <yyyymmddhhmmss>"
return usage
}
func GetStartOfDay(today time.Time) (time.Time) {
var now = fmt.Sprintf("%s", today.Format("2006-01-02"))
t, _ := time.Parse(time.RFC3339, now+"T00:00:00Z")
return t
}
func GetEndOfDay(today time.Time) (time.Time) {
var now = fmt.Sprintf("%s", today.Format("2006-01-02"))
t, _ := time.Parse(time.RFC3339, now+"T23:59:59Z")
return t
}
// sanitize data by replacing \r, and \n with ';'
func sanitize(data string) (string) {
var re = regexp.MustCompile(`\r?\n`)
var str = re.ReplaceAllString(data, ";")
str = strings.Replace(str, ";;", ";", 1)
return str;
}
// read arguments passed for the plugin
func (c *Events) buildClientOptions(args[] string) (Inputs) {
fc := flags.New()
fc.NewBoolFlag("all", "all", " get all events (defaults to last 90 days)")
fc.NewBoolFlag("today", "today", "get all events for today (till now)")
fc.NewBoolFlag("yesterday", "yest", "get events from yesterday only")
fc.NewBoolFlag("yesterday-on", "yon", "get events for yesterday onwards (till now)")
fc.NewStringFlag("from", "fr", "get events from given date [+ time] onwards (till now)")
fc.NewStringFlag("to", "to", "get events till given date [+ time]")
fc.NewBoolFlag("json", "js", "list output in json format (default is csv)")
err := fc.Parse(args[1:]...)
if err != nil {
fmt.Println("\n Receive error reading arguments ... ", err)
Usage(1)
}
today := time.Now()
var ins Inputs
ins.isCsv = true
ins.isJson = false
ins.fromDate = GetStartOfDay(today)
ins.toDate = time.Now()
if (fc.IsSet("all")) {
nintyDays := time.Hour * -(24 * 90)
ins.fromDate = today.Add(nintyDays) // today - 90 days
}
if (fc.IsSet("today")) {
ins.fromDate = GetStartOfDay(today)
}
if (fc.IsSet("yesterday")) {
oneDay := time.Hour * -24
ins.fromDate = GetStartOfDay(today.Add(oneDay)) // today - 1 day
ins.toDate = GetEndOfDay(ins.fromDate )
}
if (fc.IsSet("yesterday-on")) {
oneDay := time.Hour * -24
ins.fromDate = GetStartOfDay(today.Add(oneDay)) // today - 1 day
}
if (fc.IsSet("from")) {
var value = fc.String("from")
var layout string
switch len(value) {
case 8:
layout = "20060102" // yyyymmdd
case 14:
layout = "20060102150405" // yyyymmddhhmmss
default:
fmt.Println("Error: Failed to parse `from` date - ", value)
fmt.Println(err)
Usage(1)
}
t, err := time.Parse(layout, value)
// fmt.Println("-------> (1) filter date - ", t, filterDate, err)
if err != nil {
fmt.Println("Error: Failed to parse `from` date - ", value)
fmt.Println(err)
Usage(1)
} else {
ins.fromDate = t
}
}
if (fc.IsSet("to")) {
var value = fc.String("to")
const layout = "20060102150405" // yyyymmdd
switch len(value) {
case 8:
value = value + "235959"
case 14:
default:
fmt.Println("Error: Failed to parse `from` date - ", value)
fmt.Println(err)
Usage(1)
}
t, err := time.Parse(layout, value)
// fmt.Println("-------> (1) filter date - ", t, filterDate, err)
if err != nil {
fmt.Println("Error: Failed to parse given date - ", value)
fmt.Println(err)
Usage(1)
} else {
// filterDate = fmt.Sprintf("%s", t.Format("2006-01-02"))
ins.toDate = t
}
}
if (fc.IsSet("json")) {
ins.isJson = true
ins.isCsv = false
}
// fmt.Println("-------> (1) ins - ", ins.fromDate, ins.toDate)
return ins
}
// prints the results as a csv text to console
func (c Events) EventsInCSVFormat(results OutputResults) {
fmt.Println("")
fmt.Printf(results.Comment)
// "20161212", "dr", "lab", "app", "pcf-status", "pcf-status", "app.crash", "crashed", "2 error(s) occurred:\n\n* 2 error(s) occurred:\n\n* Exited with status 255 (out of memory)\n* cancelled\n* 1 error(s) occurred:\n\n* cancelled"
// "2016-12-09T21:44:46Z", "demo", "sandbox", "app", "test-nodejs", "admin", "app.update", "stopped", ""
fmt.Printf("%s,%s,%s,%s,%s,%s,%s,%s\n", "DATE", "ORG", "SPACE", "ACTEE-TYPE", "ACTEE-NAME", "ACTOR", "EVENT TYPE", "DETAILS")
for _, val := range results.Resources {
var mdata = sanitize(fmt.Sprintf("%+v", val.Entity.Metadata))
fmt.Printf("%s,%s,%s,%s,%s,%s,%s,%s\n",
val.Entity.Timestamp, val.Entity.Org, val.Entity.Space,
val.Entity.ActeeType, val.Entity.ActeeName, val.Entity.ActorName, val.Entity.Type, mdata)
}
}
// prints the results as a json text to console
func (c Events) EventsInJsonFormat(results OutputResults) {
var out bytes.Buffer
b, _ := json.Marshal(results)
err := json.Indent(&out, b, "", "\t")
if err != nil {
fmt.Println(" Recevied error formatting json output.")
} else {
fmt.Println(out.String())
}
}