-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgabi-cli.go
More file actions
213 lines (185 loc) · 5.55 KB
/
Copy pathgabi-cli.go
File metadata and controls
213 lines (185 loc) · 5.55 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"github.com/app-sre/gabi/pkg/models"
routev1 "github.com/openshift/api/route/v1"
routeclientv1 "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
"github.com/c-bata/go-prompt"
"github.com/jedib0t/go-pretty/v6/table"
)
func main() {
var kubeconfigPath *string
if home := homedir.HomeDir(); home != "" {
kubeconfigPath = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfigPath = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
showHelp := flag.Bool("h", false, "Shows help")
quiet := flag.Bool("q", false, "Suppress logging messages")
namespace := flag.String("n", "", "Namespace (defaults to current context)")
flag.Parse()
if *showHelp {
flag.PrintDefaults()
os.Exit(1)
}
if *quiet {
log.SetOutput(ioutil.Discard)
}
kubeconfig, config := setupK8s(*kubeconfigPath)
setDefaultNamespace(kubeconfig, namespace)
bearerToken := config.BearerToken
if bearerToken == "" {
log.Fatalf("no Bearer Token please use `oc login`")
}
log.Printf("Looking up Gabi from namespace %s, cluster %s", *namespace, config.Host)
gabiRoute, err := getGabiRoute(config, *namespace)
if err != nil {
if apierrors.IsUnauthorized(err) {
log.Fatalf("%s, please login with oc login", err)
} else {
log.Fatalf("couldn't find Gabi instance: %s", err)
}
}
gabiUrl := gabiUrlFromRoute(gabiRoute)
log.Printf("Using Gabi %s", gabiUrl)
var query string
if len(flag.Args()) > 0 {
// if there's a query on commandline, just run it
query = strings.Join(flag.Args(), " ")
runQuery(gabiUrl, bearerToken, "", &query)
return
}
p := prompt.New(func(input string) {
runQuery(gabiUrl, bearerToken, input, &query)
}, completer)
p.Run()
}
func runQuery(gabiUrl, bearerToken, input string, query *string) {
*query = fmt.Sprintf("%s%s", *query, input)
if !strings.HasSuffix(*query, ";") {
*query = fmt.Sprintf("%s\n", *query)
return
}
*query = strings.TrimSpace(*query)
result, err := queryGabi(gabiUrl, *query, bearerToken)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
} else if result.Error != "" {
fmt.Fprintf(os.Stderr, "Error: %s\n", result.Error)
} else {
formatResult(result, os.Stdout)
}
*query = ""
}
func completer(in prompt.Document) []prompt.Suggest {
return []prompt.Suggest{}
}
func setupK8s(kubeconfigPath string) (clientcmd.ClientConfig, *restclient.Config) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.ExplicitPath = kubeconfigPath
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
// use the current context in kubeconfig
clientconfig, err := kubeconfig.ClientConfig()
if err != nil {
log.Fatal(err.Error())
}
return kubeconfig, clientconfig
}
func setDefaultNamespace(kubeconfig clientcmd.ClientConfig, namespace *string) {
if *namespace == "" {
var err error
*namespace, _, err = kubeconfig.Namespace()
if err != nil {
log.Fatal(err.Error())
}
}
}
func getGabiRoute(config *restclient.Config, namespace string) (gabi routev1.Route, err error) {
clientset, err := routeclientv1.NewForConfig(config)
if err != nil {
return
}
routes, err := clientset.Routes(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return
}
for _, route := range routes.Items {
if strings.HasPrefix(route.Name, "gabi-") {
gabi = route
return
}
}
err = fmt.Errorf("no gabi route found in namespace %s", namespace)
return
}
func gabiUrlFromRoute(route routev1.Route) string {
var proto = "https"
if route.Spec.TLS == nil {
proto = "https"
}
return fmt.Sprintf("%s://%s%s", proto, route.Spec.Host, route.Spec.Path)
}
func queryGabi(url, query, token string) (models.QueryResponse, error) {
reqModel := models.QueryRequest{Query: query}
reqData, err := json.Marshal(reqModel)
if err != nil {
return models.QueryResponse{}, fmt.Errorf("marshal of query failed: %w", err)
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/query", url), bytes.NewReader(reqData))
if err != nil {
return models.QueryResponse{}, fmt.Errorf("request build failed: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return models.QueryResponse{}, fmt.Errorf("gabi request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusBadRequest {
return models.QueryResponse{}, fmt.Errorf("http status: %s", resp.Status)
}
dec := json.NewDecoder(resp.Body)
result := models.QueryResponse{}
if e := dec.Decode(&result); e != nil {
err = fmt.Errorf("malformed result %w", e)
}
return result, err
}
func formatResult(r models.QueryResponse, out io.Writer) {
t := table.NewWriter()
t.SetOutputMirror(out)
if len(r.Result) > 0 {
t.AppendHeader(convertToRow(r.Result[0]))
}
if len(r.Result) > 0 {
for _, row := range r.Result[1:] {
t.AppendRow(convertToRow(row))
}
}
t.Style().Options.DrawBorder = false
t.Render()
}
func convertToRow(raw []string) (r table.Row) {
r = make(table.Row, len(raw))
for i, cell := range raw {
r[i] = interface{}(cell)
}
return
}