This repository has been archived by the owner on Nov 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
385 lines (312 loc) · 8.56 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
package main
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"path"
"strings"
"sync"
"time"
"github.com/cskr/pubsub"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/gorilla/mux"
akashv1 "github.com/ovrclk/akash/pkg/apis/akash.network/v1"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"github.com/ovrclk/k8s-inventory-operator/util/runner"
"github.com/boz/go-lifecycle"
akashclientset "github.com/ovrclk/akash/pkg/client/clientset/versioned"
rookclientset "github.com/rook/rook/pkg/client/clientset/versioned"
)
const (
FlagKubeConfig = "kubeconfig"
FlagKubeInCluster = "kube-incluster"
FlagApiTimeout = "api-timeout"
FlagQueryTimeout = "query-timeout"
)
type ContextKey string
const (
CtxKeyKubeConfig = ContextKey(FlagKubeConfig)
CtxKeyKubeClientSet = ContextKey("kube-clientset")
CtxKeyRookClientSet = ContextKey("rook-clientset")
CtxKeyAkashClientSet = ContextKey("akash-clientset")
CtxKeyPubSub = ContextKey("pubsub")
CtxKeyLifecycle = ContextKey("lifecycle")
CtxKeyErrGroup = ContextKey("errgroup")
CtxKeyStorage = ContextKey("storage")
)
func LogFromCtx(ctx context.Context) logr.Logger {
return logr.FromContext(ctx)
}
func KubeConfigFromCtx(ctx context.Context) *rest.Config {
val := ctx.Value(CtxKeyKubeConfig)
if val == nil {
panic("context does not have kubeconfig set")
}
return val.(*rest.Config)
}
func KubeClientFromCtx(ctx context.Context) *kubernetes.Clientset {
val := ctx.Value(CtxKeyKubeClientSet)
if val == nil {
panic("context does not have kube client set")
}
return val.(*kubernetes.Clientset)
}
func RookClientFromCtx(ctx context.Context) *rookclientset.Clientset {
val := ctx.Value(CtxKeyRookClientSet)
if val == nil {
panic("context does not have rook client set")
}
return val.(*rookclientset.Clientset)
}
func AkashClientFromCtx(ctx context.Context) *akashclientset.Clientset {
val := ctx.Value(CtxKeyAkashClientSet)
if val == nil {
panic("context does not have akash client set")
}
return val.(*akashclientset.Clientset)
}
func PubSubFromCtx(ctx context.Context) *pubsub.PubSub {
val := ctx.Value(CtxKeyPubSub)
if val == nil {
panic("context does not have pubsub set")
}
return val.(*pubsub.PubSub)
}
func LifecycleFromCtx(ctx context.Context) lifecycle.Lifecycle {
val := ctx.Value(CtxKeyLifecycle)
if val == nil {
panic("context does not have lifecycle set")
}
return val.(lifecycle.Lifecycle)
}
func ErrGroupFromCtx(ctx context.Context) *errgroup.Group {
val := ctx.Value(CtxKeyErrGroup)
if val == nil {
panic("context does not have errgroup set")
}
return val.(*errgroup.Group)
}
func StorageFromCtx(ctx context.Context) []Storage {
val := ctx.Value(CtxKeyStorage)
if val == nil {
panic("context does not have storage set")
}
return val.([]Storage)
}
func ContextSet(c *cli.Context, key, val interface{}) {
c.Context = context.WithValue(c.Context, key, val)
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
zconf := zap.NewDevelopmentConfig()
zconf.DisableCaller = true
zconf.EncoderConfig.EncodeTime = func(time.Time, zapcore.PrimitiveArrayEncoder) {}
zapLog, _ := zconf.Build()
ctx = logr.NewContext(ctx, zapr.NewLogger(zapLog))
app := cli.NewApp()
app.ErrWriter = os.Stdout
app.EnableBashCompletion = true
app.ExitErrHandler = func(c *cli.Context, err error) {
if err != nil && !errors.Is(err, context.Canceled) {
fmt.Println(err.Error())
os.Exit(1)
}
}
app.Flags = []cli.Flag{
&cli.PathFlag{
Name: FlagKubeConfig,
Usage: "Load kube configuration from `FILE`",
EnvVars: []string{strings.ToUpper(FlagKubeConfig)},
Value: path.Join(homedir.HomeDir(), ".kube", "config"),
},
&cli.BoolFlag{
Name: FlagKubeInCluster,
},
&cli.DurationFlag{
Name: FlagApiTimeout,
EnvVars: []string{strings.ToUpper(FlagApiTimeout)},
Required: false,
Hidden: false,
Value: 3 * time.Second,
},
&cli.DurationFlag{
Name: FlagQueryTimeout,
EnvVars: []string{strings.ToUpper(FlagQueryTimeout)},
Required: false,
Hidden: false,
Value: 2 * time.Second,
},
}
app.Before = func(c *cli.Context) error {
err := loadKubeConfig(c)
if err != nil {
return err
}
kubecfg := KubeConfigFromCtx(c.Context)
clientset, err := kubernetes.NewForConfig(kubecfg)
if err != nil {
return err
}
rc, err := rookclientset.NewForConfig(kubecfg)
if err != nil {
return err
}
ac, err := akashclientset.NewForConfig(kubecfg)
group, ctx := errgroup.WithContext(c.Context)
c.Context = ctx
ContextSet(c, CtxKeyKubeClientSet, clientset)
ContextSet(c, CtxKeyRookClientSet, rc)
ContextSet(c, CtxKeyAkashClientSet, ac)
ContextSet(c, CtxKeyPubSub, pubsub.New(1000))
ContextSet(c, CtxKeyErrGroup, group)
return nil
}
app.Action = func(c *cli.Context) error {
bus := PubSubFromCtx(c.Context)
kc := KubeClientFromCtx(c.Context)
group := ErrGroupFromCtx(c.Context)
var storage []Storage
st, err := NewCeph(c.Context)
if err != nil {
return err
}
storage = append(storage, st)
if st, err = NewRancher(c.Context); err != nil {
return err
}
storage = append(storage, st)
ContextSet(c, CtxKeyStorage, storage)
srv := &http.Server{
Addr: ":8080",
Handler: newRouter(LogFromCtx(c.Context).WithName("router"), c.Duration(FlagApiTimeout), c.Duration(FlagQueryTimeout)),
BaseContext: func(_ net.Listener) context.Context {
return c.Context
},
}
group.Go(func() error {
return srv.ListenAndServe()
})
group.Go(func() error {
select {
case <-ctx.Done():
}
return srv.Shutdown(ctx)
})
WatchKubeObjects(c.Context,
bus,
kc.CoreV1().Namespaces(),
"ns")
WatchKubeObjects(c.Context,
bus,
kc.StorageV1().StorageClasses(),
"sc")
WatchKubeObjects(c.Context,
bus,
kc.CoreV1().PersistentVolumes(),
"pv")
WatchKubeObjects(c.Context,
bus,
kc.CoreV1().Nodes(),
"nodes")
return group.Wait()
}
_ = app.RunContext(ctx, os.Args)
}
func newRouter(log logr.Logger, apiTimeout, queryTimeout time.Duration) *mux.Router {
router := mux.NewRouter()
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rCtx, cancel := context.WithTimeout(r.Context(), apiTimeout)
defer cancel()
h.ServeHTTP(w, r.WithContext(rCtx))
})
})
router.HandleFunc("/inventory", func(w http.ResponseWriter, req *http.Request) {
storage := StorageFromCtx(req.Context())
inv := akashv1.Inventory{
TypeMeta: metav1.TypeMeta{
Kind: "Inventory",
APIVersion: "akash.network/v1",
},
ObjectMeta: metav1.ObjectMeta{
CreationTimestamp: metav1.NewTime(time.Now().UTC()),
},
Spec: akashv1.InventorySpec{},
Status: akashv1.InventoryStatus{
State: akashv1.InventoryStatePulled,
},
}
ctx, cancel := context.WithTimeout(req.Context(), queryTimeout)
datach := make(chan runner.Result, 1)
var wg sync.WaitGroup
wg.Add(len(storage))
for idx := range storage {
go func(idx int) {
defer wg.Done()
datach <- runner.NewResult(storage[idx].Query(ctx))
}(idx)
}
go func() {
defer cancel()
wg.Wait()
}()
done:
for {
select {
case <-ctx.Done():
break done
case res := <-datach:
if res.Error() != nil {
inv.Status.Messages = append(inv.Status.Messages, res.Error().Error())
}
if inventory, valid := res.Value().([]akashv1.InventoryClusterStorage); valid {
inv.Spec.Storage = append(inv.Spec.Storage, inventory...)
}
}
}
data, err := json.Marshal(&inv)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
data = []byte(err.Error())
} else {
w.Header().Set("Content-Type", "application/json")
}
_, _ = w.Write(data)
})
return router
}
func loadKubeConfig(c *cli.Context) error {
log := LogFromCtx(c.Context)
var config *rest.Config
configPath := c.Path(FlagKubeConfig)
_, err := os.Stat(configPath)
if err == nil && !c.Bool(FlagKubeInCluster) {
config, err = clientcmd.BuildConfigFromFlags("", configPath)
} else if err != nil && c.IsSet(FlagKubeConfig) {
return err
} else {
log.Info("trying use incluster kube config")
config, err = rest.InClusterConfig()
}
if err != nil {
return err
}
log.Info("kube config loaded successfully")
ContextSet(c, CtxKeyKubeConfig, config)
return nil
}