-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
cmd.go
314 lines (281 loc) · 10.1 KB
/
cmd.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
// Copyright 2020 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package run
import (
"errors"
"flag"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/healthz"
logf "sigs.k8s.io/controller-runtime/pkg/log"
zapf "sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/operator-framework/operator-sdk/internal/ansible/controller"
"github.com/operator-framework/operator-sdk/internal/ansible/flags"
"github.com/operator-framework/operator-sdk/internal/ansible/metrics"
"github.com/operator-framework/operator-sdk/internal/ansible/proxy"
"github.com/operator-framework/operator-sdk/internal/ansible/proxy/controllermap"
"github.com/operator-framework/operator-sdk/internal/ansible/runner"
"github.com/operator-framework/operator-sdk/internal/ansible/watches"
"github.com/operator-framework/operator-sdk/internal/clientbuilder"
"github.com/operator-framework/operator-sdk/internal/util/k8sutil"
sdkVersion "github.com/operator-framework/operator-sdk/internal/version"
)
var log = logf.Log.WithName("cmd")
func printVersion() {
log.Info("Version",
"Go Version", runtime.Version(),
"GOOS", runtime.GOOS,
"GOARCH", runtime.GOARCH,
"ansible-operator", sdkVersion.Version,
"commit", sdkVersion.GitCommit)
}
func NewCmd() *cobra.Command {
f := &flags.Flags{}
zapfs := flag.NewFlagSet("zap", flag.ExitOnError)
opts := &zapf.Options{}
opts.BindFlags(zapfs)
cmd := &cobra.Command{
Use: "run",
Short: "Run the operator",
Run: func(cmd *cobra.Command, _ []string) {
logf.SetLogger(zapf.New(zapf.UseFlagOptions(opts)))
run(cmd, f)
},
}
f.AddTo(cmd.Flags())
cmd.Flags().AddGoFlagSet(zapfs)
return cmd
}
func run(cmd *cobra.Command, f *flags.Flags) {
printVersion()
metrics.RegisterBuildInfo(crmetrics.Registry)
// Load config options from the config at f.ManagerConfigPath.
// These options will not override those set by flags.
var (
options manager.Options
err error
)
if f.ManagerConfigPath != "" {
cfgLoader := ctrl.ConfigFile().AtPath(f.ManagerConfigPath)
if options, err = options.AndFrom(cfgLoader); err != nil {
log.Error(err, "Unable to load the manager config file")
os.Exit(1)
}
}
exitIfUnsupported(options)
cfg, err := config.GetConfig()
if err != nil {
log.Error(err, "Failed to get config.")
os.Exit(1)
}
// TODO(2.0.0): remove
// Deprecated: OPERATOR_NAME environment variable is an artifact of the
// legacy operator-sdk project scaffolding. Flag `--leader-election-id`
// should be used instead.
if operatorName, found := os.LookupEnv("OPERATOR_NAME"); found {
log.Info("Environment variable OPERATOR_NAME has been deprecated, use --leader-election-id instead.")
if cmd.Flags().Changed("leader-election-id") {
log.Info("Ignoring OPERATOR_NAME environment variable since --leader-election-id is set")
} else if options.LeaderElectionID == "" {
// Only set leader election ID using OPERATOR_NAME if unset everywhere else,
// since this env var is deprecated.
options.LeaderElectionID = operatorName
}
}
//TODO(2.0.0): remove the following checks. they are required just because of the flags deprecation
if cmd.Flags().Changed("leader-elect") && cmd.Flags().Changed("enable-leader-election") {
log.Error(errors.New("only one of --leader-elect and --enable-leader-election may be set"), "invalid flags usage")
os.Exit(1)
}
if cmd.Flags().Changed("metrics-addr") && cmd.Flags().Changed("metrics-bind-address") {
log.Error(errors.New("only one of --metrics-addr and --metrics-bind-address may be set"), "invalid flags usage")
os.Exit(1)
}
// Set default manager options
// TODO: probably should expose the host & port as an environment variables
options = f.ToManagerOptions(options)
if options.ClientBuilder == nil {
options.ClientBuilder = clientbuilder.NewUnstructedCached()
}
namespace, found := os.LookupEnv(k8sutil.WatchNamespaceEnvVar)
log = log.WithValues("Namespace", namespace)
if found {
log.V(1).Info(fmt.Sprintf("Setting namespace with value in %s", k8sutil.WatchNamespaceEnvVar))
if namespace == metav1.NamespaceAll {
log.Info("Watching all namespaces.")
options.Namespace = metav1.NamespaceAll
} else {
if strings.Contains(namespace, ",") {
log.Info("Watching multiple namespaces.")
options.NewCache = cache.MultiNamespacedCacheBuilder(strings.Split(namespace, ","))
} else {
log.Info("Watching single namespace.")
options.Namespace = namespace
}
}
} else if options.Namespace == "" {
log.Info(fmt.Sprintf("Watch namespaces not configured by environment variable %s or file. "+
"Watching all namespaces.", k8sutil.WatchNamespaceEnvVar))
options.Namespace = metav1.NamespaceAll
}
err = setAnsibleEnvVars(f)
if err != nil {
log.Error(err, "Failed to set environment variable.")
os.Exit(1)
}
// Create a new manager to provide shared dependencies and start components
mgr, err := manager.New(cfg, options)
if err != nil {
log.Error(err, "Failed to create a new manager.")
os.Exit(1)
}
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
log.Error(err, "Unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
log.Error(err, "Unable to set up ready check")
os.Exit(1)
}
cMap := controllermap.NewControllerMap()
watches, err := watches.Load(f.WatchesFile, f.MaxConcurrentReconciles, f.AnsibleVerbosity)
if err != nil {
log.Error(err, "Failed to load watches.")
os.Exit(1)
}
for _, w := range watches {
runner, err := runner.New(w, f.AnsibleArgs)
if err != nil {
log.Error(err, "Failed to create runner")
os.Exit(1)
}
ctr := controller.Add(mgr, controller.Options{
GVK: w.GroupVersionKind,
Runner: runner,
ManageStatus: w.ManageStatus,
AnsibleDebugLogs: getAnsibleDebugLog(),
MaxConcurrentReconciles: w.MaxConcurrentReconciles,
ReconcilePeriod: w.ReconcilePeriod,
Selector: w.Selector,
})
if ctr == nil {
log.Error(fmt.Errorf("failed to add controller for GVK %v", w.GroupVersionKind.String()), "")
os.Exit(1)
}
cMap.Store(w.GroupVersionKind, &controllermap.Contents{Controller: *ctr,
WatchDependentResources: w.WatchDependentResources,
WatchClusterScopedResources: w.WatchClusterScopedResources,
OwnerWatchMap: controllermap.NewWatchMap(),
AnnotationWatchMap: controllermap.NewWatchMap(),
}, w.Blacklist)
}
// TODO(2.0.0): remove
err = mgr.AddHealthzCheck("ping", healthz.Ping)
if err != nil {
log.Error(err, "Failed to add Healthz check.")
}
done := make(chan error)
// start the proxy
err = proxy.Run(done, proxy.Options{
Address: "localhost",
Port: 8888,
KubeConfig: mgr.GetConfig(),
Cache: mgr.GetCache(),
RESTMapper: mgr.GetRESTMapper(),
ControllerMap: cMap,
OwnerInjection: f.InjectOwnerRef,
WatchedNamespaces: strings.Split(namespace, ","),
})
if err != nil {
log.Error(err, "Error starting proxy.")
os.Exit(1)
}
// start the operator
go func() {
done <- mgr.Start(signals.SetupSignalHandler())
}()
// wait for either to finish
err = <-done
if err != nil {
log.Error(err, "Proxy or operator exited with error.")
os.Exit(1)
}
log.Info("Exiting.")
}
// exitIfUnsupported prints an error containing unsupported field names and exits
// if any of those fields are not their default values.
func exitIfUnsupported(options manager.Options) {
var keys []string
// The below options are webhook-specific, which is not supported by ansible.
if options.CertDir != "" {
keys = append(keys, "certDir")
}
if options.Host != "" {
keys = append(keys, "host")
}
if options.Port != 0 {
keys = append(keys, "port")
}
if len(keys) > 0 {
log.Error(fmt.Errorf("%s set in manager options", strings.Join(keys, ", ")), "unsupported fields")
os.Exit(1)
}
}
// getAnsibleDebugLog return the value from the ANSIBLE_DEBUG_LOGS it order to
// print the full Ansible logs
func getAnsibleDebugLog() bool {
const envVar = "ANSIBLE_DEBUG_LOGS"
val := false
if envVal, ok := os.LookupEnv(envVar); ok {
if i, err := strconv.ParseBool(envVal); err != nil {
log.Info("Could not parse environment variable as an boolean; using default value",
"envVar", envVar, "default", val)
} else {
val = i
}
} else if !ok {
log.Info("Environment variable not set; using default value", "envVar", envVar,
envVar, val)
}
return val
}
// setAnsibleEnvVars will set environment variables based on CLI flags
func setAnsibleEnvVars(f *flags.Flags) error {
if len(f.AnsibleRolesPath) > 0 {
if err := os.Setenv(flags.AnsibleRolesPathEnvVar, f.AnsibleRolesPath); err != nil {
return fmt.Errorf("failed to set environment variable %s: %v", flags.AnsibleRolesPathEnvVar, err)
}
log.Info("Set the environment variable", "envVar", flags.AnsibleRolesPathEnvVar,
"value", f.AnsibleRolesPath)
}
if len(f.AnsibleCollectionsPath) > 0 {
if err := os.Setenv(flags.AnsibleCollectionsPathEnvVar, f.AnsibleCollectionsPath); err != nil {
return fmt.Errorf("failed to set environment variable %s: %v", flags.AnsibleCollectionsPathEnvVar, err)
}
log.Info("Set the environment variable", "envVar", flags.AnsibleCollectionsPathEnvVar,
"value", f.AnsibleCollectionsPath)
}
return nil
}