-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
407 lines (340 loc) · 9.17 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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"code.cloudfoundry.org/clock"
"code.cloudfoundry.org/lager/v3"
"code.cloudfoundry.org/lager/v3/lagerflags"
"code.cloudfoundry.org/routing-api/models"
routing_api "code.cloudfoundry.org/routing-api"
"code.cloudfoundry.org/routing-api-cli/commands"
"code.cloudfoundry.org/routing-api/trace"
uaaclient "code.cloudfoundry.org/routing-api/uaaclient"
"github.com/urfave/cli"
)
const (
RTR_TRACE = "RTR_TRACE"
DefaultTokenFetchRetryInterval = 5 * time.Second
DefaultTokenFetchNumRetries = uint32(1)
DefaultExpirationBufferTime = int64(30)
)
var version string
var skipVerificationFlag = cli.BoolFlag{
Name: "skip-tls-verification, k",
Usage: "Skip OAuth TLS Verification (optional)",
}
var flags = []cli.Flag{
cli.StringFlag{
Name: "api",
Usage: "Endpoint for the routing-api. (required)",
},
cli.StringFlag{
Name: "client-id",
Usage: "Id of the OAuth client. (required)",
},
cli.StringFlag{
Name: "client-secret",
Usage: "Secret for OAuth client. (required)",
},
cli.StringFlag{
Name: "oauth-url",
Usage: "URL for OAuth client. (required)",
},
skipVerificationFlag,
cli.StringFlag{
Name: "ca-certs",
Usage: "CA for UAA client (optional)",
},
}
var eventsFlags = []cli.Flag{
cli.BoolFlag{
Name: "http",
Usage: "Stream HTTP events",
},
cli.BoolFlag{
Name: "tcp",
Usage: "Stream TCP events",
},
}
var cliCommands = []cli.Command{
{
Name: "register",
Usage: "Registers routes with the routing-api",
Description: `Routes must be specified in JSON format, like so:
'[{"route":"foo.com", "port":12345, "ip":"1.2.3.4", "ttl":5, "log_guid":"log-guid"}]'`,
Action: registerRoutes,
Flags: flags,
},
{
Name: "unregister",
Usage: "Unregisters routes with the routing-api",
Description: `Routes must be specified in JSON format, like so:
'[{"route":"foo.com", "port":12345, "ip":"1.2.3.4"]'`,
Action: unregisterRoutes,
Flags: flags,
},
{
Name: "list",
Usage: "Lists the currently registered routes",
Action: listRoutes,
Flags: flags,
},
{
Name: "events",
Usage: "Stream events from the Routing API",
Action: streamEvents,
Flags: append(flags, eventsFlags...),
},
}
var environmentVariableHelp = `ENVIRONMENT VARIABLES:
RTR_TRACE=true Print API request diagnostics to stdout`
func main() {
lagerflags.AddFlags(flag.CommandLine)
fmt.Println()
app := cli.NewApp()
app.Name = "rtr"
app.Usage = "A CLI for the Router API server."
authors := []cli.Author{cli.Author{Name: "Cloud Foundry Routing Team", Email: "cf-dev@lists.cloudfoundry.org"}}
app.Authors = authors
app.Commands = cliCommands
app.CommandNotFound = commandNotFound
app.Version = version
app.Flags = []cli.Flag{skipVerificationFlag}
cli.AppHelpTemplate = cli.AppHelpTemplate + environmentVariableHelp + "\n"
trace.NewLogger(os.Getenv(RTR_TRACE))
err := app.Run(os.Args)
if err != nil {
log.Fatalf("Error running routing-api-cli: %s\n", err)
}
os.Exit(0)
}
func registerRoutes(c *cli.Context) {
issues := checkFlags(c)
errorMessage := "route registration failed:"
issues = append(issues, checkArguments(c, "register")...)
if len(issues) > 0 {
printHelpForCommand(c, issues, "register")
}
desiredRoutes := c.Args().First()
var routes []models.Route
err := json.Unmarshal([]byte(desiredRoutes), &routes)
checkError(errorMessage, err)
client, err := newRoutingApiClient(c)
checkError(errorMessage, err)
err = commands.Register(client, routes)
checkError(errorMessage, err)
fmt.Printf("Successfully registered routes: %s\n", desiredRoutes)
}
func unregisterRoutes(c *cli.Context) {
issues := checkFlags(c)
errorMessage := "route unregistration failed:"
issues = append(issues, checkArguments(c, "unregister")...)
if len(issues) > 0 {
printHelpForCommand(c, issues, "unregister")
}
desiredRoutes := c.Args().First()
var routes []models.Route
err := json.Unmarshal([]byte(desiredRoutes), &routes)
checkError(errorMessage, err)
client, err := newRoutingApiClient(c)
checkError(errorMessage, err)
err = commands.UnRegister(client, routes)
checkError(errorMessage, err)
fmt.Printf("Successfully unregistered routes: %s\n", desiredRoutes)
}
func listRoutes(c *cli.Context) {
errorMessage := "listing routes failed:"
issues := checkFlags(c)
issues = append(issues, checkArguments(c, "list")...)
if len(issues) > 0 {
printHelpForCommand(c, issues, "list")
}
client, err := newRoutingApiClient(c)
checkError(errorMessage, err)
routes, err := commands.List(client)
if err != nil {
fmt.Println("listing routes failed:", err)
os.Exit(3)
}
prettyRoutes, _ := json.Marshal(routes)
fmt.Printf("%v\n", string(prettyRoutes))
}
func streamEvents(c *cli.Context) {
issues := checkFlags(c)
issues = append(issues, checkArguments(c, "events")...)
if len(issues) > 0 {
printHelpForCommand(c, issues, "events")
}
streamHttp := c.Bool("http")
streamTcp := c.Bool("tcp")
if !streamHttp && !streamTcp {
streamHttp = true
streamTcp = true
}
client, err := newRoutingApiClient(c)
checkError("streaming events failed:", err)
errorChan := make(chan error)
eventChan := make(chan string)
numOfSubscriptions := 0
if streamHttp {
numOfSubscriptions++
go streamHttpEvents(client, eventChan, errorChan)
}
if streamTcp {
numOfSubscriptions++
go streamTcpEvents(client, eventChan, errorChan)
}
errorCount := 0
loop:
for {
select {
case eventMessage := <-eventChan:
fmt.Println(eventMessage)
case err := <-errorChan:
errorCount++
fmt.Printf("Connection closed: %s", err.Error())
if errorCount >= numOfSubscriptions {
break loop
}
}
}
}
func streamHttpEvents(client routing_api.Client, eventChan chan string, errorChan chan error) {
eventSource, err := client.SubscribeToEvents()
if err != nil {
fmt.Println("streaming events failed:", err)
return
}
for {
e, err := eventSource.Next()
if err != nil {
errorChan <- err
break
}
event, _ := json.Marshal(e)
eventChan <- fmt.Sprintf("%v\n", string(event))
}
}
func streamTcpEvents(client routing_api.Client, eventChan chan string, errorChan chan error) {
eventSource, err := client.SubscribeToTcpEvents()
if err != nil {
fmt.Println("streaming events failed:", err)
return
}
for {
e, err := eventSource.Next()
if err != nil {
errorChan <- err
break
}
event, _ := json.Marshal(e)
eventChan <- fmt.Sprintf("%v\n", string(event))
}
}
func checkFlags(c *cli.Context) []string {
var issues []string
if c.String("api") == "" {
issues = append(issues, "Must provide an API endpoint for the routing-api component.")
}
if c.String("client-id") == "" {
issues = append(issues, "Must provide the id of an OAuth client.")
}
if c.String("client-secret") == "" {
issues = append(issues, "Must provide an OAuth secret.")
}
if c.String("oauth-url") == "" {
issues = append(issues, "Must provide an URL to the OAuth client.")
}
_, err := url.Parse(c.String("oauth-url"))
if err != nil {
issues = append(issues, "Invalid OAuth client URL")
}
return issues
}
func checkArguments(c *cli.Context, cmd string) []string {
var issues []string
switch cmd {
case "register", "unregister":
if len(c.Args()) > 1 {
issues = append(issues, "Unexpected arguments.")
} else if len(c.Args()) < 1 {
issues = append(issues, "Must provide routes JSON.")
}
case "list", "events":
if len(c.Args()) > 0 {
issues = append(issues, "Unexpected arguments.")
}
}
return issues
}
func printHelpForCommand(c *cli.Context, issues []string, cmd string) {
for _, issue := range issues {
fmt.Println(issue)
}
fmt.Println()
err := cli.ShowCommandHelp(c, cmd)
if err != nil {
fmt.Printf("Help Error: %s\n", err)
}
os.Exit(1)
}
func commandNotFound(c *cli.Context, cmd string) {
fmt.Println("Not a valid command:", cmd)
os.Exit(1)
}
func newRoutingApiClient(c *cli.Context) (routing_api.Client, error) {
rtr_trace := os.Getenv(RTR_TRACE)
var logger lager.Logger
if rtr_trace == "true" {
logger, _ = lagerflags.New("rtr")
} else {
logger = lager.NewLogger("rtr")
}
tokenURL := c.String("oauth-url")
u, err := url.Parse(c.String("oauth-url"))
if err != nil {
return nil, err
}
addr := strings.Split(u.Host, ":")
if len(addr) < 2 {
return nil, fmt.Errorf("Invalid oauth url: %s", tokenURL)
}
port, err := strconv.Atoi(addr[1])
if err != nil {
return nil, err
}
uaaConfig := uaaclient.Config{
SkipSSLValidation: c.Bool("skip-tls-verification"),
ClientName: c.String("client-id"),
ClientSecret: c.String("client-secret"),
CACerts: c.String("ca-certs"),
TokenEndpoint: addr[0],
Port: port,
}
clk := clock.NewClock()
uaaClient, err := uaaclient.NewTokenFetcher(false, uaaConfig, clk, 3, 500*time.Millisecond, 30, logger)
if err != nil {
return nil, err
}
token, err := uaaClient.FetchToken(context.Background(), true)
if err != nil {
return nil, err
}
routingApiClient := routing_api.NewClient(c.String("api"), c.Bool("skip-tls-verification"))
routingApiClient.SetToken(token.AccessToken)
return routingApiClient, nil
}
func checkError(message string, err error) {
if err != nil {
fmt.Println(message, err.Error())
os.Exit(3)
}
}