blob: 2c6b31ea24700ffe45ba3daa856a9e1660dee007 [file] [log] [blame]
Scott Bakere7144bc2019-10-01 14:16:47 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package main
18
19import (
20 "errors"
21 "flag"
22 "fmt"
23 "google.golang.org/grpc/connectivity"
24 "google.golang.org/grpc/keepalive"
25 "k8s.io/api/core/v1"
26 "math"
27 "os"
28 "path"
29 "regexp"
30 "strconv"
31 "time"
32
33 "github.com/golang/protobuf/ptypes"
34 "github.com/golang/protobuf/ptypes/empty"
35 "github.com/opencord/voltha-go/common/log"
36 "github.com/opencord/voltha-go/common/version"
37 "github.com/opencord/voltha-go/kafka"
38 pb "github.com/opencord/voltha-protos/go/afrouter"
39 cmn "github.com/opencord/voltha-protos/go/common"
40 ic "github.com/opencord/voltha-protos/go/inter_container"
41 vpb "github.com/opencord/voltha-protos/go/voltha"
42 "golang.org/x/net/context"
43 "google.golang.org/grpc"
44 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
45 "k8s.io/client-go/kubernetes"
46 "k8s.io/client-go/rest"
47 "k8s.io/client-go/tools/clientcmd"
48)
49
50type volthaPod struct {
51 name string
52 ipAddr string
53 node string
54 devIds map[string]struct{}
55 backend string
56 connection string
57}
58
59type Configuration struct {
60 DisplayVersionOnly *bool
61}
62
63var (
64 // if k8s variables are undefined, will attempt to use in-cluster config
65 k8sApiServer = getStrEnv("K8S_API_SERVER", "")
66 k8sKubeConfigPath = getStrEnv("K8S_KUBE_CONFIG_PATH", "")
67
68 podNamespace = getStrEnv("POD_NAMESPACE", "voltha")
69 podLabelSelector = getStrEnv("POD_LABEL_SELECTOR", "app=rw-core")
70 podAffinityGroupLabel = getStrEnv("POD_AFFINITY_GROUP_LABEL", "affinity-group")
71
72 podGrpcPort = uint64(getIntEnv("POD_GRPC_PORT", 0, math.MaxUint16, 50057))
73
74 afrouterApiAddress = getStrEnv("AFROUTER_API_ADDRESS", "localhost:55554")
75
76 afrouterRouterName = getStrEnv("AFROUTER_ROUTER_NAME", "vcore")
77 afrouterRouteName = getStrEnv("AFROUTER_ROUTE_NAME", "dev_manager")
78 afrouterRWClusterName = getStrEnv("AFROUTER_RW_CLUSTER_NAME", "vcore")
79
80 kafkaTopic = getStrEnv("KAFKA_TOPIC", "AffinityRouter")
81 kafkaClientType = getStrEnv("KAFKA_CLIENT_TYPE", "sarama")
82 kafkaHost = getStrEnv("KAFKA_HOST", "kafka")
83 kafkaPort = getIntEnv("KAFKA_PORT", 0, math.MaxUint16, 9092)
84 kafkaInstanceID = getStrEnv("KAFKA_INSTANCE_ID", "arouterd")
85)
86
87func getIntEnv(key string, min, max, defaultValue int) int {
88 if val, have := os.LookupEnv(key); have {
89 num, err := strconv.Atoi(val)
90 if err != nil || !(min <= num && num <= max) {
91 panic(fmt.Errorf("%s must be a number in the range [%d, %d]; default: %d", key, min, max, defaultValue))
92 }
93 return num
94 }
95 return defaultValue
96}
97
98func getStrEnv(key, defaultValue string) string {
99 if val, have := os.LookupEnv(key); have {
100 return val
101 }
102 return defaultValue
103}
104
105func newKafkaClient(clientType string, host string, port int, instanceID string) (kafka.Client, error) {
106 log.Infow("kafka-client-type", log.Fields{"client": clientType})
107 switch clientType {
108 case "sarama":
109 return kafka.NewSaramaClient(
110 kafka.Host(host),
111 kafka.Port(port),
112 kafka.ConsumerType(kafka.GroupCustomer),
113 kafka.ProducerReturnOnErrors(true),
114 kafka.ProducerReturnOnSuccess(true),
115 kafka.ProducerMaxRetries(6),
116 kafka.NumPartitions(3),
117 kafka.ConsumerGroupName(instanceID),
118 kafka.ConsumerGroupPrefix(instanceID),
119 kafka.AutoCreateTopic(false),
120 kafka.ProducerFlushFrequency(5),
121 kafka.ProducerRetryBackoff(time.Millisecond*30)), nil
122 }
123 return nil, errors.New("unsupported-client-type")
124}
125
126func k8sClientSet() *kubernetes.Clientset {
127 var config *rest.Config
128 if k8sApiServer != "" || k8sKubeConfigPath != "" {
129 // use combination of URL & local kube-config file
130 c, err := clientcmd.BuildConfigFromFlags(k8sApiServer, k8sKubeConfigPath)
131 if err != nil {
132 panic(err)
133 }
134 config = c
135 } else {
136 // use in-cluster config
137 c, err := rest.InClusterConfig()
138 if err != nil {
139 log.Errorf("Unable to load in-cluster config. Try setting K8S_API_SERVER and K8S_KUBE_CONFIG_PATH?")
140 panic(err)
141 }
142 config = c
143 }
144 // creates the clientset
145 clientset, err := kubernetes.NewForConfig(config)
146 if err != nil {
147 panic(err)
148 }
149
150 return clientset
151}
152
153func connect(ctx context.Context, addr string) (*grpc.ClientConn, error) {
154 log.Debugf("Trying to connect to %s", addr)
155 conn, err := grpc.DialContext(ctx, addr,
156 grpc.WithInsecure(),
157 grpc.WithBlock(),
158 grpc.WithBackoffMaxDelay(time.Second*5),
159 grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: time.Second * 10, Timeout: time.Second * 5}))
160 if err == nil {
161 log.Debugf("Connection succeeded")
162 }
163 return conn, err
164}
165
166func getVolthaPods(cs *kubernetes.Clientset) ([]*volthaPod, error) {
167 pods, err := cs.CoreV1().Pods(podNamespace).List(metav1.ListOptions{LabelSelector: podLabelSelector})
168 if err != nil {
169 return nil, err
170 }
171
172 var rwPods []*volthaPod
173items:
174 for _, v := range pods.Items {
175 // only pods that are actually running should be considered
176 if v.Status.Phase == v1.PodRunning {
177 for _, condition := range v.Status.Conditions {
178 if condition.Status != v1.ConditionTrue {
179 continue items
180 }
181 }
182
183 if group, have := v.Labels[podAffinityGroupLabel]; have {
184 log.Debugf("Namespace: %s, PodName: %s, PodIP: %s, Host: %s\n", v.Namespace, v.Name, v.Status.PodIP, v.Spec.NodeName)
185 rwPods = append(rwPods, &volthaPod{
186 name: v.Name,
187 ipAddr: v.Status.PodIP,
188 node: v.Spec.NodeName,
189 devIds: make(map[string]struct{}),
190 backend: afrouterRWClusterName + group,
191 })
192 } else {
193 log.Warnf("Pod %s found matching % without label %", v.Name, podLabelSelector, podAffinityGroupLabel)
194 }
195 }
196 }
197 return rwPods, nil
198}
199
200func reconcilePodDeviceIds(ctx context.Context, pod *volthaPod, ids map[string]struct{}) {
201 ctxTimeout, _ := context.WithTimeout(ctx, time.Second*5)
202 conn, err := connect(ctxTimeout, fmt.Sprintf("%s:%d", pod.ipAddr, podGrpcPort))
203 if err != nil {
204 log.Debugf("Could not reconcile devices from %s, could not connect: %s", pod.name, err)
205 return
206 }
207 defer conn.Close()
208
209 var idList cmn.IDs
210 for k := range ids {
211 idList.Items = append(idList.Items, &cmn.ID{Id: k})
212 }
213
214 client := vpb.NewVolthaServiceClient(conn)
215 _, err = client.ReconcileDevices(ctx, &idList)
216 if err != nil {
217 log.Errorf("Attempt to reconcile ids on pod %s failed: %s", pod.name, err)
218 return
219 }
220}
221
222func queryPodDeviceIds(ctx context.Context, pod *volthaPod) map[string]struct{} {
223 ctxTimeout, _ := context.WithTimeout(ctx, time.Second*5)
224 conn, err := connect(ctxTimeout, fmt.Sprintf("%s:%d", pod.ipAddr, podGrpcPort))
225 if err != nil {
226 log.Debugf("Could not query devices from %s, could not connect: %s", pod.name, err)
227 return nil
228 }
229 defer conn.Close()
230
231 client := vpb.NewVolthaServiceClient(conn)
232 devs, err := client.ListDeviceIds(ctx, &empty.Empty{})
233 if err != nil {
234 log.Error(err)
235 return nil
236 }
237
238 var ret = make(map[string]struct{})
239 for _, dv := range devs.Items {
240 ret[dv.Id] = struct{}{}
241 }
242 return ret
243}
244
245func setAffinity(ctx context.Context, client pb.ConfigurationClient, deviceId string, backend string) {
246 log.Debugf("Configuring backend %s with device id %s \n", backend, deviceId)
247 if res, err := client.SetAffinity(ctx, &pb.Affinity{
248 Router: afrouterRouterName,
249 Route: afrouterRouteName,
250 Cluster: afrouterRWClusterName,
251 Backend: backend,
252 Id: deviceId,
253 }); err != nil {
254 log.Debugf("failed affinity RPC call: %s\n", err)
255 } else {
256 log.Debugf("Result: %v\n", res)
257 }
258}
259
260func monitorDiscovery(kc kafka.Client, ctx context.Context, client pb.ConfigurationClient, ch <-chan *ic.InterContainerMessage, doneCh chan<- struct{}) {
261 defer close(doneCh)
262 defer kc.Stop()
263
264monitorLoop:
265 for {
266 select {
267 case <-ctx.Done():
268 break monitorLoop
269 case msg := <-ch:
270 log.Debug("Received a device discovery notification")
271 device := &ic.DeviceDiscovered{}
272 if err := ptypes.UnmarshalAny(msg.Body, device); err != nil {
273 log.Errorf("Could not unmarshal received notification %v", msg)
274 } else {
275 // somewhat hackish solution, backend is known from the first digit found in the publisher name
276 group := regexp.MustCompile(`\d`).FindString(device.Publisher)
277 if group != "" {
278 // set the affinity of the discovered device
279 setAffinity(ctx, client, device.Id, afrouterRWClusterName+group)
280 } else {
281 log.Error("backend is unknown")
282 }
283 }
284 }
285 }
286}
287
288func startDiscoveryMonitor(ctx context.Context, client pb.ConfigurationClient) (<-chan struct{}, error) {
289 doneCh := make(chan struct{})
290 // Connect to kafka for discovery events
291 kc, err := newKafkaClient(kafkaClientType, kafkaHost, kafkaPort, kafkaInstanceID)
292 if err != nil {
293 panic(err)
294 }
295
296 for {
297 if err := kc.Start(); err != nil {
298 log.Error("Could not connect to kafka")
299 } else {
300 break
301 }
302 select {
303 case <-ctx.Done():
304 close(doneCh)
305 return doneCh, errors.New("GRPC context done")
306
307 case <-time.After(5 * time.Second):
308 }
309 }
310 ch, err := kc.Subscribe(&kafka.Topic{Name: kafkaTopic})
311 if err != nil {
312 log.Errorf("Could not subscribe to the '%s' channel, discovery disabled", kafkaTopic)
313 close(doneCh)
314 kc.Stop()
315 return doneCh, err
316 }
317
318 go monitorDiscovery(kc, ctx, client, ch, doneCh)
319 return doneCh, nil
320}
321
322// coreMonitor polls the list of devices from all RW cores, pushes these devices
323// into the affinity router, and ensures that all cores in a backend have their devices synced
324func coreMonitor(ctx context.Context, client pb.ConfigurationClient, clientset *kubernetes.Clientset) {
325 // map[backend]map[deviceId]struct{}
326 deviceOwnership := make(map[string]map[string]struct{})
327loop:
328 for {
329 // get the rw core list from k8s
330 rwPods, err := getVolthaPods(clientset)
331 if err != nil {
332 log.Error(err)
333 continue
334 }
335
336 // for every pod
337 for _, pod := range rwPods {
338 // get the devices for this pod's backend
339 devices, have := deviceOwnership[pod.backend]
340 if !have {
341 devices = make(map[string]struct{})
342 deviceOwnership[pod.backend] = devices
343 }
344
345 coreDevices := queryPodDeviceIds(ctx, pod)
346
347 // handle devices that exist in the core, but we have just learned about
348 for deviceId := range coreDevices {
349 // if there's a new device
350 if _, have := devices[deviceId]; !have {
351 // add the device to our local list
352 devices[deviceId] = struct{}{}
353 // push the device into the affinity router
354 setAffinity(ctx, client, deviceId, pod.backend)
355 }
356 }
357
358 // ensure that the core knows about all devices in its backend
359 toSync := make(map[string]struct{})
360 for deviceId := range devices {
361 // if the pod is missing any devices
362 if _, have := coreDevices[deviceId]; !have {
363 // we will reconcile them
364 toSync[deviceId] = struct{}{}
365 }
366 }
367
368 if len(toSync) != 0 {
369 reconcilePodDeviceIds(ctx, pod, toSync)
370 }
371 }
372
373 select {
374 case <-ctx.Done():
375 // if we're done, exit
376 break loop
377 case <-time.After(10 * time.Second): // wait a while
378 }
379 }
380}
381
382// endOnClose cancels the context when the connection closes
383func connectionActiveContext(conn *grpc.ClientConn) context.Context {
384 ctx, disconnected := context.WithCancel(context.Background())
385 go func() {
386 for state := conn.GetState(); state != connectivity.TransientFailure && state != connectivity.Shutdown; state = conn.GetState() {
387 if !conn.WaitForStateChange(context.Background(), state) {
388 break
389 }
390 }
391 log.Infof("Connection to afrouter lost")
392 disconnected()
393 }()
394 return ctx
395}
396
397func main() {
398 config := &Configuration{}
399 cmdParse := flag.NewFlagSet(path.Base(os.Args[0]), flag.ContinueOnError)
400 config.DisplayVersionOnly = cmdParse.Bool("version", false, "Print version information and exit")
401
402 if err := cmdParse.Parse(os.Args[1:]); err != nil {
403 fmt.Printf("Error: %v\n", err)
404 os.Exit(1)
405 }
406
407 if *config.DisplayVersionOnly {
408 fmt.Println("VOLTHA API Server (afrouterd)")
409 fmt.Println(version.VersionInfo.String(" "))
410 return
411 }
412
413 // Set up logging
414 if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
415 log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
416 }
417
418 // Set up kubernetes api
419 clientset := k8sClientSet()
420
421 for {
422 // Connect to the affinity router
423 conn, err := connect(context.Background(), afrouterApiAddress) // This is a sidecar container so communicating over localhost
424 if err != nil {
425 panic(err)
426 }
427
428 // monitor the connection status, end context if connection is lost
429 ctx := connectionActiveContext(conn)
430
431 // set up the client
432 client := pb.NewConfigurationClient(conn)
433
434 // start the discovery monitor and core monitor
435 // these two processes do the majority of the work
436
437 log.Info("Starting discovery monitoring")
438 doneCh, _ := startDiscoveryMonitor(ctx, client)
439
440 log.Info("Starting core monitoring")
441 coreMonitor(ctx, client, clientset)
442
443 //ensure the discovery monitor to quit
444 <-doneCh
445
446 conn.Close()
447 }
448}