blob: 44bfae011507bbaab3a889a3303ea58a0ac41431 [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001/*
2 * Copyright 2020-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
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000017//Package core provides the utility for onu devices, flows and statistics
18package core
Holger Hildebrandtfa074992020-03-27 15:42:06 +000019
20import (
21 "context"
22 "errors"
23 "fmt"
khenaidoo55cebc62021-12-08 14:44:41 -050024 "hash/fnv"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000025 "sync"
26 "time"
27
Holger Hildebrandt60652202021-11-02 11:09:36 +000028 "github.com/opencord/voltha-lib-go/v7/pkg/db"
khenaidoo7d3c5582021-08-11 18:09:44 -040029 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
dbainbri4d3a0dc2020-12-02 00:33:42 +000030
khenaidoo7d3c5582021-08-11 18:09:44 -040031 conf "github.com/opencord/voltha-lib-go/v7/pkg/config"
32 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoo42dcdfd2021-10-19 17:34:12 -040033 "github.com/opencord/voltha-protos/v5/go/health"
34 "github.com/opencord/voltha-protos/v5/go/olt_inter_adapter_service"
khenaidoo7d3c5582021-08-11 18:09:44 -040035 "google.golang.org/grpc"
khenaidoo55cebc62021-12-08 14:44:41 -050036 "google.golang.org/grpc/codes"
37 "google.golang.org/grpc/status"
khenaidoo7d3c5582021-08-11 18:09:44 -040038
39 "github.com/golang/protobuf/ptypes/empty"
40 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
41 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
42 "github.com/opencord/voltha-lib-go/v7/pkg/log"
khenaidoo42dcdfd2021-10-19 17:34:12 -040043 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo7d3c5582021-08-11 18:09:44 -040044 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoo42dcdfd2021-10-19 17:34:12 -040045 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
46 "github.com/opencord/voltha-protos/v5/go/omci"
khenaidoo7d3c5582021-08-11 18:09:44 -040047 "github.com/opencord/voltha-protos/v5/go/voltha"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000048
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000049 cmn "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/common"
Matteo Scandolo761f7512020-11-23 15:52:40 -080050 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/config"
Holger Hildebrandt60652202021-11-02 11:09:36 +000051 pmmgr "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/pmmgr"
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000052 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/swupg"
53 uniprt "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/uniprt"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000054)
55
Holger Hildebrandt60652202021-11-02 11:09:36 +000056var onuKvStorePathPrefixes = []string{cmn.CBasePathOnuKVStore, pmmgr.CPmKvStorePrefixBase}
57
khenaidoo55cebc62021-12-08 14:44:41 -050058type reachabilityFromRemote struct {
59 lastKeepAlive time.Time
60 keepAliveInterval int64
61}
62
Holger Hildebrandtfa074992020-03-27 15:42:06 +000063//OpenONUAC structure holds the ONU core information
64type OpenONUAC struct {
Himani Chawla6d2ae152020-09-02 13:11:20 +053065 deviceHandlers map[string]*deviceHandler
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +000066 deviceHandlersCreateChan map[string]chan bool //channels for deviceHandler create events
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000067 mutexDeviceHandlersMap sync.RWMutex
khenaidoo7d3c5582021-08-11 18:09:44 -040068 coreClient *vgrpc.Client
69 parentAdapterClients map[string]*vgrpc.Client
70 lockParentAdapterClients sync.RWMutex
khenaidoo55cebc62021-12-08 14:44:41 -050071 reachableFromRemote map[string]*reachabilityFromRemote
72 lockReachableFromRemote sync.RWMutex
Himani Chawlac07fda02020-12-09 16:21:21 +053073 eventProxy eventif.EventProxy
mpagenkoaf801632020-07-03 10:00:42 +000074 kvClient kvstore.Client
Matteo Scandolof1f39a72020-11-24 12:08:11 -080075 cm *conf.ConfigManager
Holger Hildebrandtfa074992020-03-27 15:42:06 +000076 config *config.AdapterFlags
77 numOnus int
Matteo Scandolo127c59d2021-01-28 11:31:18 -080078 KVStoreAddress string
Holger Hildebrandtfa074992020-03-27 15:42:06 +000079 KVStoreType string
mpagenkoaf801632020-07-03 10:00:42 +000080 KVStoreTimeout time.Duration
Holger Hildebrandt61b24d02020-11-16 13:36:40 +000081 mibTemplatesGenerated map[string]bool
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000082 mutexMibTemplateGenerated sync.RWMutex
Holger Hildebrandtfa074992020-03-27 15:42:06 +000083 exitChannel chan int
84 HeartbeatCheckInterval time.Duration
85 HeartbeatFailReportInterval time.Duration
mpagenkodff5dda2020-08-28 11:52:01 +000086 AcceptIncrementalEvto bool
khenaidoo55cebc62021-12-08 14:44:41 -050087 pSupportedFsms *cmn.OmciDeviceFsms
88 maxTimeoutInterAdapterComm time.Duration
89 maxTimeoutReconciling time.Duration
90 pDownloadManager *swupg.AdapterDownloadManager
91 pFileManager *swupg.FileDownloadManager //let coexist 'old and new' DownloadManager as long as 'old' does not get obsolete
92 MetricsEnabled bool
93 mibAuditInterval time.Duration
94 omciTimeout int // in seconds
95 alarmAuditInterval time.Duration
96 dlToOnuTimeout4M time.Duration
97 rpcTimeout time.Duration
98 maxConcurrentFlowsPerUni int
Holger Hildebrandtfa074992020-03-27 15:42:06 +000099}
100
101//NewOpenONUAC returns a new instance of OpenONU_AC
khenaidoo7d3c5582021-08-11 18:09:44 -0400102func NewOpenONUAC(ctx context.Context, coreClient *vgrpc.Client, eventProxy eventif.EventProxy,
103 kvClient kvstore.Client, cfg *config.AdapterFlags, cm *conf.ConfigManager) *OpenONUAC {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000104 var openOnuAc OpenONUAC
105 openOnuAc.exitChannel = make(chan int, 1)
Himani Chawla6d2ae152020-09-02 13:11:20 +0530106 openOnuAc.deviceHandlers = make(map[string]*deviceHandler)
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000107 openOnuAc.deviceHandlersCreateChan = make(map[string]chan bool)
khenaidoo7d3c5582021-08-11 18:09:44 -0400108 openOnuAc.parentAdapterClients = make(map[string]*vgrpc.Client)
khenaidoo55cebc62021-12-08 14:44:41 -0500109 openOnuAc.reachableFromRemote = make(map[string]*reachabilityFromRemote)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000110 openOnuAc.mutexDeviceHandlersMap = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000111 openOnuAc.config = cfg
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800112 openOnuAc.cm = cm
khenaidoo7d3c5582021-08-11 18:09:44 -0400113 openOnuAc.coreClient = coreClient
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000114 openOnuAc.numOnus = cfg.OnuNumber
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000115 openOnuAc.eventProxy = eventProxy
mpagenkoaf801632020-07-03 10:00:42 +0000116 openOnuAc.kvClient = kvClient
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800117 openOnuAc.KVStoreAddress = cfg.KVStoreAddress
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000118 openOnuAc.KVStoreType = cfg.KVStoreType
mpagenkoaf801632020-07-03 10:00:42 +0000119 openOnuAc.KVStoreTimeout = cfg.KVStoreTimeout
Holger Hildebrandt61b24d02020-11-16 13:36:40 +0000120 openOnuAc.mibTemplatesGenerated = make(map[string]bool)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000121 openOnuAc.mutexMibTemplateGenerated = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000122 openOnuAc.HeartbeatCheckInterval = cfg.HeartbeatCheckInterval
123 openOnuAc.HeartbeatFailReportInterval = cfg.HeartbeatFailReportInterval
mpagenkodff5dda2020-08-28 11:52:01 +0000124 openOnuAc.AcceptIncrementalEvto = cfg.AccIncrEvto
Himani Chawlad96df182020-09-28 11:12:02 +0530125 openOnuAc.maxTimeoutInterAdapterComm = cfg.MaxTimeoutInterAdapterComm
Holger Hildebrandt38985dc2021-02-18 16:25:20 +0000126 openOnuAc.maxTimeoutReconciling = cfg.MaxTimeoutReconciling
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000127 //openOnuAc.GrpcTimeoutInterval = cfg.GrpcTimeoutInterval
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000128 openOnuAc.MetricsEnabled = cfg.MetricsEnabled
Holger Hildebrandte3677f12021-02-05 14:50:56 +0000129 openOnuAc.mibAuditInterval = cfg.MibAuditInterval
Girish Gowdra0b235842021-03-09 13:06:46 -0800130 // since consumers of OMCI timeout value everywhere in code is in "int seconds", do this useful conversion
131 openOnuAc.omciTimeout = int(cfg.OmciTimeout.Seconds())
Himani Chawla075f1642021-03-15 19:23:24 +0530132 openOnuAc.alarmAuditInterval = cfg.AlarmAuditInterval
mpagenkoc26d4c02021-05-06 14:27:57 +0000133 openOnuAc.dlToOnuTimeout4M = cfg.DownloadToOnuTimeout4MB
khenaidoo7d3c5582021-08-11 18:09:44 -0400134 openOnuAc.rpcTimeout = cfg.RPCTimeout
Girish Gowdrae95687a2021-09-08 16:30:58 -0700135 openOnuAc.maxConcurrentFlowsPerUni = cfg.MaxConcurrentFlowsPerUni
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000136
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000137 openOnuAc.pSupportedFsms = &cmn.OmciDeviceFsms{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000138 "mib-synchronizer": {
139 //mibSyncFsm, // Implements the MIB synchronization state machine
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000140 DatabaseClass: mibDbVolatileDictImpl, // Implements volatile ME MIB database
Himani Chawla4d908332020-08-31 12:30:20 +0530141 //true, // Advertise events on OpenOMCI event bus
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000142 AuditInterval: openOnuAc.mibAuditInterval, // Time to wait between MIB audits. 0 to disable audits.
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000143 // map[string]func() error{
144 // "mib-upload": onuDeviceEntry.MibUploadTask,
145 // "mib-template": onuDeviceEntry.MibTemplateTask,
146 // "get-mds": onuDeviceEntry.GetMdsTask,
147 // "mib-audit": onuDeviceEntry.GetMdsTask,
148 // "mib-resync": onuDeviceEntry.MibResyncTask,
149 // "mib-reconcile": onuDeviceEntry.MibReconcileTask,
150 // },
151 },
152 }
153
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000154 openOnuAc.pDownloadManager = swupg.NewAdapterDownloadManager(ctx)
155 openOnuAc.pFileManager = swupg.NewFileDownloadManager(ctx)
mpagenkoc26d4c02021-05-06 14:27:57 +0000156 openOnuAc.pFileManager.SetDownloadTimeout(ctx, cfg.DownloadToAdapterTimeout)
mpagenkoc8bba412021-01-15 15:38:44 +0000157
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000158 return &openOnuAc
159}
160
161//Start starts (logs) the adapter
162func (oo *OpenONUAC) Start(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000163 logger.Info(ctx, "starting-openonu-adapter")
mpagenkoc8bba412021-01-15 15:38:44 +0000164
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000165 return nil
166}
167
Himani Chawla6d2ae152020-09-02 13:11:20 +0530168/*
169//stop terminates the session
170func (oo *OpenONUAC) stop(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000171 logger.Info(ctx,"stopping-device-manager")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000172 oo.exitChannel <- 1
dbainbri4d3a0dc2020-12-02 00:33:42 +0000173 logger.Info(ctx,"device-manager-stopped")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000174 return nil
175}
Himani Chawla6d2ae152020-09-02 13:11:20 +0530176*/
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000177
Himani Chawla6d2ae152020-09-02 13:11:20 +0530178func (oo *OpenONUAC) addDeviceHandlerToMap(ctx context.Context, agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000179 oo.mutexDeviceHandlersMap.Lock()
180 defer oo.mutexDeviceHandlersMap.Unlock()
181 if _, exist := oo.deviceHandlers[agent.DeviceID]; !exist {
182 oo.deviceHandlers[agent.DeviceID] = agent
183 oo.deviceHandlers[agent.DeviceID].start(ctx)
184 if _, exist := oo.deviceHandlersCreateChan[agent.DeviceID]; exist {
185 logger.Debugw(ctx, "deviceHandler created - trigger processing of pending ONU_IND_REQUEST", log.Fields{"device-id": agent.DeviceID})
186 oo.deviceHandlersCreateChan[agent.DeviceID] <- true
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000187 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000188 }
189}
190
Himani Chawla6d2ae152020-09-02 13:11:20 +0530191func (oo *OpenONUAC) deleteDeviceHandlerToMap(agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000192 oo.mutexDeviceHandlersMap.Lock()
193 defer oo.mutexDeviceHandlersMap.Unlock()
194 delete(oo.deviceHandlers, agent.DeviceID)
195 delete(oo.deviceHandlersCreateChan, agent.DeviceID)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000196}
197
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000198//getDeviceHandler gets the ONU deviceHandler and may wait until it is created
dbainbri4d3a0dc2020-12-02 00:33:42 +0000199func (oo *OpenONUAC) getDeviceHandler(ctx context.Context, deviceID string, aWait bool) *deviceHandler {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000200 oo.mutexDeviceHandlersMap.Lock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000201 agent, ok := oo.deviceHandlers[deviceID]
202 if aWait && !ok {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000203 logger.Infow(ctx, "Race condition: deviceHandler not present - wait for creation or timeout",
Holger Hildebrandt6c1fb0a2020-11-25 15:41:01 +0000204 log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000205 if _, exist := oo.deviceHandlersCreateChan[deviceID]; !exist {
206 oo.deviceHandlersCreateChan[deviceID] = make(chan bool, 1)
207 }
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800208 deviceCreateChan := oo.deviceHandlersCreateChan[deviceID]
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000209 //keep the read sema short to allow for subsequent write
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000210 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000211 // based on concurrent processing the deviceHandler creation may not yet be finished at his point
212 // so it might be needed to wait here for that event with some timeout
213 select {
214 case <-time.After(1 * time.Second): //timer may be discussed ...
dbainbri4d3a0dc2020-12-02 00:33:42 +0000215 logger.Warnw(ctx, "No valid deviceHandler created after max WaitTime", log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000216 return nil
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800217 case <-deviceCreateChan:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000218 logger.Debugw(ctx, "deviceHandler is ready now - continue", log.Fields{"device-id": deviceID})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000219 oo.mutexDeviceHandlersMap.RLock()
220 defer oo.mutexDeviceHandlersMap.RUnlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000221 return oo.deviceHandlers[deviceID]
222 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000223 }
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000224 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000225 return agent
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000226}
227
khenaidoo7d3c5582021-08-11 18:09:44 -0400228// GetHealthStatus is used as a service readiness validation as a grpc connection
khenaidoo55cebc62021-12-08 14:44:41 -0500229func (oo *OpenONUAC) GetHealthStatus(ctx context.Context, clientConn *common.Connection) (*health.HealthStatus, error) {
230 // Update the remote reachability
231 oo.updateReachabilityFromRemote(ctx, clientConn)
232
khenaidoo42dcdfd2021-10-19 17:34:12 -0400233 return &health.HealthStatus{State: health.HealthStatus_HEALTHY}, nil
Holger Hildebrandt6c1fb0a2020-11-25 15:41:01 +0000234}
235
khenaidoo7d3c5582021-08-11 18:09:44 -0400236// AdoptDevice creates a new device handler if not present already and then adopts the device
237func (oo *OpenONUAC) AdoptDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000238 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000239 logger.Warn(ctx, "voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400240 return nil, errors.New("nil-device")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000241 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000242 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id})
Himani Chawla6d2ae152020-09-02 13:11:20 +0530243 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000244 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400245 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000246 oo.addDeviceHandlerToMap(ctx, handler)
khenaidoo7d3c5582021-08-11 18:09:44 -0400247
248 // Setup the grpc communication with the parent adapter
249 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
250 // TODO: Cleanup on failure needed
251 return nil, err
252 }
253
254 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), device)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000255 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400256 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000257}
258
khenaidoo7d3c5582021-08-11 18:09:44 -0400259//ReconcileDevice is called once when the adapter needs to re-create device - usually on core restart
260func (oo *OpenONUAC) ReconcileDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000261 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000262 logger.Warn(ctx, "reconcile-device-voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400263 return nil, errors.New("nil-device")
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000264 }
khenaidoo55cebc62021-12-08 14:44:41 -0500265 logger.Infow(ctx, "reconcile-device", log.Fields{"device-id": device.Id, "parent-id": device.ParentId})
266
267 // Check whether the grpc client in the adapter of the parent device can reach us yet
268 if !oo.isReachableFromRemote(device.ProxyAddress.AdapterEndpoint, device.ParentId) {
269 return nil, status.Errorf(codes.Unavailable, "adapter-not-reachable-from-parent-%s", device.ProxyAddress.AdapterEndpoint)
270 }
271
Himani Chawla6d2ae152020-09-02 13:11:20 +0530272 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000273 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400274 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000275 oo.addDeviceHandlerToMap(ctx, handler)
276 handler.device = device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400277 if err := handler.updateDeviceStateInCore(log.WithSpanFromContext(context.Background(), ctx), &ca.DeviceStateFilter{
khenaidoo7d3c5582021-08-11 18:09:44 -0400278 DeviceId: device.Id,
279 OperStatus: voltha.OperStatus_RECONCILING,
280 ConnStatus: device.ConnectStatus,
281 }); err != nil {
282 return nil, fmt.Errorf("not able to update device state to reconciling. Err : %s", err.Error())
Maninderb5187552021-03-23 22:23:42 +0530283 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400284 // Setup the grpc communication with the parent adapter
285 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
286 // TODO: Cleanup on failure needed
287 return nil, err
288 }
289
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000290 handler.StartReconciling(log.WithSpanFromContext(context.Background(), ctx), false)
khenaidoo7d3c5582021-08-11 18:09:44 -0400291 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), handler.device)
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000292 // reconcilement will be continued after onu-device entry is added
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000293 } else {
khenaidoo7d3c5582021-08-11 18:09:44 -0400294 return nil, fmt.Errorf(fmt.Sprintf("device-already-reconciled-or-active-%s", device.Id))
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000295 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400296 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000297}
298
khenaidoo7d3c5582021-08-11 18:09:44 -0400299//DisableDevice disables the given device
300func (oo *OpenONUAC) DisableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000301 logger.Infow(ctx, "disable-device", log.Fields{"device-id": device.Id})
302 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400303 go handler.disableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
304 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300305 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000306 logger.Warnw(ctx, "no handler found for device-disable", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400307 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000308}
309
khenaidoo7d3c5582021-08-11 18:09:44 -0400310//ReEnableDevice enables the onu device after disable
311func (oo *OpenONUAC) ReEnableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000312 logger.Infow(ctx, "reenable-device", log.Fields{"device-id": device.Id})
313 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400314 go handler.reEnableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
315 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300316 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000317 logger.Warnw(ctx, "no handler found for device-reenable", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400318 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000319}
320
khenaidoo7d3c5582021-08-11 18:09:44 -0400321//RebootDevice reboots the given device
322func (oo *OpenONUAC) RebootDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000323 logger.Infow(ctx, "reboot-device", log.Fields{"device-id": device.Id})
324 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400325 go handler.rebootDevice(log.WithSpanFromContext(context.Background(), ctx), true, device) //reboot request with device checking
326 return &empty.Empty{}, nil
ozgecanetsiae11479f2020-07-06 09:44:47 +0300327 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000328 logger.Warnw(ctx, "no handler found for device-reboot", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400329 return nil, fmt.Errorf("handler-not-found-for-device: %s", device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000330}
331
khenaidoo7d3c5582021-08-11 18:09:44 -0400332// DeleteDevice deletes the given device
333func (oo *OpenONUAC) DeleteDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
334 nctx := log.WithSpanFromContext(context.Background(), ctx)
khenaidoo7d3c5582021-08-11 18:09:44 -0400335 logger.Infow(ctx, "delete-device", log.Fields{"device-id": device.Id, "SerialNumber": device.SerialNumber, "ctx": ctx, "nctx": nctx})
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000336
dbainbri4d3a0dc2020-12-02 00:33:42 +0000337 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
Girish Gowdra0e533642021-03-02 22:02:51 -0800338 var errorsList []error
Holger Hildebrandtff05b682021-03-16 15:02:05 +0000339
340 handler.mutexDeletionInProgressFlag.Lock()
341 handler.deletionInProgress = true
342 handler.mutexDeletionInProgressFlag.Unlock()
343
Holger Hildebrandt60652202021-11-02 11:09:36 +0000344 if err := handler.resetFsms(ctx, true); err != nil {
345 errorsList = append(errorsList, err)
346 }
Girish Gowdrae95687a2021-09-08 16:30:58 -0700347 for _, uni := range handler.uniEntityMap {
348 if handler.GetFlowMonitoringIsRunning(uni.UniID) {
349 handler.stopFlowMonitoringRoutine[uni.UniID] <- true
350 logger.Debugw(ctx, "sent stop signal to self flow monitoring routine", log.Fields{"device-id": device.Id})
351 }
352 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000353 //don't leave any garbage in kv-store
354 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
355 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000356 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000357 oo.deleteDeviceHandlerToMap(handler)
358 go handler.PrepareForGarbageCollection(ctx, handler.DeviceID)
Holger Hildebrandt60652202021-11-02 11:09:36 +0000359
Girish Gowdra0e533642021-03-02 22:02:51 -0800360 if len(errorsList) > 0 {
361 logger.Errorw(ctx, "one-or-more-error-during-device-delete", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400362 return nil, fmt.Errorf("one-or-more-error-during-device-delete, errors:%v", errorsList)
Girish Gowdra0e533642021-03-02 22:02:51 -0800363 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400364 return &empty.Empty{}, nil
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000365 }
Holger Hildebrandt60652202021-11-02 11:09:36 +0000366 logger.Infow(ctx, "no handler found for device-deletion - trying to delete remaining data in the kv-store ", log.Fields{"device-id": device.Id})
367
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000368 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
369 return nil, err
Holger Hildebrandt60652202021-11-02 11:09:36 +0000370 }
371 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000372}
373
khenaidoo7d3c5582021-08-11 18:09:44 -0400374//UpdateFlowsIncrementally updates (add/remove) the flows on a given device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400375func (oo *OpenONUAC) UpdateFlowsIncrementally(ctx context.Context, incrFlows *ca.IncrementalFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400376 logger.Infow(ctx, "update-flows-incrementally", log.Fields{"device-id": incrFlows.Device.Id})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000377
mpagenkofc4f56e2020-11-04 17:17:49 +0000378 //flow config is relayed to handler even if the device might be in some 'inactive' state
379 // let the handler or related FSM's decide, what to do with the modified flow state info
380 // at least the flow-remove must be done in respect to internal data, while OMCI activity might not be needed here
mpagenkodff5dda2020-08-28 11:52:01 +0000381
382 // For now, there is no support for group changes (as in the actual Py-adapter code)
mpagenkofc4f56e2020-11-04 17:17:49 +0000383 // but processing is continued for flowUpdate possibly also set in the request
khenaidoo7d3c5582021-08-11 18:09:44 -0400384 if incrFlows.Groups.ToAdd != nil && incrFlows.Groups.ToAdd.Items != nil {
385 logger.Warnw(ctx, "Update-flow-incr: group add not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000386 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400387 if incrFlows.Groups.ToRemove != nil && incrFlows.Groups.ToRemove.Items != nil {
388 logger.Warnw(ctx, "Update-flow-incr: group remove not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000389 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400390 if incrFlows.Groups.ToUpdate != nil && incrFlows.Groups.ToUpdate.Items != nil {
391 logger.Warnw(ctx, "Update-flow-incr: group update not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000392 }
393
khenaidoo7d3c5582021-08-11 18:09:44 -0400394 if handler := oo.getDeviceHandler(ctx, incrFlows.Device.Id, false); handler != nil {
395 if err := handler.FlowUpdateIncremental(log.WithSpanFromContext(context.Background(), ctx), incrFlows.Flows, incrFlows.Groups, incrFlows.FlowMetadata); err != nil {
396 return nil, err
397 }
398 return &empty.Empty{}, nil
mpagenkodff5dda2020-08-28 11:52:01 +0000399 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400400 logger.Warnw(ctx, "no handler found for incremental flow update", log.Fields{"device-id": incrFlows.Device.Id})
401 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", incrFlows.Device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000402}
403
khenaidoo7d3c5582021-08-11 18:09:44 -0400404//UpdatePmConfig returns PmConfigs nil or error
khenaidoo42dcdfd2021-10-19 17:34:12 -0400405func (oo *OpenONUAC) UpdatePmConfig(ctx context.Context, configs *ca.PmConfigsInfo) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400406 logger.Infow(ctx, "update-pm-config", log.Fields{"device-id": configs.DeviceId})
407 if handler := oo.getDeviceHandler(ctx, configs.DeviceId, false); handler != nil {
408 if err := handler.updatePmConfig(log.WithSpanFromContext(context.Background(), ctx), configs.PmConfigs); err != nil {
409 return nil, err
410 }
411 return &empty.Empty{}, nil
Girish Gowdrae09a6202021-01-12 18:10:59 -0800412 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400413 logger.Warnw(ctx, "no handler found for update-pm-config", log.Fields{"device-id": configs.DeviceId})
414 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", configs.DeviceId))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000415}
416
khenaidoo7d3c5582021-08-11 18:09:44 -0400417//DownloadImage requests downloading some image according to indications as given in request
Andrea Campanella71e546a2021-02-26 11:09:33 +0100418//The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400419func (oo *OpenONUAC) DownloadImage(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400420 ctx = log.WithSpanFromContext(context.Background(), ctx)
421 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000422 if !oo.pDownloadManager.ImageExists(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400423 logger.Debugw(ctx, "start image download", log.Fields{"image-description": imageInfo.Image})
mpagenko15ff4a52021-03-02 10:09:20 +0000424 // Download_image is not supposed to be blocking, anyway let's call the DownloadManager still synchronously to detect 'fast' problems
425 // the download itself is later done in background
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000426 if err := oo.pDownloadManager.StartDownload(ctx, imageInfo.Image); err != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400427 return nil, err
428 }
429 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000430 }
431 // image already exists
khenaidoo7d3c5582021-08-11 18:09:44 -0400432 logger.Debugw(ctx, "image already downloaded", log.Fields{"image-description": imageInfo.Image})
433 return imageInfo.Image, nil
mpagenkoc8bba412021-01-15 15:38:44 +0000434 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400435
436 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000437}
438
mpagenko59862f02021-10-11 08:53:18 +0000439//ActivateImageUpdate requests downloading some Onu Software image to the ONU via OMCI
Andrea Campanella71e546a2021-02-26 11:09:33 +0100440// according to indications as given in request and on success activate the image on the ONU
441//The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400442func (oo *OpenONUAC) ActivateImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400443 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000444 if oo.pDownloadManager.ImageLocallyDownloaded(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400445 if handler := oo.getDeviceHandler(ctx, imageInfo.Device.Id, false); handler != nil {
mpagenko15ff4a52021-03-02 10:09:20 +0000446 logger.Debugw(ctx, "image download on omci requested", log.Fields{
khenaidoo7d3c5582021-08-11 18:09:44 -0400447 "image-description": imageInfo.Image, "device-id": imageInfo.Device.Id})
448 if err := handler.doOnuSwUpgrade(ctx, imageInfo.Image, oo.pDownloadManager); err != nil {
449 return nil, err
450 }
451 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000452 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400453 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": imageInfo.Device.Id})
454 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found - device-id: %s", imageInfo.Device.Id))
mpagenko057889c2021-01-21 16:51:58 +0000455 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400456 logger.Debugw(ctx, "image not yet downloaded on activate request", log.Fields{"image-description": imageInfo.Image})
457 return nil, fmt.Errorf(fmt.Sprintf("image-not-yet-downloaded - device-id: %s", imageInfo.Device.Id))
mpagenkoc8bba412021-01-15 15:38:44 +0000458 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400459 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000460}
461
khenaidoo7d3c5582021-08-11 18:09:44 -0400462//GetSingleValue handles the core request to retrieve uni status
463func (oo *OpenONUAC) GetSingleValue(ctx context.Context, request *extension.SingleGetValueRequest) (*extension.SingleGetValueResponse, error) {
kesavandfdf77632021-01-26 23:40:33 -0500464 logger.Infow(ctx, "Single_get_value_request", log.Fields{"request": request})
465
466 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
467 switch reqType := request.GetRequest().GetRequest().(type) {
468 case *extension.GetValueRequest_UniInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000469 return handler.GetUniPortStatus(ctx, reqType.UniInfo), nil
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700470 case *extension.GetValueRequest_OnuOpticalInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000471 CommChan := make(chan cmn.Message)
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700472 respChan := make(chan extension.SingleGetValueResponse)
473 // Initiate the self test request
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000474 if err := handler.pSelfTestHdlr.SelfTestRequestStart(ctx, *request, CommChan, respChan); err != nil {
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700475 return &extension.SingleGetValueResponse{
476 Response: &extension.GetValueResponse{
477 Status: extension.GetValueResponse_ERROR,
478 ErrReason: extension.GetValueResponse_INTERNAL_ERROR,
479 },
480 }, err
481 }
482 // The timeout handling is already implemented in omci_self_test_handler module
483 resp := <-respChan
484 return &resp, nil
Himani Chawla43f95ff2021-06-03 00:24:12 +0530485 case *extension.GetValueRequest_OnuInfo:
486 return handler.getOnuOMCICounters(ctx, reqType.OnuInfo), nil
kesavandfdf77632021-01-26 23:40:33 -0500487 default:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000488 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_UNSUPPORTED), nil
kesavandfdf77632021-01-26 23:40:33 -0500489
490 }
491 }
492 logger.Errorw(ctx, "Single_get_value_request failed ", log.Fields{"request": request})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000493 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_INVALID_DEVICE_ID), nil
mpagenkoc8bba412021-01-15 15:38:44 +0000494}
495
mpagenko83144272021-04-27 10:06:22 +0000496//if update >= 4.3.0
mpagenkoc26d4c02021-05-06 14:27:57 +0000497// Note: already with the implementation of the 'old' download interface problems were detected when the argument name used here is not the same
498// as defined in the adapter interface file. That sounds strange and the effects were strange as well.
499// The reason for that was never finally investigated.
500// To be on the safe side argument names are left here always as defined in iAdapter.go .
mpagenko83144272021-04-27 10:06:22 +0000501
khenaidoo7d3c5582021-08-11 18:09:44 -0400502// DownloadOnuImage downloads (and optionally activates and commits) the indicated ONU image to the requested ONU(s)
mpagenko83144272021-04-27 10:06:22 +0000503// if the image is not yet present on the adapter it has to be automatically downloaded
khenaidoo7d3c5582021-08-11 18:09:44 -0400504func (oo *OpenONUAC) DownloadOnuImage(ctx context.Context, request *voltha.DeviceImageDownloadRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000505 if request != nil && len((*request).DeviceId) > 0 && (*request).Image.Version != "" {
506 loResponse := voltha.DeviceImageResponse{}
507 imageIdentifier := (*request).Image.Version
mpagenkoc497ee32021-11-10 17:30:20 +0000508 downloadStartDone := false
mpagenkoc26d4c02021-05-06 14:27:57 +0000509 firstDevice := true
510 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000511 var onuVolthaDevice *voltha.Device
512 var devErr error
mpagenkoc26d4c02021-05-06 14:27:57 +0000513 for _, pCommonID := range (*request).DeviceId {
mpagenko38662d02021-08-11 09:45:19 +0000514 vendorIDMatch := true
mpagenkoc26d4c02021-05-06 14:27:57 +0000515 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000516 loDeviceImageState := voltha.DeviceImageState{}
517 loDeviceImageState.DeviceId = loDeviceID
518 loImageState := voltha.ImageState{}
519 loDeviceImageState.ImageState = &loImageState
520 loDeviceImageState.ImageState.Version = (*request).Image.Version
mpagenko38662d02021-08-11 09:45:19 +0000521
mpagenko59862f02021-10-11 08:53:18 +0000522 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400523 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000524 if handler != nil {
525 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
526 } else {
527 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
528 devErr = errors.New("no handler found for device-id")
khenaidoo7d3c5582021-08-11 18:09:44 -0400529 }
mpagenko59862f02021-10-11 08:53:18 +0000530 if devErr != nil || onuVolthaDevice == nil {
531 logger.Warnw(ctx, "Failed to fetch ONU device for image download",
532 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000533 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
534 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //proto restriction, better option: 'INVALID_DEVICE'
mpagenkoc26d4c02021-05-06 14:27:57 +0000535 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000536 } else {
mpagenko38662d02021-08-11 09:45:19 +0000537 if firstDevice {
538 //start/verify download of the image to the adapter based on first found device only
539 // use the OnuVendor identification from first given device
mpagenkoc497ee32021-11-10 17:30:20 +0000540
541 // note: if the request was done for a list of devices on the Voltha interface, rwCore
542 // translates that into a new rpc for each device, hence each device will be the first device in parallel requests!
mpagenko38662d02021-08-11 09:45:19 +0000543 firstDevice = false
544 vendorID = onuVolthaDevice.VendorId
545 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
mpagenkoc497ee32021-11-10 17:30:20 +0000546 logger.Infow(ctx, "download request for file",
547 log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000548
mpagenkoc497ee32021-11-10 17:30:20 +0000549 // call the StartDownload synchronously to detect 'immediate' download problems
550 // the real download itself is later done in background
551 if fileState, err := oo.pFileManager.StartDownload(ctx, imageIdentifier, (*request).Image.Url); err == nil {
mpagenko38662d02021-08-11 09:45:19 +0000552 // note: If the image (with vendorId+name) has already been downloaded before from some other
mpagenkoc497ee32021-11-10 17:30:20 +0000553 // valid URL, the current download request is not executed (current code delivers URL error).
554 // If the operators want to ensure that the new URL
mpagenko38662d02021-08-11 09:45:19 +0000555 // is really used, then they first have to use the 'abort' API to remove the existing image!
556 // (abort API can be used also after some successful download to just remove the image from adapter)
mpagenkoc497ee32021-11-10 17:30:20 +0000557 if fileState == swupg.CFileStateDlSucceeded || fileState == swupg.CFileStateDlStarted {
558 downloadStartDone = true
559 } //else fileState may also indicate error situation, where the requested image is not ready to be used for other devices
mpagenko38662d02021-08-11 09:45:19 +0000560 }
561 } else {
562 //for all following devices verify the matching vendorID
563 if onuVolthaDevice.VendorId != vendorID {
564 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
565 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
566 vendorIDMatch = false
567 }
568 }
mpagenkoc497ee32021-11-10 17:30:20 +0000569 if downloadStartDone && vendorIDMatch {
mpagenko38662d02021-08-11 09:45:19 +0000570 // start the ONU download activity for each possible device
mpagenkoc497ee32021-11-10 17:30:20 +0000571 logger.Infow(ctx, "request image download to ONU on omci ", log.Fields{
mpagenko59862f02021-10-11 08:53:18 +0000572 "image-id": imageIdentifier, "device-id": loDeviceID})
573 //onu upgrade handling called in background without immediate error evaluation here
574 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
575 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
576 go handler.onuSwUpgradeAfterDownload(ctx, request, oo.pFileManager, imageIdentifier)
577 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_STARTED
578 loDeviceImageState.ImageState.Reason = voltha.ImageState_NO_ERROR
579 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenko38662d02021-08-11 09:45:19 +0000580 } else {
581 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
mpagenkoc497ee32021-11-10 17:30:20 +0000582 if !downloadStartDone {
583 //based on above fileState more descriptive error codes would be possible, e.g
584 // IMAGE_EXISTS_WITH_DIFFERENT_URL - would require proto buf update
mpagenko38662d02021-08-11 09:45:19 +0000585 loDeviceImageState.ImageState.Reason = voltha.ImageState_INVALID_URL
586 } else { //only logical option is !vendorIDMatch
587 loDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
588 }
589 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
590 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000591 }
mpagenko2f2f2362021-06-07 08:25:22 +0000592 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000593 } //for all requested devices
mpagenkoc26d4c02021-05-06 14:27:57 +0000594 pImageResp := &loResponse
595 return pImageResp, nil
596 }
597 return nil, errors.New("invalid image download parameters")
mpagenko83144272021-04-27 10:06:22 +0000598}
599
khenaidoo7d3c5582021-08-11 18:09:44 -0400600// GetOnuImageStatus delivers the adapter-related information about the download/activation/commitment
mpagenko83144272021-04-27 10:06:22 +0000601// status for the requested image
khenaidoo7d3c5582021-08-11 18:09:44 -0400602func (oo *OpenONUAC) GetOnuImageStatus(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000603 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
604 loResponse := voltha.DeviceImageResponse{}
mpagenkoaa3afe92021-05-21 16:20:58 +0000605 imageIdentifier := (*in).Version
mpagenko38662d02021-08-11 09:45:19 +0000606 var vendorIDSet bool
mpagenkoaa3afe92021-05-21 16:20:58 +0000607 firstDevice := true
608 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000609 var onuVolthaDevice *voltha.Device
610 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000611 for _, pCommonID := range (*in).DeviceId {
612 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400613 pDeviceImageState := &voltha.DeviceImageState{DeviceId: loDeviceID}
mpagenko59862f02021-10-11 08:53:18 +0000614 vendorIDSet = false
615 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400616 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000617 if handler != nil {
618 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
619 } else {
620 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
621 devErr = errors.New("no handler found for device-id")
mpagenko38662d02021-08-11 09:45:19 +0000622 }
mpagenko59862f02021-10-11 08:53:18 +0000623 if devErr != nil || onuVolthaDevice == nil {
mpagenkoaa3afe92021-05-21 16:20:58 +0000624 logger.Warnw(ctx, "Failed to fetch Onu device to get image status",
mpagenko59862f02021-10-11 08:53:18 +0000625 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000626 pImageState := &voltha.ImageState{
627 Version: (*in).Version,
628 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //no statement about last activity possible
629 Reason: voltha.ImageState_UNKNOWN_ERROR, //something like "DEVICE_NOT_EXISTS" would be better (proto def)
630 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
mpagenkoaa3afe92021-05-21 16:20:58 +0000631 }
mpagenko38662d02021-08-11 09:45:19 +0000632 pDeviceImageState.ImageState = pImageState
mpagenkoaa3afe92021-05-21 16:20:58 +0000633 } else {
mpagenko38662d02021-08-11 09:45:19 +0000634 if firstDevice {
635 //start/verify download of the image to the adapter based on first found device only
636 // use the OnuVendor identification from first given device
637 firstDevice = false
638 vendorID = onuVolthaDevice.VendorId
639 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
640 vendorIDSet = true
641 logger.Debugw(ctx, "status request for image", log.Fields{"image-id": imageIdentifier})
642 } else {
643 //for all following devices verify the matching vendorID
644 if onuVolthaDevice.VendorId != vendorID {
645 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
646 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
647 } else {
648 vendorIDSet = true
649 }
650 }
651 if !vendorIDSet {
652 pImageState := &voltha.ImageState{
653 Version: (*in).Version,
654 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //can't be sure that download for this device was really tried
655 Reason: voltha.ImageState_VENDOR_DEVICE_MISMATCH,
656 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
657 }
658 pDeviceImageState.ImageState = pImageState
659 } else {
khenaidoo7d3c5582021-08-11 18:09:44 -0400660 logger.Debugw(ctx, "image status request for", log.Fields{
661 "image-id": imageIdentifier, "device-id": loDeviceID})
662 //status request is called synchronously to collect the indications for all concerned devices
663 pDeviceImageState.ImageState = handler.requestOnuSwUpgradeState(ctx, imageIdentifier, (*in).Version)
mpagenko38662d02021-08-11 09:45:19 +0000664 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000665 }
666 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000667 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000668 pImageResp := &loResponse
669 return pImageResp, nil
670 }
671 return nil, errors.New("invalid image status request parameters")
mpagenko83144272021-04-27 10:06:22 +0000672}
673
khenaidoo7d3c5582021-08-11 18:09:44 -0400674// AbortOnuImageUpgrade stops the actual download/activation/commitment process (on next possibly step)
675func (oo *OpenONUAC) AbortOnuImageUpgrade(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000676 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
677 loResponse := voltha.DeviceImageResponse{}
678 imageIdentifier := (*in).Version
679 firstDevice := true
680 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000681 var vendorIDSet bool
682 var onuVolthaDevice *voltha.Device
683 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000684 for _, pCommonID := range (*in).DeviceId {
685 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400686 pDeviceImageState := &voltha.DeviceImageState{}
687 loImageState := voltha.ImageState{}
688 pDeviceImageState.ImageState = &loImageState
mpagenko59862f02021-10-11 08:53:18 +0000689 vendorIDSet = false
690 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400691 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000692 if handler != nil {
693 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
694 } else {
695 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
696 devErr = errors.New("no handler found for device-id")
697 }
698 if devErr != nil || onuVolthaDevice == nil {
699 logger.Warnw(ctx, "Failed to fetch Onu device to abort its download",
700 log.Fields{"device-id": loDeviceID, "err": devErr})
khenaidoo7d3c5582021-08-11 18:09:44 -0400701 pDeviceImageState.DeviceId = loDeviceID
702 pDeviceImageState.ImageState.Version = (*in).Version
mpagenko59862f02021-10-11 08:53:18 +0000703 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
704 pDeviceImageState.ImageState.Reason = voltha.ImageState_CANCELLED_ON_REQUEST //something better could be considered (MissingHandler) - proto
khenaidoo7d3c5582021-08-11 18:09:44 -0400705 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoaa3afe92021-05-21 16:20:58 +0000706 } else {
mpagenko59862f02021-10-11 08:53:18 +0000707 if firstDevice {
708 //start/verify download of the image to the adapter based on first found device only
709 // use the OnuVendor identification from first given device
710 firstDevice = false
711 vendorID = onuVolthaDevice.VendorId
712 vendorIDSet = true
713 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
714 logger.Debugw(ctx, "abort request for file", log.Fields{"image-id": imageIdentifier})
715 } else {
716 //for all following devices verify the matching vendorID
717 if onuVolthaDevice.VendorId != vendorID {
718 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
719 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
720 pDeviceImageState.DeviceId = loDeviceID
721 pDeviceImageState.ImageState.Version = (*in).Version
722 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
723 pDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
724 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
725 } else {
726 vendorIDSet = true
727 }
728 }
729 if vendorIDSet {
730 // cancel the ONU upgrade activity for each possible device
731 logger.Debugw(ctx, "image upgrade abort requested", log.Fields{
732 "image-id": imageIdentifier, "device-id": loDeviceID})
733 //upgrade cancel is called synchronously to collect the imageResponse indications for all concerned devices
734 handler.cancelOnuSwUpgrade(ctx, imageIdentifier, (*in).Version, pDeviceImageState)
mpagenkoaa3afe92021-05-21 16:20:58 +0000735 }
736 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000737 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000738 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000739 if !firstDevice {
740 //if at least one valid device was found cancel also a possibly running download to adapter and remove the image
741 // this is to be done after the upgradeOnu cancel activities in order to not subduct the file for still running processes
742 oo.pFileManager.CancelDownload(ctx, imageIdentifier)
743 }
744 pImageResp := &loResponse
745 return pImageResp, nil
746 }
747 return nil, errors.New("invalid image upgrade abort parameters")
mpagenko83144272021-04-27 10:06:22 +0000748}
749
khenaidoo7d3c5582021-08-11 18:09:44 -0400750// GetOnuImages retrieves the ONU SW image status information via OMCI
751func (oo *OpenONUAC) GetOnuImages(ctx context.Context, id *common.ID) (*voltha.OnuImages, error) {
752 logger.Infow(ctx, "Get_onu_images", log.Fields{"device-id": id.Id})
753 if handler := oo.getDeviceHandler(ctx, id.Id, false); handler != nil {
Himani Chawla69992ab2021-07-08 15:13:02 +0530754 images, err := handler.getOnuImages(ctx)
755 if err == nil {
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000756 return images, nil
757 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400758 return nil, fmt.Errorf(fmt.Sprintf("%s-%s", err, id.Id))
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000759 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400760 logger.Warnw(ctx, "no handler found for Get_onu_images", log.Fields{"device-id": id.Id})
761 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", id.Id))
mpagenko83144272021-04-27 10:06:22 +0000762}
763
khenaidoo7d3c5582021-08-11 18:09:44 -0400764// ActivateOnuImage initiates the activation of the image for the requested ONU(s)
mpagenkoc26d4c02021-05-06 14:27:57 +0000765// precondition: image downloaded and not yet activated or image refers to current inactive image
khenaidoo7d3c5582021-08-11 18:09:44 -0400766func (oo *OpenONUAC) ActivateOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000767 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
768 loResponse := voltha.DeviceImageResponse{}
769 imageIdentifier := (*in).Version
770 //let the deviceHandler find the adequate way of requesting the image activation
771 for _, pCommonID := range (*in).DeviceId {
772 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000773 loDeviceImageState := voltha.DeviceImageState{}
774 loDeviceImageState.DeviceId = loDeviceID
775 loImageState := voltha.ImageState{}
776 loDeviceImageState.ImageState = &loImageState
777 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000778 //compared to download procedure the vendorID (from device) is secondary here
779 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
780 // start image activation activity for each possible device
781 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
782 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
783 logger.Debugw(ctx, "onu image activation requested", log.Fields{
784 "image-id": imageIdentifier, "device-id": loDeviceID})
785 //onu activation handling called in background without immediate error evaluation here
786 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
787 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000788 if pImageStates, err := handler.onuSwActivateRequest(ctx, imageIdentifier, (*in).CommitOnSuccess); err != nil {
789 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
790 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
791 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
792 } else {
793 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
794 loDeviceImageState.ImageState.Reason = pImageStates.Reason
795 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
796 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000797 } else {
798 //cannot start SW activation for requested device
799 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000800 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000801 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
802 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000803 }
mpagenko2f2f2362021-06-07 08:25:22 +0000804 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000805 }
806 pImageResp := &loResponse
807 return pImageResp, nil
808 }
809 return nil, errors.New("invalid image activation parameters")
mpagenko83144272021-04-27 10:06:22 +0000810}
811
khenaidoo7d3c5582021-08-11 18:09:44 -0400812// CommitOnuImage enforces the commitment of the image for the requested ONU(s)
mpagenko83144272021-04-27 10:06:22 +0000813// precondition: image activated and not yet committed
khenaidoo7d3c5582021-08-11 18:09:44 -0400814func (oo *OpenONUAC) CommitOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000815 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
816 loResponse := voltha.DeviceImageResponse{}
817 imageIdentifier := (*in).Version
818 //let the deviceHandler find the adequate way of requesting the image activation
819 for _, pCommonID := range (*in).DeviceId {
820 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000821 loDeviceImageState := voltha.DeviceImageState{}
822 loDeviceImageState.DeviceId = loDeviceID
823 loImageState := voltha.ImageState{}
824 loDeviceImageState.ImageState = &loImageState
825 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000826 //compared to download procedure the vendorID (from device) is secondary here
827 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
828 // start image activation activity for each possible device
829 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
830 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
831 logger.Debugw(ctx, "onu image commitment requested", log.Fields{
832 "image-id": imageIdentifier, "device-id": loDeviceID})
833 //onu commitment handling called in background without immediate error evaluation here
834 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
835 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000836 if pImageStates, err := handler.onuSwCommitRequest(ctx, imageIdentifier); err != nil {
mpagenko38662d02021-08-11 09:45:19 +0000837 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
838 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //can be multiple reasons here
mpagenko183647c2021-06-08 15:25:04 +0000839 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
840 } else {
841 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
842 loDeviceImageState.ImageState.Reason = pImageStates.Reason
843 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
844 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000845 } else {
846 //cannot start SW commitment for requested device
847 logger.Warnw(ctx, "no handler found for image commitment", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000848 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000849 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
850 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000851 }
mpagenko2f2f2362021-06-07 08:25:22 +0000852 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000853 }
854 pImageResp := &loResponse
855 return pImageResp, nil
856 }
857 return nil, errors.New("invalid image commitment parameters")
mpagenko83144272021-04-27 10:06:22 +0000858}
859
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000860// Adapter interface required methods ################ end #########
861// #################################################################
khenaidoo7d3c5582021-08-11 18:09:44 -0400862
863/*
864 *
865 * ONU inter adapter service
866 *
867 */
868
869// OnuIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400870func (oo *OpenONUAC) OnuIndication(ctx context.Context, onuInd *ia.OnuIndicationMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400871 logger.Debugw(ctx, "onu-indication", log.Fields{"onu-indication": onuInd})
872
873 if onuInd == nil || onuInd.OnuIndication == nil {
874 return nil, fmt.Errorf("invalid-onu-indication-%v", onuInd)
875 }
876
877 onuIndication := onuInd.OnuIndication
878 onuOperstate := onuIndication.GetOperState()
879 waitForDhInstPresent := false
880 if onuOperstate == "up" {
881 //Race condition (relevant in BBSIM-environment only): Due to unsynchronized processing of olt-adapter and rw_core,
882 //ONU_IND_REQUEST msg by olt-adapter could arrive a little bit earlier than rw_core was able to announce the corresponding
883 //ONU by RPC of Adopt_device(). Therefore it could be necessary to wait with processing of ONU_IND_REQUEST until call of
884 //Adopt_device() arrived and DeviceHandler instance was created
885 waitForDhInstPresent = true
886 }
887 if handler := oo.getDeviceHandler(ctx, onuInd.DeviceId, waitForDhInstPresent); handler != nil {
888 logger.Infow(ctx, "onu-ind-request", log.Fields{"device-id": onuInd.DeviceId,
889 "OnuId": onuIndication.GetOnuId(),
890 "AdminState": onuIndication.GetAdminState(), "OperState": onuOperstate,
891 "SNR": onuIndication.GetSerialNumber()})
892
893 if onuOperstate == "up" {
894 if err := handler.createInterface(ctx, onuIndication); err != nil {
895 return nil, err
896 }
897 return &empty.Empty{}, nil
898 } else if (onuOperstate == "down") || (onuOperstate == "unreachable") {
899 return nil, handler.updateInterface(ctx, onuIndication)
900 } else {
901 logger.Errorw(ctx, "unknown-onu-ind-request operState", log.Fields{"OnuId": onuIndication.GetOnuId()})
902 return nil, fmt.Errorf("invalidOperState: %s, %s", onuOperstate, onuInd.DeviceId)
903 }
904 }
905 logger.Warnw(ctx, "no handler found for received onu-ind-request", log.Fields{
906 "msgToDeviceId": onuInd.DeviceId})
907 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", onuInd.DeviceId))
908}
909
910// OmciIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400911func (oo *OpenONUAC) OmciIndication(ctx context.Context, msg *ia.OmciMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400912 logger.Debugw(ctx, "omci-response", log.Fields{"parent-device-id": msg.ParentDeviceId, "child-device-id": msg.ChildDeviceId})
913
914 if handler := oo.getDeviceHandler(ctx, msg.ChildDeviceId, false); handler != nil {
915 if err := handler.handleOMCIIndication(log.WithSpanFromContext(context.Background(), ctx), msg); err != nil {
916 return nil, err
917 }
918 return &empty.Empty{}, nil
919 }
920 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", msg.ChildDeviceId))
921}
922
923// DownloadTechProfile is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400924func (oo *OpenONUAC) DownloadTechProfile(ctx context.Context, tProfile *ia.TechProfileDownloadMessage) (*empty.Empty, error) {
Holger Hildebrandtba6fbe82021-12-03 14:29:42 +0000925 logger.Debugw(ctx, "download-tech-profile", log.Fields{"device-id": tProfile.DeviceId, "uni-id": tProfile.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400926
927 if handler := oo.getDeviceHandler(ctx, tProfile.DeviceId, false); handler != nil {
928 if err := handler.handleTechProfileDownloadRequest(log.WithSpanFromContext(context.Background(), ctx), tProfile); err != nil {
929 return nil, err
930 }
931 return &empty.Empty{}, nil
932 }
933 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", tProfile.DeviceId))
934}
935
936// DeleteGemPort is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400937func (oo *OpenONUAC) DeleteGemPort(ctx context.Context, gPort *ia.DeleteGemPortMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400938 logger.Debugw(ctx, "delete-gem-port", log.Fields{"device-id": gPort.DeviceId, "uni-id": gPort.UniId})
939
940 if handler := oo.getDeviceHandler(ctx, gPort.DeviceId, false); handler != nil {
941 if err := handler.handleDeleteGemPortRequest(log.WithSpanFromContext(context.Background(), ctx), gPort); err != nil {
942 return nil, err
943 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000944 } else {
945 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": gPort.DeviceId})
946 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400947 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000948 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400949}
950
951// DeleteTCont is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400952func (oo *OpenONUAC) DeleteTCont(ctx context.Context, tConf *ia.DeleteTcontMessage) (*empty.Empty, error) {
Holger Hildebrandtba6fbe82021-12-03 14:29:42 +0000953 logger.Debugw(ctx, "delete-tcont", log.Fields{"device-id": tConf.DeviceId, "tconf": tConf})
khenaidoo7d3c5582021-08-11 18:09:44 -0400954
955 if handler := oo.getDeviceHandler(ctx, tConf.DeviceId, false); handler != nil {
956 if err := handler.handleDeleteTcontRequest(log.WithSpanFromContext(context.Background(), ctx), tConf); err != nil {
957 return nil, err
958 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000959 } else {
960 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": tConf.DeviceId})
961 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400962 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000963 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400964}
965
966/*
967 * Parent GRPC clients
968 */
969
khenaidoo55cebc62021-12-08 14:44:41 -0500970func getHash(endpoint, contextInfo string) string {
971 strToHash := endpoint + contextInfo
972 h := fnv.New128().Sum([]byte(strToHash))
973 return string(h)
974}
975
976func (oo *OpenONUAC) updateReachabilityFromRemote(ctx context.Context, remote *common.Connection) {
977 logger.Debugw(context.Background(), "updating-remote-connection-status", log.Fields{"remote": remote})
978 oo.lockReachableFromRemote.Lock()
979 defer oo.lockReachableFromRemote.Unlock()
980 endpointHash := getHash(remote.Endpoint, remote.ContextInfo)
981 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
982 oo.reachableFromRemote[endpointHash].lastKeepAlive = time.Now()
983 oo.reachableFromRemote[endpointHash].keepAliveInterval = remote.KeepAliveInterval
984 return
985 }
986 logger.Debugw(context.Background(), "initial-remote-connection", log.Fields{"remote": remote})
987 oo.reachableFromRemote[endpointHash] = &reachabilityFromRemote{lastKeepAlive: time.Now(), keepAliveInterval: remote.KeepAliveInterval}
988}
989
990func (oo *OpenONUAC) isReachableFromRemote(endpoint string, contextInfo string) bool {
991 oo.lockReachableFromRemote.RLock()
992 defer oo.lockReachableFromRemote.RUnlock()
993 endpointHash := getHash(endpoint, contextInfo)
994 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
995 // Assume the connection is down if we did not receive 2 keep alives in succession
996 maxKeepAliveWait := time.Duration(oo.reachableFromRemote[endpointHash].keepAliveInterval * 2)
997 return time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive) <= maxKeepAliveWait
998 }
999 return false
1000}
1001
khenaidoo7d3c5582021-08-11 18:09:44 -04001002func (oo *OpenONUAC) setupParentInterAdapterClient(ctx context.Context, endpoint string) error {
1003 logger.Infow(ctx, "setting-parent-adapter-connection", log.Fields{"parent-endpoint": endpoint})
1004 oo.lockParentAdapterClients.Lock()
1005 defer oo.lockParentAdapterClients.Unlock()
1006 if _, ok := oo.parentAdapterClients[endpoint]; ok {
1007 return nil
1008 }
1009
khenaidoo55cebc62021-12-08 14:44:41 -05001010 childClient, err := vgrpc.NewClient(
1011 oo.config.AdapterEndpoint,
1012 endpoint,
1013 oo.oltAdapterRestarted)
khenaidoo7d3c5582021-08-11 18:09:44 -04001014
1015 if err != nil {
1016 return err
1017 }
1018
1019 oo.parentAdapterClients[endpoint] = childClient
1020
khenaidoo55cebc62021-12-08 14:44:41 -05001021 go oo.parentAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), setAndTestOltInterAdapterServiceHandler)
khenaidoo7d3c5582021-08-11 18:09:44 -04001022
1023 // Wait until we have a connection to the child adapter.
1024 // Unlimited retries or until context expires
1025 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
1026 backoff := vgrpc.NewBackoff(oo.config.MinBackoffRetryDelay, oo.config.MaxBackoffRetryDelay, 0)
1027 for {
1028 client, err := oo.parentAdapterClients[endpoint].GetOltInterAdapterServiceClient()
1029 if err == nil && client != nil {
1030 logger.Infow(subCtx, "connected-to-parent-adapter", log.Fields{"parent-endpoint": endpoint})
1031 break
1032 }
1033 logger.Warnw(subCtx, "connection-to-parent-adapter-not-ready", log.Fields{"error": err, "parent-endpoint": endpoint})
1034 // Backoff
1035 if err = backoff.Backoff(subCtx); err != nil {
1036 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "parent-endpoint": endpoint})
1037 break
1038 }
1039 }
1040 return nil
1041}
1042
khenaidoo42dcdfd2021-10-19 17:34:12 -04001043func (oo *OpenONUAC) getParentAdapterServiceClient(endpoint string) (olt_inter_adapter_service.OltInterAdapterServiceClient, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001044 // First check from cache
1045 oo.lockParentAdapterClients.RLock()
1046 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1047 oo.lockParentAdapterClients.RUnlock()
1048 return pgClient.GetOltInterAdapterServiceClient()
1049 }
1050 oo.lockParentAdapterClients.RUnlock()
1051
1052 // Set the parent connection - can occur on restarts
1053 ctx, cancel := context.WithTimeout(context.Background(), oo.config.RPCTimeout)
1054 err := oo.setupParentInterAdapterClient(ctx, endpoint)
1055 cancel()
1056 if err != nil {
1057 return nil, err
1058 }
1059
1060 // Get the parent client now
1061 oo.lockParentAdapterClients.RLock()
1062 defer oo.lockParentAdapterClients.RUnlock()
1063 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1064 return pgClient.GetOltInterAdapterServiceClient()
1065 }
1066
1067 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
1068}
1069
1070// TODO: Any action the adapter needs to do following an olt adapter restart?
1071func (oo *OpenONUAC) oltAdapterRestarted(ctx context.Context, endPoint string) error {
1072 logger.Errorw(ctx, "olt-adapter-restarted", log.Fields{"endpoint": endPoint})
1073 return nil
1074}
1075
khenaidoo55cebc62021-12-08 14:44:41 -05001076// setAndTestOltInterAdapterServiceHandler is used to test whether the remote gRPC service is up
1077func setAndTestOltInterAdapterServiceHandler(ctx context.Context, conn *grpc.ClientConn, clientConn *common.Connection) interface{} {
khenaidoo42dcdfd2021-10-19 17:34:12 -04001078 svc := olt_inter_adapter_service.NewOltInterAdapterServiceClient(conn)
khenaidoo55cebc62021-12-08 14:44:41 -05001079 if h, err := svc.GetHealthStatus(ctx, clientConn); err != nil || h.State != health.HealthStatus_HEALTHY {
khenaidoo7d3c5582021-08-11 18:09:44 -04001080 return nil
1081 }
1082 return svc
1083}
1084
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001085func (oo *OpenONUAC) forceDeleteDeviceKvData(ctx context.Context, aDeviceID string) error {
1086 logger.Debugw(ctx, "force deletion of ONU device specific data in kv store", log.Fields{"device-id": aDeviceID})
1087
1088 for i := range onuKvStorePathPrefixes {
1089 baseKvStorePath := fmt.Sprintf(onuKvStorePathPrefixes[i], oo.cm.Backend.PathPrefix)
1090 logger.Debugw(ctx, "SetKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": baseKvStorePath,
1091 "device-id": aDeviceID})
1092 kvbackend := &db.Backend{
1093 Client: oo.kvClient,
1094 StoreType: oo.KVStoreType,
1095 Address: oo.KVStoreAddress,
1096 Timeout: oo.KVStoreTimeout,
1097 PathPrefix: baseKvStorePath}
1098
1099 if kvbackend == nil {
1100 logger.Errorw(ctx, "Can't access onuKVStore - no backend connection to service", log.Fields{"service": baseKvStorePath, "device-id": aDeviceID})
1101 return fmt.Errorf("can-not-access-onuKVStore-no-backend-connection-to-service")
1102 }
1103 err := kvbackend.DeleteWithPrefix(ctx, aDeviceID)
1104 if err != nil {
1105 logger.Errorw(ctx, "unable to delete in KVstore", log.Fields{"service": baseKvStorePath, "device-id": aDeviceID, "err": err})
1106 return fmt.Errorf("unable-to-delete-in-KVstore")
1107 }
1108 }
1109 return nil
1110}
1111
khenaidoo7d3c5582021-08-11 18:09:44 -04001112/*
1113 *
1114 * Unimplemented APIs
1115 *
1116 */
1117
1118//GetOfpDeviceInfo returns OFP information for the given device. Method not implemented as per [VOL-3202].
1119// OF port info is now to be delivered within UniPort create cmp changes in onu_uni_port.go::CreateVolthaPort()
1120//
khenaidoo42dcdfd2021-10-19 17:34:12 -04001121func (oo *OpenONUAC) GetOfpDeviceInfo(ctx context.Context, device *voltha.Device) (*ca.SwitchCapability, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001122 return nil, errors.New("unImplemented")
1123}
1124
1125//SimulateAlarm is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001126func (oo *OpenONUAC) SimulateAlarm(context.Context, *ca.SimulateAlarmMessage) (*common.OperationResp, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001127 return nil, errors.New("unImplemented")
1128}
1129
1130//SetExtValue is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001131func (oo *OpenONUAC) SetExtValue(context.Context, *ca.SetExtValueMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001132 return nil, errors.New("unImplemented")
1133}
1134
1135//SetSingleValue is unimplemented
1136func (oo *OpenONUAC) SetSingleValue(context.Context, *extension.SingleSetValueRequest) (*extension.SingleSetValueResponse, error) {
1137 return nil, errors.New("unImplemented")
1138}
1139
1140//StartOmciTest not implemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001141func (oo *OpenONUAC) StartOmciTest(ctx context.Context, test *ca.OMCITest) (*omci.TestResponse, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001142 return nil, errors.New("unImplemented")
1143}
1144
1145//SuppressEvent unimplemented
1146func (oo *OpenONUAC) SuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1147 return nil, errors.New("unImplemented")
1148}
1149
1150//UnSuppressEvent unimplemented
1151func (oo *OpenONUAC) UnSuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1152 return nil, errors.New("unImplemented")
1153}
1154
1155//GetImageDownloadStatus is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001156func (oo *OpenONUAC) GetImageDownloadStatus(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001157 return nil, errors.New("unImplemented")
1158}
1159
1160//CancelImageDownload is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001161func (oo *OpenONUAC) CancelImageDownload(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001162 return nil, errors.New("unImplemented")
1163}
1164
1165//RevertImageUpdate is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001166func (oo *OpenONUAC) RevertImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001167 return nil, errors.New("unImplemented")
1168}
1169
1170// UpdateFlowsBulk is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001171func (oo *OpenONUAC) UpdateFlowsBulk(ctx context.Context, flows *ca.BulkFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001172 return nil, errors.New("unImplemented")
1173}
1174
1175//SelfTestDevice unimplented
1176func (oo *OpenONUAC) SelfTestDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
1177 return nil, errors.New("unImplemented")
1178}
1179
1180//SendPacketOut sends packet out to the device
khenaidoo42dcdfd2021-10-19 17:34:12 -04001181func (oo *OpenONUAC) SendPacketOut(ctx context.Context, packet *ca.PacketOut) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001182 return nil, errors.New("unImplemented")
1183}
1184
1185// EnablePort to Enable PON/NNI interface - seems not to be used/required according to python code
1186func (oo *OpenONUAC) EnablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1187 return nil, errors.New("unImplemented")
1188}
1189
1190// DisablePort to Disable pon/nni interface - seems not to be used/required according to python code
1191func (oo *OpenONUAC) DisablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1192 return nil, errors.New("unImplemented")
1193}
1194
1195// GetExtValue - unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001196func (oo *OpenONUAC) GetExtValue(ctx context.Context, extInfo *ca.GetExtValueMessage) (*extension.ReturnValues, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001197 return nil, errors.New("unImplemented")
1198}
1199
1200// ChildDeviceLost - unimplemented
1201func (oo *OpenONUAC) ChildDeviceLost(ctx context.Context, childDevice *voltha.Device) (*empty.Empty, error) {
1202 return nil, errors.New("unImplemented")
1203}
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +00001204
1205// GetSupportedFsms - TODO: add comment
1206func (oo *OpenONUAC) GetSupportedFsms() *cmn.OmciDeviceFsms {
1207 return oo.pSupportedFsms
1208}
1209
1210// LockMutexMibTemplateGenerated - TODO: add comment
1211func (oo *OpenONUAC) LockMutexMibTemplateGenerated() {
1212 oo.mutexMibTemplateGenerated.Lock()
1213}
1214
1215// UnlockMutexMibTemplateGenerated - TODO: add comment
1216func (oo *OpenONUAC) UnlockMutexMibTemplateGenerated() {
1217 oo.mutexMibTemplateGenerated.Unlock()
1218}
1219
1220// GetMibTemplatesGenerated - TODO: add comment
1221func (oo *OpenONUAC) GetMibTemplatesGenerated(mibTemplatePath string) (value bool, exist bool) {
1222 value, exist = oo.mibTemplatesGenerated[mibTemplatePath]
1223 return value, exist
1224}
1225
1226// SetMibTemplatesGenerated - TODO: add comment
1227func (oo *OpenONUAC) SetMibTemplatesGenerated(mibTemplatePath string, value bool) {
1228 oo.mibTemplatesGenerated[mibTemplatePath] = value
1229}
1230
1231// RLockMutexDeviceHandlersMap - TODO: add comment
1232func (oo *OpenONUAC) RLockMutexDeviceHandlersMap() {
1233 oo.mutexDeviceHandlersMap.RLock()
1234}
1235
1236// RUnlockMutexDeviceHandlersMap - TODO: add comment
1237func (oo *OpenONUAC) RUnlockMutexDeviceHandlersMap() {
1238 oo.mutexDeviceHandlersMap.RUnlock()
1239}
1240
1241// GetDeviceHandler - TODO: add comment
1242func (oo *OpenONUAC) GetDeviceHandler(deviceID string) (value cmn.IdeviceHandler, exist bool) {
1243 value, exist = oo.deviceHandlers[deviceID]
1244 return value, exist
1245}