-
Notifications
You must be signed in to change notification settings - Fork 111
/
start.go
263 lines (223 loc) · 7.95 KB
/
start.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
/*
Copyright 2023.
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 main
import (
"context"
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/spf13/cobra"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/connrotation"
"sigs.k8s.io/controller-runtime/pkg/log"
configv1 "github.com/openshift/api/config/v1"
mcfgv1 "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1"
sriovnetworkv1 "github.com/k8snetworkplumbingwg/sriov-network-operator/api/v1"
snclientset "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/client/clientset/versioned"
"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/consts"
"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/daemon"
"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/helper"
snolog "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/log"
"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/platforms"
"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/vars"
)
var (
startCmd = &cobra.Command{
Use: "start",
Short: "Starts SR-IOV Network Config Daemon",
Long: "",
RunE: runStartCmd,
}
startOpts struct {
kubeconfig string
nodeName string
systemd bool
}
)
func init() {
rootCmd.AddCommand(startCmd)
startCmd.PersistentFlags().StringVar(&startOpts.kubeconfig, "kubeconfig", "", "Kubeconfig file to access a remote cluster (testing only)")
startCmd.PersistentFlags().StringVar(&startOpts.nodeName, "node-name", "", "kubernetes node name daemon is managing")
startCmd.PersistentFlags().BoolVar(&startOpts.systemd, "use-systemd-service", false, "use config daemon in systemd mode")
}
func runStartCmd(cmd *cobra.Command, args []string) error {
// init logger
snolog.InitLog()
setupLog := log.Log.WithName("sriov-network-config-daemon")
// Mark that we are running inside a container
vars.UsingSystemdMode = false
if startOpts.systemd {
vars.UsingSystemdMode = true
}
if startOpts.nodeName == "" {
name, ok := os.LookupEnv("NODE_NAME")
if !ok || name == "" {
return fmt.Errorf("node-name is required")
}
startOpts.nodeName = name
}
vars.NodeName = startOpts.nodeName
// This channel is used to ensure all spawned goroutines exit when we exit.
stopCh := make(chan struct{})
defer close(stopCh)
// This channel is used to signal Run() something failed and to jump ship.
// It's purely a chan<- in the Daemon struct for goroutines to write to, and
// a <-chan in Run() for the main thread to listen on.
exitCh := make(chan error)
defer close(exitCh)
// This channel is to make sure main thread will wait until the writer finish
// to report lastSyncError in SriovNetworkNodeState object.
syncCh := make(chan struct{})
defer close(syncCh)
refreshCh := make(chan daemon.Message)
defer close(refreshCh)
var config *rest.Config
var err error
// On openshift we use the kubeconfig from kubelet on the node where the daemon is running
// this allow us to improve security as every daemon has access only to its own node
if vars.ClusterType == consts.ClusterTypeOpenshift {
kubeconfig, err := clientcmd.LoadFromFile("/host/etc/kubernetes/kubeconfig")
if err != nil {
setupLog.Error(err, "failed to load kubelet kubeconfig")
}
clusterName := kubeconfig.Contexts[kubeconfig.CurrentContext].Cluster
apiURL := kubeconfig.Clusters[clusterName].Server
urlPath, err := url.Parse(apiURL)
if err != nil {
setupLog.Error(err, "failed to parse api url from kubelet kubeconfig")
}
// The kubernetes in-cluster functions don't let you override the apiserver
// directly; gotta "pass" it via environment vars.
setupLog.V(0).Info("overriding kubernetes api", "new-url", apiURL)
err = os.Setenv("KUBERNETES_SERVICE_HOST", urlPath.Hostname())
if err != nil {
setupLog.Error(err, "failed to set KUBERNETES_SERVICE_HOST environment variable")
}
err = os.Setenv("KUBERNETES_SERVICE_PORT", urlPath.Port())
if err != nil {
setupLog.Error(err, "failed to set KUBERNETES_SERVICE_PORT environment variable")
}
}
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig != "" {
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
} else {
// creates the in-cluster config
config, err = rest.InClusterConfig()
}
if err != nil {
return err
}
vars.Config = config
vars.Scheme = scheme.Scheme
closeAllConns, err := updateDialer(config)
if err != nil {
return err
}
err = sriovnetworkv1.AddToScheme(scheme.Scheme)
if err != nil {
setupLog.Error(err, "failed to load sriov network CRDs to scheme")
return err
}
err = mcfgv1.AddToScheme(scheme.Scheme)
if err != nil {
setupLog.Error(err, "failed to load machine config CRDs to scheme")
return err
}
err = configv1.Install(scheme.Scheme)
if err != nil {
setupLog.Error(err, "failed to load openshift config CRDs to scheme")
return err
}
snclient := snclientset.NewForConfigOrDie(config)
kubeclient := kubernetes.NewForConfigOrDie(config)
hostHelpers, err := helper.NewDefaultHostHelpers()
if err != nil {
setupLog.Error(err, "failed to create hostHelpers")
return err
}
platformHelper, err := platforms.NewDefaultPlatformHelper()
if err != nil {
setupLog.Error(err, "failed to create platformHelper")
return err
}
config.Timeout = 5 * time.Second
writerclient := snclientset.NewForConfigOrDie(config)
eventRecorder := daemon.NewEventRecorder(writerclient, kubeclient)
defer eventRecorder.Shutdown()
setupLog.V(0).Info("starting node writer")
nodeWriter := daemon.NewNodeStateStatusWriter(writerclient,
closeAllConns,
eventRecorder,
hostHelpers,
platformHelper)
nodeInfo, err := kubeclient.CoreV1().Nodes().Get(context.Background(), startOpts.nodeName, v1.GetOptions{})
if err == nil {
for key, pType := range vars.PlatformsMap {
if strings.Contains(strings.ToLower(nodeInfo.Spec.ProviderID), strings.ToLower(key)) {
vars.PlatformType = pType
}
}
} else {
setupLog.Error(err, "failed to fetch node state, exiting", "node-name", startOpts.nodeName)
return err
}
setupLog.Info("Running on", "platform", vars.PlatformType.String())
var namespace = os.Getenv("NAMESPACE")
if err := sriovnetworkv1.InitNicIDMapFromConfigMap(kubeclient, namespace); err != nil {
setupLog.Error(err, "failed to run init NicIdMap")
return err
}
eventRecorder.SendEvent("ConfigDaemonStart", "Config Daemon starting")
// block the deamon process until nodeWriter finish first its run
err = nodeWriter.RunOnce()
if err != nil {
setupLog.Error(err, "failed to run writer")
return err
}
go nodeWriter.Run(stopCh, refreshCh, syncCh)
setupLog.V(0).Info("Starting SriovNetworkConfigDaemon")
err = daemon.New(
snclient,
kubeclient,
hostHelpers,
platformHelper,
exitCh,
stopCh,
syncCh,
refreshCh,
eventRecorder,
).Run(stopCh, exitCh)
if err != nil {
setupLog.Error(err, "failed to run daemon")
}
setupLog.V(0).Info("Shutting down SriovNetworkConfigDaemon")
return err
}
// updateDialer instruments a restconfig with a dial. the returned function allows forcefully closing all active connections.
func updateDialer(clientConfig *rest.Config) (func(), error) {
if clientConfig.Transport != nil || clientConfig.Dial != nil {
return nil, fmt.Errorf("there is already a transport or dialer configured")
}
f := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
d := connrotation.NewDialer(f.DialContext)
clientConfig.Dial = d.DialContext
return d.CloseAll, nil
}