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