-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
188 lines (163 loc) · 5.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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"strings"
"github.com/alecthomas/kong"
"github.com/ninech/nctl/api"
"github.com/ninech/nctl/api/util"
"github.com/ninech/nctl/apply"
"github.com/ninech/nctl/auth"
"github.com/ninech/nctl/create"
"github.com/ninech/nctl/delete"
"github.com/ninech/nctl/get"
"github.com/ninech/nctl/internal/format"
"github.com/ninech/nctl/logs"
"github.com/ninech/nctl/predictor"
"github.com/ninech/nctl/update"
"github.com/posener/complete"
"github.com/willabides/kongplete"
)
type flags struct {
Project string `predictor:"resource_name" help:"Limit commands to a specific project." short:"p"`
APICluster string `help:"Context name of the API cluster." default:"nineapis.ch" env:"NCTL_API_CLUSTER"`
LogAPIAddress string `help:"Address of the deplo.io logging API server." default:"https://logs.deplo.io" env:"NCTL_LOG_ADDR"`
LogAPIInsecure bool `help:"Don't verify TLS connection to the logging API server." hidden:"" default:"false" env:"NCTL_LOG_INSECURE"`
Version kong.VersionFlag `name:"version" help:"Print version information and quit."`
}
type rootCommand struct {
flags
Get get.Cmd `cmd:"" help:"Get resource."`
Auth auth.Cmd `cmd:"" help:"Authenticate with resource."`
Completions kongplete.InstallCompletions `cmd:"" help:"Print shell completions."`
Create create.Cmd `cmd:"" help:"Create resource."`
Apply apply.Cmd `cmd:"" help:"Apply resource."`
Delete delete.Cmd `cmd:"" help:"Delete resource."`
Logs logs.Cmd `cmd:"" help:"Get logs of resource."`
Update update.Cmd `cmd:"" help:"Update resource."`
}
var version = "dev"
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
setupSignalHandler(ctx, cancel)
kongVars, err := kongVariables()
if err != nil {
log.Fatal(err)
}
nctl := &rootCommand{}
parser := kong.Must(
nctl,
kong.Name(util.NctlName),
kong.Description("Interact with Nine API resources. See https://docs.nineapis.ch for the full API docs."),
kong.UsageOnError(),
kong.PostBuild(format.InterpolateFlagPlaceholders(kongVars)),
kongVars,
kong.BindTo(ctx, (*context.Context)(nil)),
)
resourceNamePredictor := predictor.NewResourceName(func() (*api.Client, error) {
// for the resourcePredictor to use the correct APICluster, we need to
// call parse already. Note that this won't parse the flag for
// completion but it will work for the default and env.
_, _ = parser.Parse(os.Args[1:])
c, err := api.New(ctx, nctl.APICluster, nctl.Project)
if err != nil {
return nil, err
}
return c, nil
})
// completion handling
kongplete.Complete(parser,
kongplete.WithPredictor("file", complete.PredictFiles("*")),
kongplete.WithPredictor("resource_name", resourceNamePredictor),
)
kongCtx, err := parser.Parse(os.Args[1:])
if err != nil {
var parseErr *kong.ParseError
if errors.As(err, &parseErr) {
// do not error on missing command/argument.
// Print Usage + friendly message instead.
if parseErr.Context.Error == nil {
node := parseErr.Context.Selected()
if node == nil {
node = parseErr.Context.Model.Node
}
if format.MissingChildren(node) {
err = format.ExitIfErrorf(err, parseErr.Context.Command())
}
}
}
parser.FatalIfErrorf(err)
}
// handle the login/oidc cmds separately as we should not try to get the
// API client if we're not logged in.
command, err := os.Executable()
if err != nil {
kongCtx.Fatalf("can not identify executable path of %s: %v", util.NctlName, err)
}
if strings.HasPrefix(kongCtx.Command(), format.LoginCommand) {
tk := &api.DefaultTokenGetter{}
kongCtx.FatalIfErrorf(nctl.Auth.Login.Run(ctx, command, tk))
return
}
if strings.HasPrefix(kongCtx.Command(), format.LogoutCommand) {
tk := &api.DefaultTokenGetter{}
kongCtx.FatalIfErrorf(nctl.Auth.Logout.Run(ctx, command, tk))
return
}
if strings.HasPrefix(kongCtx.Command(), auth.OIDCCmdName) {
kongCtx.FatalIfErrorf(nctl.Auth.OIDC.Run(ctx, os.Stdout))
return
}
client, err := api.New(ctx, nctl.APICluster, nctl.Project, api.LogClient(nctl.LogAPIAddress, nctl.LogAPIInsecure))
if err != nil {
fmt.Println(err)
fmt.Printf("\nUnable to get API client, are you logged in?\n\nUse `%s` to login.\n", format.Command().Login())
os.Exit(1)
}
kongCtx.FatalIfErrorf(kongCtx.Run(ctx, client))
}
func setupSignalHandler(ctx context.Context, cancel context.CancelFunc) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
defer func() {
signal.Stop(c)
}()
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
}
// kongVariables collects all variables which should be passed to kong. It
// checks for variables which would overwrite already existing ones.
func kongVariables() (kong.Vars, error) {
result := make(kong.Vars)
result["version"] = version
appCreateKongVars, err := create.ApplicationKongVars()
if err != nil {
return nil, fmt.Errorf("error on application create kong vars: %w", err)
}
if err := merge(result, appCreateKongVars, create.MySQLKongVars(), create.PostgresKongVars()); err != nil {
return nil, fmt.Errorf("error when merging kong variables: %w", err)
}
return result, nil
}
func merge(existing kong.Vars, withs ...kong.Vars) error {
for _, with := range withs {
for k, v := range with {
_, exists := existing[k]
if exists {
return fmt.Errorf("variable %q is already in use", k)
}
existing[k] = v
}
}
return nil
}