-
Notifications
You must be signed in to change notification settings - Fork 490
/
kiali.go
262 lines (221 loc) · 7.76 KB
/
kiali.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
// Kiali
//
// # Kiali Project, The Console for Istio Service Mesh
//
// NOTE! The Kiali API is not for public use and is not supported for any use outside of the Kiali UI itself.
// The API can and will change from version to version with no guarantee of backwards compatibility.
//
// To generate this API document:
// ```
//
// > alias swagger='docker run --rm -it --user $(id -u):$(id -g) -e GOCACHE=/tmp -e GOPATH=$(go env GOPATH):/go -v $HOME:$HOME -w $(pwd) quay.io/goswagger/swagger'
// > swagger generate spec -o ./swagger.json
// > swagger generate markdown --quiet --spec ./swagger.json --output ./kiali_internal_api.md
//
// ```
//
// Schemes: http, https
// BasePath: /api
// Version: _
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// swagger:meta
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"k8s.io/client-go/rest"
"github.com/kiali/kiali/business/authentication"
"github.com/kiali/kiali/config"
"github.com/kiali/kiali/kubernetes"
"github.com/kiali/kiali/log"
"github.com/kiali/kiali/prometheus/internalmetrics"
"github.com/kiali/kiali/server"
"github.com/kiali/kiali/status"
"github.com/kiali/kiali/util"
)
// Identifies the build. These are set via ldflags during the build (see Makefile).
var (
version = "unknown"
commitHash = "unknown"
goVersion = "unknown"
)
// Command line arguments
var (
argConfigFile = flag.String("config", "", "Path to the YAML configuration file. If not specified, environment variables will be used for configuration.")
)
func init() {
// log everything to stderr so that it can be easily gathered by logs, separate log files are problematic with containers
_ = flag.Set("logtostderr", "true")
}
func main() {
log.InitializeLogger()
util.Clock = util.RealClock{}
// process command line
flag.Parse()
validateFlags()
// log startup information
log.Infof("Kiali: Version: %v, Commit: %v, Go: %v", version, commitHash, goVersion)
log.Debugf("Kiali: Command line: [%v]", strings.Join(os.Args, " "))
// load config file if specified, otherwise, rely on environment variables to configure us
if *argConfigFile != "" {
c, err := config.LoadFromFile(*argConfigFile)
if err != nil {
log.Fatal(err)
}
config.Set(c)
} else {
log.Infof("No configuration file specified. Will rely on environment for configuration.")
config.Set(config.NewConfig())
}
updateConfigWithIstioInfo()
cfg := config.Get()
log.Tracef("Kiali Configuration:\n%s", cfg)
if err := validateConfig(); err != nil {
log.Fatal(err)
}
status.Put(status.CoreVersion, version)
status.Put(status.CoreCommitHash, commitHash)
status.Put(status.ContainerVersion, determineContainerVersion(version))
authentication.InitializeAuthenticationController(cfg.Auth.Strategy)
// prepare our internal metrics so Prometheus can scrape them
internalmetrics.RegisterInternalMetrics()
// Start listening to requests
server := server.NewServer()
server.Start()
// wait forever, or at least until we are told to exit
waitForTermination()
// Shutdown internal components
log.Info("Shutting down internal components")
server.Stop()
}
func waitForTermination() {
// Channel that is notified when we are done and should exit
// TODO: may want to make this a package variable - other things might want to tell us to exit
doneChan := make(chan bool)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
for range signalChan {
log.Info("Termination Signal Received")
doneChan <- true
}
}()
<-doneChan
}
func validateConfig() error {
cfg := config.Get()
if cfg.Server.Port < 0 {
return fmt.Errorf("server port is negative: %v", cfg.Server.Port)
}
if strings.Contains(cfg.Server.StaticContentRootDirectory, "..") {
return fmt.Errorf("server static content root directory must not contain '..': %v", cfg.Server.StaticContentRootDirectory)
}
if _, err := os.Stat(cfg.Server.StaticContentRootDirectory); os.IsNotExist(err) {
return fmt.Errorf("server static content root directory does not exist: %v", cfg.Server.StaticContentRootDirectory)
}
validPathRegEx := regexp.MustCompile(`^\/[a-zA-Z0-9\-\._~!\$&\'()\*\+\,;=:@%/]*$`)
webRoot := cfg.Server.WebRoot
if !validPathRegEx.MatchString(webRoot) {
return fmt.Errorf("web root must begin with a / and contain valid URL path characters: %v", webRoot)
}
if webRoot != "/" && strings.HasSuffix(webRoot, "/") {
return fmt.Errorf("web root must not contain a trailing /: %v", webRoot)
}
if strings.Contains(webRoot, "/../") {
return fmt.Errorf("for security purposes, web root must not contain '/../': %v", webRoot)
}
// log some messages to let the administrator know when credentials are configured certain ways
auth := cfg.Auth
log.Infof("Using authentication strategy [%v]", auth.Strategy)
if auth.Strategy == config.AuthStrategyAnonymous {
log.Warningf("Kiali auth strategy is configured for anonymous access - users will not be authenticated.")
} else if auth.Strategy != config.AuthStrategyOpenId &&
auth.Strategy != config.AuthStrategyOpenshift &&
auth.Strategy != config.AuthStrategyToken &&
auth.Strategy != config.AuthStrategyHeader {
return fmt.Errorf("Invalid authentication strategy [%v]", auth.Strategy)
}
// Check the ciphering key for sessions
signingKey := cfg.LoginToken.SigningKey
if err := config.ValidateSigningKey(signingKey, auth.Strategy); err != nil {
return err
}
// log a warning if the user is ignoring some validations
if len(cfg.KialiFeatureFlags.Validations.Ignore) > 0 {
log.Infof("Some validation errors will be ignored %v. If these errors do occur, they will still be logged. If you think the validation errors you see are incorrect, please report them to the Kiali team if you have not done so already and provide the details of your scenario. This will keep Kiali validations strong for the whole community.", cfg.KialiFeatureFlags.Validations.Ignore)
}
// log a info message if the user is disabling some features
if len(cfg.KialiFeatureFlags.DisabledFeatures) > 0 {
log.Infof("Some features are disabled: [%v]", strings.Join(cfg.KialiFeatureFlags.DisabledFeatures, ","))
for _, fn := range cfg.KialiFeatureFlags.DisabledFeatures {
if err := config.FeatureName(fn).IsValid(); err != nil {
return err
}
}
}
return nil
}
func validateFlags() {
if *argConfigFile != "" {
if _, err := os.Stat(*argConfigFile); err != nil {
if os.IsNotExist(err) {
log.Debugf("Configuration file [%v] does not exist.", *argConfigFile)
}
}
}
}
// determineContainerVersion will return the version of the image container.
// It does this by looking at an ENV defined in the Dockerfile when the image is built.
// If the ENV is not defined, the version is assumed the same as the given default value.
func determineContainerVersion(defaultVersion string) string {
v := os.Getenv("KIALI_CONTAINER_VERSION")
if v == "" {
return defaultVersion
}
return v
}
func updateConfigWithIstioInfo() {
conf := *config.Get()
if !conf.InCluster {
// If it's not an in-cluster kiali, we don't need to do anything
return
}
homeCluster := conf.KubernetesConfig.ClusterName
if homeCluster != "" {
// If the cluster name is already set, we don't need to do anything
return
}
err := func() error {
restConf, err := rest.InClusterConfig()
if err != nil {
return err
}
k8s, err := kubernetes.NewClientFromConfig(restConf)
if err != nil {
return err
}
// Try to auto-detect the cluster name
homeCluster, _, err = kubernetes.ClusterInfoFromIstiod(conf, k8s)
if err != nil {
return err
}
return nil
}()
if err != nil {
log.Warningf("Cannot resolve local cluster name. Err: %s. Falling back to [%s]", err, config.DefaultClusterID)
homeCluster = config.DefaultClusterID
}
conf.KubernetesConfig.ClusterName = homeCluster
config.Set(&conf)
}