This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot.go
151 lines (126 loc) · 3.77 KB
/
root.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
package cmd
import (
"bytes"
goflag "flag"
"fmt"
"io"
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
flagDryRun = "dry-run"
flagAllNamespaces = "all-namespaces"
flagVerbose = "verbose"
)
var clientConfig clientcmd.ClientConfig
var overrides clientcmd.ConfigOverrides
// Gently taken from github.com/ksonnet/kubecfg
func init() {
rootCmd.PersistentFlags().Bool(flagDryRun, false, "Dry run")
rootCmd.PersistentFlags().CountP(flagVerbose, "v", "Increase verbosity")
rootCmd.PersistentFlags().Bool(flagAllNamespaces, false, "All namespaces")
// The "usual" clientcmd/kubectl flags
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig
kflags := clientcmd.RecommendedConfigOverrideFlags("")
rootCmd.PersistentFlags().StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to a kube config. Only required if out-of-cluster")
rootCmd.MarkPersistentFlagFilename("kubeconfig")
clientcmd.BindOverrideFlags(&overrides, rootCmd.PersistentFlags(), kflags)
clientConfig = clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, &overrides, os.Stdin)
rootCmd.PersistentFlags().Set("logtostderr", "true")
}
var rootCmd = &cobra.Command{
Use: "kube-custodian",
Short: "Cleanup stuff",
SilenceErrors: true,
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
goflag.CommandLine.Parse([]string{})
flags := cmd.Flags()
// Need either --all-namespaces or --namespace=...
allNS, _ := flags.GetBool(flagAllNamespaces)
namespace, _ := flags.GetString("namespace")
if allNS == (len(namespace) > 0) {
log.Fatalf("Cowardly refusing to use a default namespace, provide --namespace=<NS> xor --all-namespaces")
}
out := cmd.OutOrStderr()
log.SetOutput(out)
logFmt := NewLogFormatter(out)
log.SetFormatter(logFmt)
verbosity, err := flags.GetCount(flagVerbose)
if err != nil {
return err
}
log.SetLevel(logLevel(verbosity))
return nil
},
}
// Execute is main() entry point
func Execute() error {
if err := rootCmd.Execute(); err != nil {
log.Errorf("rootCmd.Execute(): %v", err)
return err
}
return nil
}
// NewKubeClient creates a new kubernetes Clientset from already setup clientConfig
func NewKubeClient() *kubernetes.Clientset {
c, err := clientConfig.ClientConfig()
if err != nil {
log.Fatalf("NewKubeClient: %v", err)
}
clientset, err := kubernetes.NewForConfig(c)
if err != nil {
log.Fatalf("NewKubeClient: failed to create clienset: %v", err)
}
return clientset
}
type logFormatter struct {
escapes *terminal.EscapeCodes
colorise bool
}
func logLevel(verbosity int) log.Level {
switch verbosity {
case 0:
return log.InfoLevel
default:
return log.DebugLevel
}
}
// NewLogFormatter creates a new log.Formatter customised for writer
func NewLogFormatter(out io.Writer) log.Formatter {
var ret = logFormatter{}
if f, ok := out.(*os.File); ok {
ret.colorise = terminal.IsTerminal(int(f.Fd()))
ret.escapes = terminal.NewTerminal(f, "").Escape
}
return &ret
}
func (f *logFormatter) Format(e *log.Entry) ([]byte, error) {
buf := bytes.Buffer{}
if f.colorise {
buf.Write(f.levelEsc(e.Level))
fmt.Fprintf(&buf, "%-5s ", strings.ToUpper(e.Level.String()))
buf.Write(f.escapes.Reset)
}
buf.WriteString(strings.TrimSpace(e.Message))
buf.WriteString("\n")
return buf.Bytes(), nil
}
func (f *logFormatter) levelEsc(level log.Level) []byte {
switch level {
case log.DebugLevel:
return []byte{}
case log.WarnLevel:
return f.escapes.Yellow
case log.ErrorLevel, log.FatalLevel, log.PanicLevel:
return f.escapes.Red
default:
return f.escapes.Blue
}
}