blob: b84dc3cfdbb7115059a96a3c9c5217ced6c44dfe [file] [log] [blame]
David K. Bainbridge157bdab2020-01-16 14:38:05 -08001/*
2 Copyright 2020 the original author or authors.
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*/
16package ofagent
17
18import (
19 "context"
20 "errors"
David Bainbridgef8ce7d22020-04-08 12:49:41 -070021 "time"
22
David K. Bainbridge157bdab2020-01-16 14:38:05 -080023 "github.com/golang/protobuf/ptypes/empty"
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -080024 "github.com/opencord/voltha-lib-go/v3/pkg/log"
25 "github.com/opencord/voltha-lib-go/v3/pkg/probe"
26 "github.com/opencord/voltha-protos/v3/go/voltha"
David K. Bainbridge157bdab2020-01-16 14:38:05 -080027 "google.golang.org/grpc"
David K. Bainbridge157bdab2020-01-16 14:38:05 -080028)
29
30func (ofa *OFAgent) establishConnectionToVoltha(p *probe.Probe) error {
31 if p != nil {
32 p.UpdateStatus("voltha", probe.ServiceStatusPreparing)
33 }
34
35 if ofa.volthaConnection != nil {
36 ofa.volthaConnection.Close()
37 }
38
39 ofa.volthaConnection = nil
David Bainbridgef8ce7d22020-04-08 12:49:41 -070040 ofa.volthaClient.Clear()
David K. Bainbridge157bdab2020-01-16 14:38:05 -080041 try := 1
42 for ofa.ConnectionMaxRetries == 0 || try < ofa.ConnectionMaxRetries {
43 conn, err := grpc.Dial(ofa.VolthaApiEndPoint, grpc.WithInsecure())
44 if err == nil {
45 svc := voltha.NewVolthaServiceClient(conn)
46 if svc != nil {
47 if _, err = svc.GetVoltha(context.Background(), &empty.Empty{}); err == nil {
48 logger.Debugw("Established connection to Voltha",
49 log.Fields{
50 "VolthaApiEndPoint": ofa.VolthaApiEndPoint,
51 })
52 ofa.volthaConnection = conn
David Bainbridgef8ce7d22020-04-08 12:49:41 -070053 ofa.volthaClient.Set(svc)
David K. Bainbridge157bdab2020-01-16 14:38:05 -080054 if p != nil {
55 p.UpdateStatus("voltha", probe.ServiceStatusRunning)
56 }
57 ofa.events <- ofaEventVolthaConnected
58 return nil
59 }
60 }
61 }
62 logger.Warnw("Failed to connect to voltha",
63 log.Fields{
64 "VolthaApiEndPoint": ofa.VolthaApiEndPoint,
65 "error": err.Error(),
66 })
67 if ofa.ConnectionMaxRetries == 0 || try < ofa.ConnectionMaxRetries {
68 if ofa.ConnectionMaxRetries != 0 {
69 try += 1
70 }
71 time.Sleep(ofa.ConnectionRetryDelay)
72 }
73 }
74 if p != nil {
75 p.UpdateStatus("voltha", probe.ServiceStatusFailed)
76 }
77 return errors.New("failed-to-connect-to-voltha")
78}