blob: 445257a8119a6a290393b2f5bd7ac172aecc6272 [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001/*
Joey Armstrong89c812c2024-01-12 19:00:20 -05002 * Copyright 2020-2024 Open Networking Foundation (ONF) and the ONF Contributors
Holger Hildebrandtfa074992020-03-27 15:42:06 +00003 *
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
praneeth nalmas5a0a5502022-12-23 15:57:00 +053017// Package core provides the utility for onu devices, flows and statistics
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000018package 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 Hildebrandt52f271b2022-06-02 09:32:27 +000025 "strings"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000026 "sync"
27 "time"
28
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +053029 grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
30 "github.com/opencord/voltha-lib-go/v7/pkg/db"
31 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
32 codes "google.golang.org/grpc/codes"
33
khenaidoo7d3c5582021-08-11 18:09:44 -040034 conf "github.com/opencord/voltha-lib-go/v7/pkg/config"
khenaidoof3333552021-12-15 16:52:31 -050035 "github.com/opencord/voltha-protos/v5/go/adapter_service"
khenaidoo7d3c5582021-08-11 18:09:44 -040036 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoo42dcdfd2021-10-19 17:34:12 -040037 "github.com/opencord/voltha-protos/v5/go/health"
38 "github.com/opencord/voltha-protos/v5/go/olt_inter_adapter_service"
khenaidoo7d3c5582021-08-11 18:09:44 -040039 "google.golang.org/grpc"
khenaidoo55cebc62021-12-08 14:44:41 -050040 "google.golang.org/grpc/status"
khenaidoo7d3c5582021-08-11 18:09:44 -040041
42 "github.com/golang/protobuf/ptypes/empty"
43 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
44 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
45 "github.com/opencord/voltha-lib-go/v7/pkg/log"
khenaidoo42dcdfd2021-10-19 17:34:12 -040046 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo7d3c5582021-08-11 18:09:44 -040047 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoo42dcdfd2021-10-19 17:34:12 -040048 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
49 "github.com/opencord/voltha-protos/v5/go/omci"
khenaidoo7d3c5582021-08-11 18:09:44 -040050 "github.com/opencord/voltha-protos/v5/go/voltha"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000051
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000052 cmn "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/common"
Matteo Scandolo761f7512020-11-23 15:52:40 -080053 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/config"
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +053054 devdb "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/devdb"
Holger Hildebrandt60652202021-11-02 11:09:36 +000055 pmmgr "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/pmmgr"
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000056 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/swupg"
57 uniprt "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/uniprt"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000058)
59
khenaidoo55cebc62021-12-08 14:44:41 -050060type reachabilityFromRemote struct {
61 lastKeepAlive time.Time
62 keepAliveInterval int64
63}
64
praneeth nalmas5a0a5502022-12-23 15:57:00 +053065// OpenONUAC structure holds the ONU core information
Holger Hildebrandtfa074992020-03-27 15:42:06 +000066type OpenONUAC struct {
Himani Chawla6d2ae152020-09-02 13:11:20 +053067 deviceHandlers map[string]*deviceHandler
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +000068 deviceHandlersCreateChan map[string]chan bool //channels for deviceHandler create events
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000069 mutexDeviceHandlersMap sync.RWMutex
khenaidoo7d3c5582021-08-11 18:09:44 -040070 coreClient *vgrpc.Client
71 parentAdapterClients map[string]*vgrpc.Client
72 lockParentAdapterClients sync.RWMutex
khenaidoo55cebc62021-12-08 14:44:41 -050073 reachableFromRemote map[string]*reachabilityFromRemote
74 lockReachableFromRemote sync.RWMutex
Himani Chawlac07fda02020-12-09 16:21:21 +053075 eventProxy eventif.EventProxy
mpagenkoaf801632020-07-03 10:00:42 +000076 kvClient kvstore.Client
Matteo Scandolof1f39a72020-11-24 12:08:11 -080077 cm *conf.ConfigManager
Holger Hildebrandtfa074992020-03-27 15:42:06 +000078 config *config.AdapterFlags
79 numOnus int
Matteo Scandolo127c59d2021-01-28 11:31:18 -080080 KVStoreAddress string
Holger Hildebrandtfa074992020-03-27 15:42:06 +000081 KVStoreType string
mpagenkoaf801632020-07-03 10:00:42 +000082 KVStoreTimeout time.Duration
Holger Hildebrandt61b24d02020-11-16 13:36:40 +000083 mibTemplatesGenerated map[string]bool
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000084 mutexMibTemplateGenerated sync.RWMutex
Holger Hildebrandtfa074992020-03-27 15:42:06 +000085 exitChannel chan int
86 HeartbeatCheckInterval time.Duration
87 HeartbeatFailReportInterval time.Duration
mpagenkodff5dda2020-08-28 11:52:01 +000088 AcceptIncrementalEvto bool
khenaidoo55cebc62021-12-08 14:44:41 -050089 pSupportedFsms *cmn.OmciDeviceFsms
90 maxTimeoutInterAdapterComm time.Duration
91 maxTimeoutReconciling time.Duration
92 pDownloadManager *swupg.AdapterDownloadManager
93 pFileManager *swupg.FileDownloadManager //let coexist 'old and new' DownloadManager as long as 'old' does not get obsolete
94 MetricsEnabled bool
Holger Hildebrandtc572e622022-06-22 09:19:17 +000095 ExtendedOmciSupportEnabled bool
khenaidoo55cebc62021-12-08 14:44:41 -050096 mibAuditInterval time.Duration
97 omciTimeout int // in seconds
98 alarmAuditInterval time.Duration
99 dlToOnuTimeout4M time.Duration
100 rpcTimeout time.Duration
101 maxConcurrentFlowsPerUni int
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530102 skipOnuConfig bool
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +0530103 mutexMibDatabaseMap sync.RWMutex
104 MibDatabaseMap devdb.OnuMCmnMEDBMap
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000105}
106
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530107// NewOpenONUAC returns a new instance of OpenONU_AC
khenaidoo7d3c5582021-08-11 18:09:44 -0400108func NewOpenONUAC(ctx context.Context, coreClient *vgrpc.Client, eventProxy eventif.EventProxy,
109 kvClient kvstore.Client, cfg *config.AdapterFlags, cm *conf.ConfigManager) *OpenONUAC {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000110 var openOnuAc OpenONUAC
111 openOnuAc.exitChannel = make(chan int, 1)
Himani Chawla6d2ae152020-09-02 13:11:20 +0530112 openOnuAc.deviceHandlers = make(map[string]*deviceHandler)
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000113 openOnuAc.deviceHandlersCreateChan = make(map[string]chan bool)
khenaidoo7d3c5582021-08-11 18:09:44 -0400114 openOnuAc.parentAdapterClients = make(map[string]*vgrpc.Client)
khenaidoo55cebc62021-12-08 14:44:41 -0500115 openOnuAc.reachableFromRemote = make(map[string]*reachabilityFromRemote)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000116 openOnuAc.mutexDeviceHandlersMap = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000117 openOnuAc.config = cfg
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800118 openOnuAc.cm = cm
khenaidoo7d3c5582021-08-11 18:09:44 -0400119 openOnuAc.coreClient = coreClient
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000120 openOnuAc.numOnus = cfg.OnuNumber
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000121 openOnuAc.eventProxy = eventProxy
mpagenkoaf801632020-07-03 10:00:42 +0000122 openOnuAc.kvClient = kvClient
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800123 openOnuAc.KVStoreAddress = cfg.KVStoreAddress
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000124 openOnuAc.KVStoreType = cfg.KVStoreType
mpagenkoaf801632020-07-03 10:00:42 +0000125 openOnuAc.KVStoreTimeout = cfg.KVStoreTimeout
Holger Hildebrandt61b24d02020-11-16 13:36:40 +0000126 openOnuAc.mibTemplatesGenerated = make(map[string]bool)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000127 openOnuAc.mutexMibTemplateGenerated = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000128 openOnuAc.HeartbeatCheckInterval = cfg.HeartbeatCheckInterval
129 openOnuAc.HeartbeatFailReportInterval = cfg.HeartbeatFailReportInterval
mpagenkodff5dda2020-08-28 11:52:01 +0000130 openOnuAc.AcceptIncrementalEvto = cfg.AccIncrEvto
Himani Chawlad96df182020-09-28 11:12:02 +0530131 openOnuAc.maxTimeoutInterAdapterComm = cfg.MaxTimeoutInterAdapterComm
Holger Hildebrandt38985dc2021-02-18 16:25:20 +0000132 openOnuAc.maxTimeoutReconciling = cfg.MaxTimeoutReconciling
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000133 //openOnuAc.GrpcTimeoutInterval = cfg.GrpcTimeoutInterval
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000134 openOnuAc.MetricsEnabled = cfg.MetricsEnabled
Holger Hildebrandtc572e622022-06-22 09:19:17 +0000135 openOnuAc.ExtendedOmciSupportEnabled = cfg.ExtendedOmciSupportEnabled
Holger Hildebrandte3677f12021-02-05 14:50:56 +0000136 openOnuAc.mibAuditInterval = cfg.MibAuditInterval
Girish Gowdra0b235842021-03-09 13:06:46 -0800137 // since consumers of OMCI timeout value everywhere in code is in "int seconds", do this useful conversion
138 openOnuAc.omciTimeout = int(cfg.OmciTimeout.Seconds())
Himani Chawla075f1642021-03-15 19:23:24 +0530139 openOnuAc.alarmAuditInterval = cfg.AlarmAuditInterval
mpagenkoc26d4c02021-05-06 14:27:57 +0000140 openOnuAc.dlToOnuTimeout4M = cfg.DownloadToOnuTimeout4MB
khenaidoo7d3c5582021-08-11 18:09:44 -0400141 openOnuAc.rpcTimeout = cfg.RPCTimeout
Girish Gowdrae95687a2021-09-08 16:30:58 -0700142 openOnuAc.maxConcurrentFlowsPerUni = cfg.MaxConcurrentFlowsPerUni
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000143
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000144 openOnuAc.pSupportedFsms = &cmn.OmciDeviceFsms{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000145 "mib-synchronizer": {
146 //mibSyncFsm, // Implements the MIB synchronization state machine
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000147 DatabaseClass: mibDbVolatileDictImpl, // Implements volatile ME MIB database
Himani Chawla4d908332020-08-31 12:30:20 +0530148 //true, // Advertise events on OpenOMCI event bus
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000149 AuditInterval: openOnuAc.mibAuditInterval, // Time to wait between MIB audits. 0 to disable audits.
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000150 // map[string]func() error{
151 // "mib-upload": onuDeviceEntry.MibUploadTask,
152 // "mib-template": onuDeviceEntry.MibTemplateTask,
153 // "get-mds": onuDeviceEntry.GetMdsTask,
154 // "mib-audit": onuDeviceEntry.GetMdsTask,
155 // "mib-resync": onuDeviceEntry.MibResyncTask,
156 // "mib-reconcile": onuDeviceEntry.MibReconcileTask,
157 // },
158 },
159 }
160
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000161 openOnuAc.pDownloadManager = swupg.NewAdapterDownloadManager(ctx)
162 openOnuAc.pFileManager = swupg.NewFileDownloadManager(ctx)
mpagenkoc26d4c02021-05-06 14:27:57 +0000163 openOnuAc.pFileManager.SetDownloadTimeout(ctx, cfg.DownloadToAdapterTimeout)
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530164 openOnuAc.skipOnuConfig = cfg.SkipOnuConfig
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +0530165 openOnuAc.mutexMibDatabaseMap = sync.RWMutex{}
166 openOnuAc.MibDatabaseMap = make(map[string]*devdb.OnuCmnMEDB)
mpagenkoc8bba412021-01-15 15:38:44 +0000167
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000168 return &openOnuAc
169}
170
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530171// Start starts (logs) the adapter
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000172func (oo *OpenONUAC) Start(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000173 logger.Info(ctx, "starting-openonu-adapter")
mpagenkoc8bba412021-01-15 15:38:44 +0000174
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000175 return nil
176}
177
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530178// Stop terminates the session
khenaidoof3333552021-12-15 16:52:31 -0500179func (oo *OpenONUAC) Stop(ctx context.Context) error {
180 logger.Info(ctx, "stopping-device-manager")
181 close(oo.exitChannel)
182 oo.stopAllGrpcClients(ctx)
183 logger.Info(ctx, "device-manager-stopped")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000184 return nil
185}
186
Himani Chawla6d2ae152020-09-02 13:11:20 +0530187func (oo *OpenONUAC) addDeviceHandlerToMap(ctx context.Context, agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000188 oo.mutexDeviceHandlersMap.Lock()
189 defer oo.mutexDeviceHandlersMap.Unlock()
190 if _, exist := oo.deviceHandlers[agent.DeviceID]; !exist {
191 oo.deviceHandlers[agent.DeviceID] = agent
192 oo.deviceHandlers[agent.DeviceID].start(ctx)
193 if _, exist := oo.deviceHandlersCreateChan[agent.DeviceID]; exist {
194 logger.Debugw(ctx, "deviceHandler created - trigger processing of pending ONU_IND_REQUEST", log.Fields{"device-id": agent.DeviceID})
195 oo.deviceHandlersCreateChan[agent.DeviceID] <- true
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000196 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000197 }
198}
199
Himani Chawla6d2ae152020-09-02 13:11:20 +0530200func (oo *OpenONUAC) deleteDeviceHandlerToMap(agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000201 oo.mutexDeviceHandlersMap.Lock()
202 defer oo.mutexDeviceHandlersMap.Unlock()
203 delete(oo.deviceHandlers, agent.DeviceID)
204 delete(oo.deviceHandlersCreateChan, agent.DeviceID)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000205}
206
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530207// getDeviceHandler gets the ONU deviceHandler and may wait until it is created
dbainbri4d3a0dc2020-12-02 00:33:42 +0000208func (oo *OpenONUAC) getDeviceHandler(ctx context.Context, deviceID string, aWait bool) *deviceHandler {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000209 oo.mutexDeviceHandlersMap.Lock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000210 agent, ok := oo.deviceHandlers[deviceID]
211 if aWait && !ok {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000212 logger.Infow(ctx, "Race condition: deviceHandler not present - wait for creation or timeout",
Holger Hildebrandt6c1fb0a2020-11-25 15:41:01 +0000213 log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000214 if _, exist := oo.deviceHandlersCreateChan[deviceID]; !exist {
215 oo.deviceHandlersCreateChan[deviceID] = make(chan bool, 1)
216 }
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800217 deviceCreateChan := oo.deviceHandlersCreateChan[deviceID]
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000218 //keep the read sema short to allow for subsequent write
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000219 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000220 // based on concurrent processing the deviceHandler creation may not yet be finished at his point
221 // so it might be needed to wait here for that event with some timeout
222 select {
Akash Soni71f44762024-12-11 16:12:21 +0530223 case <-time.After(20 * time.Second): //timer may be discussed ...
dbainbri4d3a0dc2020-12-02 00:33:42 +0000224 logger.Warnw(ctx, "No valid deviceHandler created after max WaitTime", log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000225 return nil
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800226 case <-deviceCreateChan:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000227 logger.Debugw(ctx, "deviceHandler is ready now - continue", log.Fields{"device-id": deviceID})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000228 oo.mutexDeviceHandlersMap.RLock()
229 defer oo.mutexDeviceHandlersMap.RUnlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000230 return oo.deviceHandlers[deviceID]
231 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000232 }
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000233 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000234 return agent
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000235}
236
khenaidoo7d3c5582021-08-11 18:09:44 -0400237// AdoptDevice creates a new device handler if not present already and then adopts the device
238func (oo *OpenONUAC) AdoptDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000239 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000240 logger.Warn(ctx, "voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400241 return nil, errors.New("nil-device")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000242 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000243 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id})
Himani Chawla6d2ae152020-09-02 13:11:20 +0530244 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000245 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400246 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000247 oo.addDeviceHandlerToMap(ctx, handler)
khenaidoo7d3c5582021-08-11 18:09:44 -0400248
249 // Setup the grpc communication with the parent adapter
250 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
251 // TODO: Cleanup on failure needed
252 return nil, err
253 }
254
255 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), device)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000256 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400257 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000258}
259
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530260// ReconcileDevice is called once when the adapter needs to re-create device - usually on core restart
khenaidoo7d3c5582021-08-11 18:09:44 -0400261func (oo *OpenONUAC) ReconcileDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000262 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000263 logger.Warn(ctx, "reconcile-device-voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400264 return nil, errors.New("nil-device")
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000265 }
khenaidoo55cebc62021-12-08 14:44:41 -0500266 logger.Infow(ctx, "reconcile-device", log.Fields{"device-id": device.Id, "parent-id": device.ParentId})
267
268 // Check whether the grpc client in the adapter of the parent device can reach us yet
khenaidoof3333552021-12-15 16:52:31 -0500269 if !oo.isReachableFromRemote(ctx, device.ProxyAddress.AdapterEndpoint, device.ProxyAddress.DeviceId) {
khenaidoo55cebc62021-12-08 14:44:41 -0500270 return nil, status.Errorf(codes.Unavailable, "adapter-not-reachable-from-parent-%s", device.ProxyAddress.AdapterEndpoint)
271 }
272
Himani Chawla6d2ae152020-09-02 13:11:20 +0530273 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000274 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400275 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530276 logger.Infow(ctx, "reconciling-device skip-onu-config value ", log.Fields{"device-id": device.Id, "parent-id": device.ParentId, "skip-onu-config": oo.skipOnuConfig})
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000277 oo.addDeviceHandlerToMap(ctx, handler)
278 handler.device = device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400279 if err := handler.updateDeviceStateInCore(log.WithSpanFromContext(context.Background(), ctx), &ca.DeviceStateFilter{
khenaidoo7d3c5582021-08-11 18:09:44 -0400280 DeviceId: device.Id,
281 OperStatus: voltha.OperStatus_RECONCILING,
282 ConnStatus: device.ConnectStatus,
283 }); err != nil {
284 return nil, fmt.Errorf("not able to update device state to reconciling. Err : %s", err.Error())
Maninderb5187552021-03-23 22:23:42 +0530285 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400286 // Setup the grpc communication with the parent adapter
287 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
288 // TODO: Cleanup on failure needed
289 return nil, err
290 }
291
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000292 handler.StartReconciling(log.WithSpanFromContext(context.Background(), ctx), false)
khenaidoo7d3c5582021-08-11 18:09:44 -0400293 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), handler.device)
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000294 // reconcilement will be continued after onu-device entry is added
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000295 } else {
nikesh.krishnan9d2bbf72023-12-11 07:36:57 +0530296 logger.Warnf(ctx, "device-already-reconciled-or-active", log.Fields{"device-id": device.Id, "parent-id": device.ParentId})
297 return &empty.Empty{}, status.Errorf(codes.AlreadyExists, "handler exists: %s", device.Id)
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000298 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400299 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000300}
301
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530302// DisableDevice disables the given device
khenaidoo7d3c5582021-08-11 18:09:44 -0400303func (oo *OpenONUAC) DisableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000304 logger.Infow(ctx, "disable-device", log.Fields{"device-id": device.Id})
305 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400306 go handler.disableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
307 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300308 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000309 logger.Warnw(ctx, "no handler found for device-disable", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400310 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000311}
312
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530313// ReEnableDevice enables the onu device after disable
khenaidoo7d3c5582021-08-11 18:09:44 -0400314func (oo *OpenONUAC) ReEnableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000315 logger.Infow(ctx, "reenable-device", log.Fields{"device-id": device.Id})
316 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400317 go handler.reEnableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
318 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300319 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000320 logger.Warnw(ctx, "no handler found for device-reenable", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400321 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000322}
323
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530324// RebootDevice reboots the given device
khenaidoo7d3c5582021-08-11 18:09:44 -0400325func (oo *OpenONUAC) RebootDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000326 logger.Infow(ctx, "reboot-device", log.Fields{"device-id": device.Id})
327 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400328 go handler.rebootDevice(log.WithSpanFromContext(context.Background(), ctx), true, device) //reboot request with device checking
329 return &empty.Empty{}, nil
ozgecanetsiae11479f2020-07-06 09:44:47 +0300330 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000331 logger.Warnw(ctx, "no handler found for device-reboot", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400332 return nil, fmt.Errorf("handler-not-found-for-device: %s", device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000333}
334
khenaidoo7d3c5582021-08-11 18:09:44 -0400335// DeleteDevice deletes the given device
336func (oo *OpenONUAC) DeleteDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
337 nctx := log.WithSpanFromContext(context.Background(), ctx)
khenaidoo7d3c5582021-08-11 18:09:44 -0400338 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 +0000339
dbainbri4d3a0dc2020-12-02 00:33:42 +0000340 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
Girish Gowdra0e533642021-03-02 22:02:51 -0800341 var errorsList []error
Holger Hildebrandtff05b682021-03-16 15:02:05 +0000342
343 handler.mutexDeletionInProgressFlag.Lock()
344 handler.deletionInProgress = true
345 handler.mutexDeletionInProgressFlag.Unlock()
346
Girish Gowdraabcceb12022-04-13 23:35:22 -0700347 // Setting the device deletion progress flag will cause the PM FSM to cleanup for GC after FSM moves to NULL state
nikesh.krishnan1249be92023-11-27 04:20:12 +0530348 if handler.pOnuMetricsMgr != nil {
349 handler.pOnuMetricsMgr.SetdeviceDeletionInProgress(true)
350 }
praneeth nalmasf405e962023-08-07 15:02:03 +0530351
352 handler.deviceDeleteCommChan <- true
Holger Hildebrandt60652202021-11-02 11:09:36 +0000353 if err := handler.resetFsms(ctx, true); err != nil {
354 errorsList = append(errorsList, err)
355 }
Girish Gowdrae95687a2021-09-08 16:30:58 -0700356 for _, uni := range handler.uniEntityMap {
357 if handler.GetFlowMonitoringIsRunning(uni.UniID) {
358 handler.stopFlowMonitoringRoutine[uni.UniID] <- true
359 logger.Debugw(ctx, "sent stop signal to self flow monitoring routine", log.Fields{"device-id": device.Id})
360 }
361 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000362 //don't leave any garbage in kv-store
363 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
364 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000365 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000366 oo.deleteDeviceHandlerToMap(handler)
367 go handler.PrepareForGarbageCollection(ctx, handler.DeviceID)
Holger Hildebrandt60652202021-11-02 11:09:36 +0000368
Girish Gowdra0e533642021-03-02 22:02:51 -0800369 if len(errorsList) > 0 {
370 logger.Errorw(ctx, "one-or-more-error-during-device-delete", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400371 return nil, fmt.Errorf("one-or-more-error-during-device-delete, errors:%v", errorsList)
Girish Gowdra0e533642021-03-02 22:02:51 -0800372 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400373 return &empty.Empty{}, nil
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000374 }
Holger Hildebrandt60652202021-11-02 11:09:36 +0000375 logger.Infow(ctx, "no handler found for device-deletion - trying to delete remaining data in the kv-store ", log.Fields{"device-id": device.Id})
376
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000377 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
378 return nil, err
Holger Hildebrandt60652202021-11-02 11:09:36 +0000379 }
380 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000381}
382
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530383// UpdateFlowsIncrementally updates (add/remove) the flows on a given device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400384func (oo *OpenONUAC) UpdateFlowsIncrementally(ctx context.Context, incrFlows *ca.IncrementalFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400385 logger.Infow(ctx, "update-flows-incrementally", log.Fields{"device-id": incrFlows.Device.Id})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000386
mpagenkofc4f56e2020-11-04 17:17:49 +0000387 //flow config is relayed to handler even if the device might be in some 'inactive' state
388 // let the handler or related FSM's decide, what to do with the modified flow state info
389 // 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 +0000390
391 // For now, there is no support for group changes (as in the actual Py-adapter code)
mpagenkofc4f56e2020-11-04 17:17:49 +0000392 // but processing is continued for flowUpdate possibly also set in the request
khenaidoo7d3c5582021-08-11 18:09:44 -0400393 if incrFlows.Groups.ToAdd != nil && incrFlows.Groups.ToAdd.Items != nil {
394 logger.Warnw(ctx, "Update-flow-incr: group add not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000395 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400396 if incrFlows.Groups.ToRemove != nil && incrFlows.Groups.ToRemove.Items != nil {
397 logger.Warnw(ctx, "Update-flow-incr: group remove not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000398 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400399 if incrFlows.Groups.ToUpdate != nil && incrFlows.Groups.ToUpdate.Items != nil {
400 logger.Warnw(ctx, "Update-flow-incr: group update not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000401 }
402
khenaidoo7d3c5582021-08-11 18:09:44 -0400403 if handler := oo.getDeviceHandler(ctx, incrFlows.Device.Id, false); handler != nil {
404 if err := handler.FlowUpdateIncremental(log.WithSpanFromContext(context.Background(), ctx), incrFlows.Flows, incrFlows.Groups, incrFlows.FlowMetadata); err != nil {
405 return nil, err
406 }
407 return &empty.Empty{}, nil
mpagenkodff5dda2020-08-28 11:52:01 +0000408 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400409 logger.Warnw(ctx, "no handler found for incremental flow update", log.Fields{"device-id": incrFlows.Device.Id})
410 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", incrFlows.Device.Id))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000411}
412
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530413// UpdatePmConfig returns PmConfigs nil or error
khenaidoo42dcdfd2021-10-19 17:34:12 -0400414func (oo *OpenONUAC) UpdatePmConfig(ctx context.Context, configs *ca.PmConfigsInfo) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400415 logger.Infow(ctx, "update-pm-config", log.Fields{"device-id": configs.DeviceId})
416 if handler := oo.getDeviceHandler(ctx, configs.DeviceId, false); handler != nil {
417 if err := handler.updatePmConfig(log.WithSpanFromContext(context.Background(), ctx), configs.PmConfigs); err != nil {
418 return nil, err
419 }
420 return &empty.Empty{}, nil
Girish Gowdrae09a6202021-01-12 18:10:59 -0800421 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400422 logger.Warnw(ctx, "no handler found for update-pm-config", log.Fields{"device-id": configs.DeviceId})
423 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", configs.DeviceId))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000424}
425
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530426// DownloadImage requests downloading some image according to indications as given in request
427// The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400428func (oo *OpenONUAC) DownloadImage(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400429 ctx = log.WithSpanFromContext(context.Background(), ctx)
430 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt52f271b2022-06-02 09:32:27 +0000431 if strings.Contains(imageInfo.Image.Url, "https:") {
432 return nil, errors.New("image download via https not supported")
433 }
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000434 if !oo.pDownloadManager.ImageExists(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400435 logger.Debugw(ctx, "start image download", log.Fields{"image-description": imageInfo.Image})
mpagenko15ff4a52021-03-02 10:09:20 +0000436 // Download_image is not supposed to be blocking, anyway let's call the DownloadManager still synchronously to detect 'fast' problems
437 // the download itself is later done in background
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000438 if err := oo.pDownloadManager.StartDownload(ctx, imageInfo.Image); err != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400439 return nil, err
440 }
441 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000442 }
443 // image already exists
khenaidoo7d3c5582021-08-11 18:09:44 -0400444 logger.Debugw(ctx, "image already downloaded", log.Fields{"image-description": imageInfo.Image})
445 return imageInfo.Image, nil
mpagenkoc8bba412021-01-15 15:38:44 +0000446 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400447
448 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000449}
450
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530451// ActivateImageUpdate requests downloading some Onu Software image to the ONU via OMCI
452//
453// according to indications as given in request and on success activate the image on the ONU
454//
455// The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400456func (oo *OpenONUAC) ActivateImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400457 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000458 if oo.pDownloadManager.ImageLocallyDownloaded(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400459 if handler := oo.getDeviceHandler(ctx, imageInfo.Device.Id, false); handler != nil {
mpagenko15ff4a52021-03-02 10:09:20 +0000460 logger.Debugw(ctx, "image download on omci requested", log.Fields{
khenaidoo7d3c5582021-08-11 18:09:44 -0400461 "image-description": imageInfo.Image, "device-id": imageInfo.Device.Id})
462 if err := handler.doOnuSwUpgrade(ctx, imageInfo.Image, oo.pDownloadManager); err != nil {
463 return nil, err
464 }
465 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000466 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400467 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": imageInfo.Device.Id})
468 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found - device-id: %s", imageInfo.Device.Id))
mpagenko057889c2021-01-21 16:51:58 +0000469 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400470 logger.Debugw(ctx, "image not yet downloaded on activate request", log.Fields{"image-description": imageInfo.Image})
471 return nil, fmt.Errorf(fmt.Sprintf("image-not-yet-downloaded - device-id: %s", imageInfo.Device.Id))
mpagenkoc8bba412021-01-15 15:38:44 +0000472 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400473 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000474}
475
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530476// GetSingleValue handles the core request to retrieve uni status
khenaidoo7d3c5582021-08-11 18:09:44 -0400477func (oo *OpenONUAC) GetSingleValue(ctx context.Context, request *extension.SingleGetValueRequest) (*extension.SingleGetValueResponse, error) {
kesavandfdf77632021-01-26 23:40:33 -0500478 logger.Infow(ctx, "Single_get_value_request", log.Fields{"request": request})
479
480 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
481 switch reqType := request.GetRequest().GetRequest().(type) {
482 case *extension.GetValueRequest_UniInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000483 return handler.GetUniPortStatus(ctx, reqType.UniInfo), nil
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700484 case *extension.GetValueRequest_OnuOpticalInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000485 CommChan := make(chan cmn.Message)
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700486 respChan := make(chan extension.SingleGetValueResponse)
487 // Initiate the self test request
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000488 if err := handler.pSelfTestHdlr.SelfTestRequestStart(ctx, *request, CommChan, respChan); err != nil {
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700489 return &extension.SingleGetValueResponse{
490 Response: &extension.GetValueResponse{
491 Status: extension.GetValueResponse_ERROR,
492 ErrReason: extension.GetValueResponse_INTERNAL_ERROR,
493 },
494 }, err
495 }
496 // The timeout handling is already implemented in omci_self_test_handler module
497 resp := <-respChan
498 return &resp, nil
Himani Chawla43f95ff2021-06-03 00:24:12 +0530499 case *extension.GetValueRequest_OnuInfo:
500 return handler.getOnuOMCICounters(ctx, reqType.OnuInfo), nil
Holger Hildebrandt66af5ce2022-09-07 13:38:02 +0000501 case *extension.GetValueRequest_OnuOmciStats:
502 return handler.getOnuOMCIStats(ctx)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530503 case *extension.GetValueRequest_OnuActiveAlarms:
504 resp := handler.getOnuActiveAlarms(ctx)
505 logger.Infow(ctx, "Received response for on demand active alarms request ", log.Fields{"response": resp})
506 return resp, nil
kesavandfdf77632021-01-26 23:40:33 -0500507 default:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000508 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_UNSUPPORTED), nil
kesavandfdf77632021-01-26 23:40:33 -0500509 }
510 }
511 logger.Errorw(ctx, "Single_get_value_request failed ", log.Fields{"request": request})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000512 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_INVALID_DEVICE_ID), nil
mpagenkoc8bba412021-01-15 15:38:44 +0000513}
514
mpagenko83144272021-04-27 10:06:22 +0000515//if update >= 4.3.0
mpagenkoc26d4c02021-05-06 14:27:57 +0000516// Note: already with the implementation of the 'old' download interface problems were detected when the argument name used here is not the same
517// as defined in the adapter interface file. That sounds strange and the effects were strange as well.
518// The reason for that was never finally investigated.
519// To be on the safe side argument names are left here always as defined in iAdapter.go .
mpagenko83144272021-04-27 10:06:22 +0000520
khenaidoo7d3c5582021-08-11 18:09:44 -0400521// DownloadOnuImage downloads (and optionally activates and commits) the indicated ONU image to the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530522//
523// if the image is not yet present on the adapter it has to be automatically downloaded
khenaidoo7d3c5582021-08-11 18:09:44 -0400524func (oo *OpenONUAC) DownloadOnuImage(ctx context.Context, request *voltha.DeviceImageDownloadRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000525 if request != nil && len((*request).DeviceId) > 0 && (*request).Image.Version != "" {
Holger Hildebrandt52f271b2022-06-02 09:32:27 +0000526 if strings.Contains((*request).Image.Url, "https:") {
527 return nil, errors.New("image download via https not supported")
528 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000529 loResponse := voltha.DeviceImageResponse{}
530 imageIdentifier := (*request).Image.Version
mpagenkoc497ee32021-11-10 17:30:20 +0000531 downloadStartDone := false
mpagenkoc26d4c02021-05-06 14:27:57 +0000532 firstDevice := true
533 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000534 var onuVolthaDevice *voltha.Device
535 var devErr error
mpagenkoc26d4c02021-05-06 14:27:57 +0000536 for _, pCommonID := range (*request).DeviceId {
mpagenko38662d02021-08-11 09:45:19 +0000537 vendorIDMatch := true
mpagenkoc26d4c02021-05-06 14:27:57 +0000538 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000539 loDeviceImageState := voltha.DeviceImageState{}
540 loDeviceImageState.DeviceId = loDeviceID
541 loImageState := voltha.ImageState{}
542 loDeviceImageState.ImageState = &loImageState
543 loDeviceImageState.ImageState.Version = (*request).Image.Version
mpagenko38662d02021-08-11 09:45:19 +0000544
mpagenko59862f02021-10-11 08:53:18 +0000545 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400546 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000547 if handler != nil {
548 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
549 } else {
550 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
551 devErr = errors.New("no handler found for device-id")
khenaidoo7d3c5582021-08-11 18:09:44 -0400552 }
mpagenko59862f02021-10-11 08:53:18 +0000553 if devErr != nil || onuVolthaDevice == nil {
554 logger.Warnw(ctx, "Failed to fetch ONU device for image download",
555 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000556 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
557 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //proto restriction, better option: 'INVALID_DEVICE'
mpagenkoc26d4c02021-05-06 14:27:57 +0000558 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000559 } else {
mpagenko38662d02021-08-11 09:45:19 +0000560 if firstDevice {
561 //start/verify download of the image to the adapter based on first found device only
562 // use the OnuVendor identification from first given device
mpagenkoc497ee32021-11-10 17:30:20 +0000563
564 // note: if the request was done for a list of devices on the Voltha interface, rwCore
565 // 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 +0000566 firstDevice = false
567 vendorID = onuVolthaDevice.VendorId
568 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
mpagenkoc497ee32021-11-10 17:30:20 +0000569 logger.Infow(ctx, "download request for file",
570 log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000571
mpagenkoc497ee32021-11-10 17:30:20 +0000572 // call the StartDownload synchronously to detect 'immediate' download problems
573 // the real download itself is later done in background
574 if fileState, err := oo.pFileManager.StartDownload(ctx, imageIdentifier, (*request).Image.Url); err == nil {
mpagenko38662d02021-08-11 09:45:19 +0000575 // note: If the image (with vendorId+name) has already been downloaded before from some other
mpagenkoc497ee32021-11-10 17:30:20 +0000576 // valid URL, the current download request is not executed (current code delivers URL error).
577 // If the operators want to ensure that the new URL
mpagenko38662d02021-08-11 09:45:19 +0000578 // is really used, then they first have to use the 'abort' API to remove the existing image!
579 // (abort API can be used also after some successful download to just remove the image from adapter)
mpagenkoc497ee32021-11-10 17:30:20 +0000580 if fileState == swupg.CFileStateDlSucceeded || fileState == swupg.CFileStateDlStarted {
581 downloadStartDone = true
582 } //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 +0000583 }
584 } else {
585 //for all following devices verify the matching vendorID
586 if onuVolthaDevice.VendorId != vendorID {
587 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
588 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
589 vendorIDMatch = false
590 }
591 }
mpagenkoc497ee32021-11-10 17:30:20 +0000592 if downloadStartDone && vendorIDMatch {
mpagenko38662d02021-08-11 09:45:19 +0000593 // start the ONU download activity for each possible device
mpagenkoc497ee32021-11-10 17:30:20 +0000594 logger.Infow(ctx, "request image download to ONU on omci ", log.Fields{
mpagenko59862f02021-10-11 08:53:18 +0000595 "image-id": imageIdentifier, "device-id": loDeviceID})
596 //onu upgrade handling called in background without immediate error evaluation here
597 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
598 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
599 go handler.onuSwUpgradeAfterDownload(ctx, request, oo.pFileManager, imageIdentifier)
600 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_STARTED
601 loDeviceImageState.ImageState.Reason = voltha.ImageState_NO_ERROR
602 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenko38662d02021-08-11 09:45:19 +0000603 } else {
604 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
mpagenkoc497ee32021-11-10 17:30:20 +0000605 if !downloadStartDone {
606 //based on above fileState more descriptive error codes would be possible, e.g
607 // IMAGE_EXISTS_WITH_DIFFERENT_URL - would require proto buf update
mpagenko38662d02021-08-11 09:45:19 +0000608 loDeviceImageState.ImageState.Reason = voltha.ImageState_INVALID_URL
609 } else { //only logical option is !vendorIDMatch
610 loDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
611 }
612 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
613 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000614 }
mpagenko2f2f2362021-06-07 08:25:22 +0000615 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000616 } //for all requested devices
mpagenkoc26d4c02021-05-06 14:27:57 +0000617 pImageResp := &loResponse
618 return pImageResp, nil
619 }
620 return nil, errors.New("invalid image download parameters")
mpagenko83144272021-04-27 10:06:22 +0000621}
622
khenaidoo7d3c5582021-08-11 18:09:44 -0400623// GetOnuImageStatus delivers the adapter-related information about the download/activation/commitment
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530624//
625// status for the requested image
khenaidoo7d3c5582021-08-11 18:09:44 -0400626func (oo *OpenONUAC) GetOnuImageStatus(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000627 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
628 loResponse := voltha.DeviceImageResponse{}
mpagenkoaa3afe92021-05-21 16:20:58 +0000629 imageIdentifier := (*in).Version
mpagenko38662d02021-08-11 09:45:19 +0000630 var vendorIDSet bool
mpagenkoaa3afe92021-05-21 16:20:58 +0000631 firstDevice := true
632 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000633 var onuVolthaDevice *voltha.Device
634 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000635 for _, pCommonID := range (*in).DeviceId {
636 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400637 pDeviceImageState := &voltha.DeviceImageState{DeviceId: loDeviceID}
mpagenko59862f02021-10-11 08:53:18 +0000638 vendorIDSet = false
639 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400640 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000641 if handler != nil {
642 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
643 } else {
644 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
645 devErr = errors.New("no handler found for device-id")
mpagenko38662d02021-08-11 09:45:19 +0000646 }
mpagenko59862f02021-10-11 08:53:18 +0000647 if devErr != nil || onuVolthaDevice == nil {
mpagenkoaa3afe92021-05-21 16:20:58 +0000648 logger.Warnw(ctx, "Failed to fetch Onu device to get image status",
mpagenko59862f02021-10-11 08:53:18 +0000649 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000650 pImageState := &voltha.ImageState{
651 Version: (*in).Version,
652 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //no statement about last activity possible
653 Reason: voltha.ImageState_UNKNOWN_ERROR, //something like "DEVICE_NOT_EXISTS" would be better (proto def)
654 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
mpagenkoaa3afe92021-05-21 16:20:58 +0000655 }
mpagenko38662d02021-08-11 09:45:19 +0000656 pDeviceImageState.ImageState = pImageState
mpagenkoaa3afe92021-05-21 16:20:58 +0000657 } else {
mpagenko38662d02021-08-11 09:45:19 +0000658 if firstDevice {
659 //start/verify download of the image to the adapter based on first found device only
660 // use the OnuVendor identification from first given device
661 firstDevice = false
662 vendorID = onuVolthaDevice.VendorId
663 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
664 vendorIDSet = true
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000665 logger.Debugw(ctx, "status request for image", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000666 } else {
667 //for all following devices verify the matching vendorID
668 if onuVolthaDevice.VendorId != vendorID {
669 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000670 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko38662d02021-08-11 09:45:19 +0000671 } else {
672 vendorIDSet = true
673 }
674 }
675 if !vendorIDSet {
676 pImageState := &voltha.ImageState{
677 Version: (*in).Version,
678 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //can't be sure that download for this device was really tried
679 Reason: voltha.ImageState_VENDOR_DEVICE_MISMATCH,
680 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
681 }
682 pDeviceImageState.ImageState = pImageState
683 } else {
khenaidoo7d3c5582021-08-11 18:09:44 -0400684 logger.Debugw(ctx, "image status request for", log.Fields{
685 "image-id": imageIdentifier, "device-id": loDeviceID})
686 //status request is called synchronously to collect the indications for all concerned devices
687 pDeviceImageState.ImageState = handler.requestOnuSwUpgradeState(ctx, imageIdentifier, (*in).Version)
mpagenko38662d02021-08-11 09:45:19 +0000688 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000689 }
690 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000691 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000692 pImageResp := &loResponse
693 return pImageResp, nil
694 }
695 return nil, errors.New("invalid image status request parameters")
mpagenko83144272021-04-27 10:06:22 +0000696}
697
khenaidoo7d3c5582021-08-11 18:09:44 -0400698// AbortOnuImageUpgrade stops the actual download/activation/commitment process (on next possibly step)
699func (oo *OpenONUAC) AbortOnuImageUpgrade(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000700 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
701 loResponse := voltha.DeviceImageResponse{}
702 imageIdentifier := (*in).Version
703 firstDevice := true
704 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000705 var vendorIDSet bool
706 var onuVolthaDevice *voltha.Device
707 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000708 for _, pCommonID := range (*in).DeviceId {
709 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400710 pDeviceImageState := &voltha.DeviceImageState{}
711 loImageState := voltha.ImageState{}
712 pDeviceImageState.ImageState = &loImageState
mpagenko59862f02021-10-11 08:53:18 +0000713 vendorIDSet = false
714 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400715 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000716 if handler != nil {
717 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
718 } else {
719 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
720 devErr = errors.New("no handler found for device-id")
721 }
722 if devErr != nil || onuVolthaDevice == nil {
723 logger.Warnw(ctx, "Failed to fetch Onu device to abort its download",
724 log.Fields{"device-id": loDeviceID, "err": devErr})
khenaidoo7d3c5582021-08-11 18:09:44 -0400725 pDeviceImageState.DeviceId = loDeviceID
726 pDeviceImageState.ImageState.Version = (*in).Version
mpagenko59862f02021-10-11 08:53:18 +0000727 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
728 pDeviceImageState.ImageState.Reason = voltha.ImageState_CANCELLED_ON_REQUEST //something better could be considered (MissingHandler) - proto
khenaidoo7d3c5582021-08-11 18:09:44 -0400729 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoaa3afe92021-05-21 16:20:58 +0000730 } else {
mpagenko59862f02021-10-11 08:53:18 +0000731 if firstDevice {
732 //start/verify download of the image to the adapter based on first found device only
733 // use the OnuVendor identification from first given device
734 firstDevice = false
735 vendorID = onuVolthaDevice.VendorId
736 vendorIDSet = true
737 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000738 logger.Debugw(ctx, "abort request for file", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko59862f02021-10-11 08:53:18 +0000739 } else {
740 //for all following devices verify the matching vendorID
741 if onuVolthaDevice.VendorId != vendorID {
742 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000743 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko59862f02021-10-11 08:53:18 +0000744 pDeviceImageState.DeviceId = loDeviceID
745 pDeviceImageState.ImageState.Version = (*in).Version
746 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
747 pDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
748 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
749 } else {
750 vendorIDSet = true
751 }
752 }
753 if vendorIDSet {
754 // cancel the ONU upgrade activity for each possible device
755 logger.Debugw(ctx, "image upgrade abort requested", log.Fields{
756 "image-id": imageIdentifier, "device-id": loDeviceID})
757 //upgrade cancel is called synchronously to collect the imageResponse indications for all concerned devices
758 handler.cancelOnuSwUpgrade(ctx, imageIdentifier, (*in).Version, pDeviceImageState)
mpagenkoaa3afe92021-05-21 16:20:58 +0000759 }
760 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000761 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000762 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000763 if !firstDevice {
764 //if at least one valid device was found cancel also a possibly running download to adapter and remove the image
765 // this is to be done after the upgradeOnu cancel activities in order to not subduct the file for still running processes
766 oo.pFileManager.CancelDownload(ctx, imageIdentifier)
767 }
768 pImageResp := &loResponse
769 return pImageResp, nil
770 }
771 return nil, errors.New("invalid image upgrade abort parameters")
mpagenko83144272021-04-27 10:06:22 +0000772}
773
khenaidoo7d3c5582021-08-11 18:09:44 -0400774// GetOnuImages retrieves the ONU SW image status information via OMCI
775func (oo *OpenONUAC) GetOnuImages(ctx context.Context, id *common.ID) (*voltha.OnuImages, error) {
776 logger.Infow(ctx, "Get_onu_images", log.Fields{"device-id": id.Id})
777 if handler := oo.getDeviceHandler(ctx, id.Id, false); handler != nil {
Himani Chawla69992ab2021-07-08 15:13:02 +0530778 images, err := handler.getOnuImages(ctx)
779 if err == nil {
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000780 return images, nil
781 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400782 return nil, fmt.Errorf(fmt.Sprintf("%s-%s", err, id.Id))
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000783 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400784 logger.Warnw(ctx, "no handler found for Get_onu_images", log.Fields{"device-id": id.Id})
785 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", id.Id))
mpagenko83144272021-04-27 10:06:22 +0000786}
787
khenaidoo7d3c5582021-08-11 18:09:44 -0400788// ActivateOnuImage initiates the activation of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530789//
790// precondition: image downloaded and not yet activated or image refers to current inactive image
khenaidoo7d3c5582021-08-11 18:09:44 -0400791func (oo *OpenONUAC) ActivateOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000792 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
793 loResponse := voltha.DeviceImageResponse{}
794 imageIdentifier := (*in).Version
795 //let the deviceHandler find the adequate way of requesting the image activation
796 for _, pCommonID := range (*in).DeviceId {
797 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000798 loDeviceImageState := voltha.DeviceImageState{}
799 loDeviceImageState.DeviceId = loDeviceID
800 loImageState := voltha.ImageState{}
801 loDeviceImageState.ImageState = &loImageState
802 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000803 //compared to download procedure the vendorID (from device) is secondary here
804 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
805 // start image activation activity for each possible device
806 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
807 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
808 logger.Debugw(ctx, "onu image activation requested", log.Fields{
809 "image-id": imageIdentifier, "device-id": loDeviceID})
810 //onu activation handling called in background without immediate error evaluation here
811 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
812 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000813 if pImageStates, err := handler.onuSwActivateRequest(ctx, imageIdentifier, (*in).CommitOnSuccess); err != nil {
814 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
815 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
816 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
817 } else {
818 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
819 loDeviceImageState.ImageState.Reason = pImageStates.Reason
820 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
821 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000822 } else {
823 //cannot start SW activation for requested device
824 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000825 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000826 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
827 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000828 }
mpagenko2f2f2362021-06-07 08:25:22 +0000829 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000830 }
831 pImageResp := &loResponse
832 return pImageResp, nil
833 }
834 return nil, errors.New("invalid image activation parameters")
mpagenko83144272021-04-27 10:06:22 +0000835}
836
khenaidoo7d3c5582021-08-11 18:09:44 -0400837// CommitOnuImage enforces the commitment of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530838//
839// precondition: image activated and not yet committed
khenaidoo7d3c5582021-08-11 18:09:44 -0400840func (oo *OpenONUAC) CommitOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000841 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
842 loResponse := voltha.DeviceImageResponse{}
843 imageIdentifier := (*in).Version
844 //let the deviceHandler find the adequate way of requesting the image activation
845 for _, pCommonID := range (*in).DeviceId {
846 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000847 loDeviceImageState := voltha.DeviceImageState{}
848 loDeviceImageState.DeviceId = loDeviceID
849 loImageState := voltha.ImageState{}
850 loDeviceImageState.ImageState = &loImageState
851 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000852 //compared to download procedure the vendorID (from device) is secondary here
853 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
854 // start image activation activity for each possible device
855 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
856 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
857 logger.Debugw(ctx, "onu image commitment requested", log.Fields{
858 "image-id": imageIdentifier, "device-id": loDeviceID})
859 //onu commitment handling called in background without immediate error evaluation here
860 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
861 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000862 if pImageStates, err := handler.onuSwCommitRequest(ctx, imageIdentifier); err != nil {
mpagenko38662d02021-08-11 09:45:19 +0000863 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
864 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //can be multiple reasons here
mpagenko183647c2021-06-08 15:25:04 +0000865 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
866 } else {
867 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
868 loDeviceImageState.ImageState.Reason = pImageStates.Reason
869 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
870 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000871 } else {
872 //cannot start SW commitment for requested device
873 logger.Warnw(ctx, "no handler found for image commitment", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000874 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000875 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
876 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000877 }
mpagenko2f2f2362021-06-07 08:25:22 +0000878 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000879 }
880 pImageResp := &loResponse
881 return pImageResp, nil
882 }
883 return nil, errors.New("invalid image commitment parameters")
mpagenko83144272021-04-27 10:06:22 +0000884}
885
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000886// Adapter interface required methods ################ end #########
887// #################################################################
khenaidoo7d3c5582021-08-11 18:09:44 -0400888
889/*
890 *
891 * ONU inter adapter service
892 *
893 */
894
895// OnuIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400896func (oo *OpenONUAC) OnuIndication(ctx context.Context, onuInd *ia.OnuIndicationMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400897 logger.Debugw(ctx, "onu-indication", log.Fields{"onu-indication": onuInd})
898
899 if onuInd == nil || onuInd.OnuIndication == nil {
900 return nil, fmt.Errorf("invalid-onu-indication-%v", onuInd)
901 }
902
903 onuIndication := onuInd.OnuIndication
904 onuOperstate := onuIndication.GetOperState()
905 waitForDhInstPresent := false
906 if onuOperstate == "up" {
907 //Race condition (relevant in BBSIM-environment only): Due to unsynchronized processing of olt-adapter and rw_core,
908 //ONU_IND_REQUEST msg by olt-adapter could arrive a little bit earlier than rw_core was able to announce the corresponding
909 //ONU by RPC of Adopt_device(). Therefore it could be necessary to wait with processing of ONU_IND_REQUEST until call of
910 //Adopt_device() arrived and DeviceHandler instance was created
911 waitForDhInstPresent = true
912 }
913 if handler := oo.getDeviceHandler(ctx, onuInd.DeviceId, waitForDhInstPresent); handler != nil {
914 logger.Infow(ctx, "onu-ind-request", log.Fields{"device-id": onuInd.DeviceId,
915 "OnuId": onuIndication.GetOnuId(),
916 "AdminState": onuIndication.GetAdminState(), "OperState": onuOperstate,
917 "SNR": onuIndication.GetSerialNumber()})
918
919 if onuOperstate == "up" {
920 if err := handler.createInterface(ctx, onuIndication); err != nil {
921 return nil, err
922 }
923 return &empty.Empty{}, nil
924 } else if (onuOperstate == "down") || (onuOperstate == "unreachable") {
Holger Hildebrandt68854a82022-09-05 07:00:21 +0000925 if err := handler.UpdateInterface(ctx); err != nil {
ozgecanetsia76db57a2022-02-03 15:32:03 +0300926 return nil, err
927 }
928 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400929 } else {
930 logger.Errorw(ctx, "unknown-onu-ind-request operState", log.Fields{"OnuId": onuIndication.GetOnuId()})
931 return nil, fmt.Errorf("invalidOperState: %s, %s", onuOperstate, onuInd.DeviceId)
932 }
933 }
934 logger.Warnw(ctx, "no handler found for received onu-ind-request", log.Fields{
935 "msgToDeviceId": onuInd.DeviceId})
936 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", onuInd.DeviceId))
937}
938
939// OmciIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400940func (oo *OpenONUAC) OmciIndication(ctx context.Context, msg *ia.OmciMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400941 logger.Debugw(ctx, "omci-response", log.Fields{"parent-device-id": msg.ParentDeviceId, "child-device-id": msg.ChildDeviceId})
942
943 if handler := oo.getDeviceHandler(ctx, msg.ChildDeviceId, false); handler != nil {
944 if err := handler.handleOMCIIndication(log.WithSpanFromContext(context.Background(), ctx), msg); err != nil {
945 return nil, err
946 }
947 return &empty.Empty{}, nil
948 }
949 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", msg.ChildDeviceId))
950}
951
952// DownloadTechProfile is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400953func (oo *OpenONUAC) DownloadTechProfile(ctx context.Context, tProfile *ia.TechProfileDownloadMessage) (*empty.Empty, error) {
nikesh.krishnan1ffb8132023-05-23 03:44:13 +0530954 logger.Info(ctx, "download-tech-profile", log.Fields{"device-id": tProfile.DeviceId, "uni-id": tProfile.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400955
956 if handler := oo.getDeviceHandler(ctx, tProfile.DeviceId, false); handler != nil {
Praneeth Nalmas04600be2024-12-08 20:12:32 +0530957 handler.RLockMutexDeletionInProgressFlag()
958 if handler.GetDeletionInProgress() {
959 logger.Warnw(ctx, "Device deletion in progress - avoid processing Tech Profile", log.Fields{"device-id": tProfile.DeviceId})
960
961 handler.RUnlockMutexDeletionInProgressFlag()
962 return nil, fmt.Errorf(fmt.Sprintf("Can't proceed, device deletion is in progress-%s", tProfile.DeviceId))
963 }
964 handler.RUnlockMutexDeletionInProgressFlag()
khenaidoo7d3c5582021-08-11 18:09:44 -0400965 if err := handler.handleTechProfileDownloadRequest(log.WithSpanFromContext(context.Background(), ctx), tProfile); err != nil {
966 return nil, err
967 }
968 return &empty.Empty{}, nil
969 }
970 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", tProfile.DeviceId))
971}
972
973// DeleteGemPort is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400974func (oo *OpenONUAC) DeleteGemPort(ctx context.Context, gPort *ia.DeleteGemPortMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400975 logger.Debugw(ctx, "delete-gem-port", log.Fields{"device-id": gPort.DeviceId, "uni-id": gPort.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400976 if handler := oo.getDeviceHandler(ctx, gPort.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530977 if handler.GetDeletionInProgress() {
978 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": gPort.DeviceId})
979 return nil, fmt.Errorf("device deletion in progress for device-id: %s", gPort.DeviceId)
980 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400981 if err := handler.handleDeleteGemPortRequest(log.WithSpanFromContext(context.Background(), ctx), gPort); err != nil {
982 return nil, err
983 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000984 } else {
985 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": gPort.DeviceId})
986 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400987 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000988 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400989}
990
991// DeleteTCont is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400992func (oo *OpenONUAC) DeleteTCont(ctx context.Context, tConf *ia.DeleteTcontMessage) (*empty.Empty, error) {
Holger Hildebrandtba6fbe82021-12-03 14:29:42 +0000993 logger.Debugw(ctx, "delete-tcont", log.Fields{"device-id": tConf.DeviceId, "tconf": tConf})
khenaidoo7d3c5582021-08-11 18:09:44 -0400994 if handler := oo.getDeviceHandler(ctx, tConf.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530995 if handler.GetDeletionInProgress() {
996 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": tConf.DeviceId})
997 return nil, fmt.Errorf("device deletion in progress for device-id: %s", tConf.DeviceId)
998 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400999 if err := handler.handleDeleteTcontRequest(log.WithSpanFromContext(context.Background(), ctx), tConf); err != nil {
1000 return nil, err
1001 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +00001002 } else {
1003 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": tConf.DeviceId})
1004 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -04001005 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +00001006 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001007}
1008
1009/*
1010 * Parent GRPC clients
1011 */
1012
khenaidoo55cebc62021-12-08 14:44:41 -05001013func getHash(endpoint, contextInfo string) string {
1014 strToHash := endpoint + contextInfo
1015 h := fnv.New128().Sum([]byte(strToHash))
1016 return string(h)
1017}
1018
1019func (oo *OpenONUAC) updateReachabilityFromRemote(ctx context.Context, remote *common.Connection) {
1020 logger.Debugw(context.Background(), "updating-remote-connection-status", log.Fields{"remote": remote})
1021 oo.lockReachableFromRemote.Lock()
1022 defer oo.lockReachableFromRemote.Unlock()
1023 endpointHash := getHash(remote.Endpoint, remote.ContextInfo)
1024 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
1025 oo.reachableFromRemote[endpointHash].lastKeepAlive = time.Now()
1026 oo.reachableFromRemote[endpointHash].keepAliveInterval = remote.KeepAliveInterval
1027 return
1028 }
1029 logger.Debugw(context.Background(), "initial-remote-connection", log.Fields{"remote": remote})
1030 oo.reachableFromRemote[endpointHash] = &reachabilityFromRemote{lastKeepAlive: time.Now(), keepAliveInterval: remote.KeepAliveInterval}
1031}
1032
khenaidoof3333552021-12-15 16:52:31 -05001033func (oo *OpenONUAC) isReachableFromRemote(ctx context.Context, endpoint string, contextInfo string) bool {
1034 logger.Debugw(ctx, "checking-remote-reachability", log.Fields{"endpoint": endpoint, "context": contextInfo})
khenaidoo55cebc62021-12-08 14:44:41 -05001035 oo.lockReachableFromRemote.RLock()
1036 defer oo.lockReachableFromRemote.RUnlock()
1037 endpointHash := getHash(endpoint, contextInfo)
1038 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
khenaidoof3333552021-12-15 16:52:31 -05001039 logger.Debugw(ctx, "endpoint-exists", log.Fields{"last-keep-alive": time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive)})
khenaidoo55cebc62021-12-08 14:44:41 -05001040 // Assume the connection is down if we did not receive 2 keep alives in succession
1041 maxKeepAliveWait := time.Duration(oo.reachableFromRemote[endpointHash].keepAliveInterval * 2)
1042 return time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive) <= maxKeepAliveWait
1043 }
1044 return false
1045}
1046
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301047// stopAllGrpcClients stops all grpc clients in use
khenaidoof3333552021-12-15 16:52:31 -05001048func (oo *OpenONUAC) stopAllGrpcClients(ctx context.Context) {
1049 // Stop the clients that connect to the parent
1050 oo.lockParentAdapterClients.Lock()
1051 for key := range oo.parentAdapterClients {
1052 oo.parentAdapterClients[key].Stop(ctx)
1053 delete(oo.parentAdapterClients, key)
1054 }
1055 oo.lockParentAdapterClients.Unlock()
1056
1057 // Stop core client connection
1058 oo.coreClient.Stop(ctx)
1059}
1060
khenaidoo7d3c5582021-08-11 18:09:44 -04001061func (oo *OpenONUAC) setupParentInterAdapterClient(ctx context.Context, endpoint string) error {
1062 logger.Infow(ctx, "setting-parent-adapter-connection", log.Fields{"parent-endpoint": endpoint})
1063 oo.lockParentAdapterClients.Lock()
1064 defer oo.lockParentAdapterClients.Unlock()
1065 if _, ok := oo.parentAdapterClients[endpoint]; ok {
1066 return nil
1067 }
1068
khenaidoo55cebc62021-12-08 14:44:41 -05001069 childClient, err := vgrpc.NewClient(
1070 oo.config.AdapterEndpoint,
1071 endpoint,
khenaidoof3333552021-12-15 16:52:31 -05001072 "olt_inter_adapter_service.OltInterAdapterService",
khenaidoo55cebc62021-12-08 14:44:41 -05001073 oo.oltAdapterRestarted)
khenaidoo7d3c5582021-08-11 18:09:44 -04001074
1075 if err != nil {
1076 return err
1077 }
nikesh.krishnance4879a2023-08-01 18:36:57 +05301078 retryCodes := []codes.Code{
1079 codes.Unavailable, // server is currently unavailable
1080 codes.DeadlineExceeded, // deadline for the operation was exceeded
1081 }
1082 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(oo.config.PerRPCRetryTimeout, 0.2))
1083 grpcRetryOptions := grpc_retry.UnaryClientInterceptor(grpc_retry.WithMax(oo.config.MaxRetries), grpc_retry.WithPerRetryTimeout(oo.config.PerRPCRetryTimeout), grpc_retry.WithCodes(retryCodes...), backoffCtxOption)
khenaidoo7d3c5582021-08-11 18:09:44 -04001084
1085 oo.parentAdapterClients[endpoint] = childClient
nikesh.krishnance4879a2023-08-01 18:36:57 +05301086 go oo.parentAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), getOltInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo7d3c5582021-08-11 18:09:44 -04001087 // Wait until we have a connection to the child adapter.
1088 // Unlimited retries or until context expires
1089 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
1090 backoff := vgrpc.NewBackoff(oo.config.MinBackoffRetryDelay, oo.config.MaxBackoffRetryDelay, 0)
1091 for {
1092 client, err := oo.parentAdapterClients[endpoint].GetOltInterAdapterServiceClient()
1093 if err == nil && client != nil {
1094 logger.Infow(subCtx, "connected-to-parent-adapter", log.Fields{"parent-endpoint": endpoint})
1095 break
1096 }
1097 logger.Warnw(subCtx, "connection-to-parent-adapter-not-ready", log.Fields{"error": err, "parent-endpoint": endpoint})
1098 // Backoff
1099 if err = backoff.Backoff(subCtx); err != nil {
1100 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "parent-endpoint": endpoint})
1101 break
1102 }
1103 }
1104 return nil
1105}
1106
khenaidoo42dcdfd2021-10-19 17:34:12 -04001107func (oo *OpenONUAC) getParentAdapterServiceClient(endpoint string) (olt_inter_adapter_service.OltInterAdapterServiceClient, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001108 // First check from cache
1109 oo.lockParentAdapterClients.RLock()
1110 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1111 oo.lockParentAdapterClients.RUnlock()
1112 return pgClient.GetOltInterAdapterServiceClient()
1113 }
1114 oo.lockParentAdapterClients.RUnlock()
1115
1116 // Set the parent connection - can occur on restarts
1117 ctx, cancel := context.WithTimeout(context.Background(), oo.config.RPCTimeout)
1118 err := oo.setupParentInterAdapterClient(ctx, endpoint)
1119 cancel()
1120 if err != nil {
1121 return nil, err
1122 }
1123
1124 // Get the parent client now
1125 oo.lockParentAdapterClients.RLock()
1126 defer oo.lockParentAdapterClients.RUnlock()
1127 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1128 return pgClient.GetOltInterAdapterServiceClient()
1129 }
1130
1131 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
1132}
1133
1134// TODO: Any action the adapter needs to do following an olt adapter restart?
1135func (oo *OpenONUAC) oltAdapterRestarted(ctx context.Context, endPoint string) error {
1136 logger.Errorw(ctx, "olt-adapter-restarted", log.Fields{"endpoint": endPoint})
1137 return nil
1138}
1139
khenaidoof3333552021-12-15 16:52:31 -05001140// getOltInterAdapterServiceClientHandler is used to setup the remote gRPC service
1141func getOltInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
1142 if conn == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -04001143 return nil
1144 }
khenaidoof3333552021-12-15 16:52:31 -05001145 return olt_inter_adapter_service.NewOltInterAdapterServiceClient(conn)
khenaidoo7d3c5582021-08-11 18:09:44 -04001146}
1147
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001148func (oo *OpenONUAC) forceDeleteDeviceKvData(ctx context.Context, aDeviceID string) error {
1149 logger.Debugw(ctx, "force deletion of ONU device specific data in kv store", log.Fields{"device-id": aDeviceID})
Girish Gowdraf10379e2022-02-02 21:49:44 -08001150 var errorsList []error
1151 // delete onu persitent data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001152 onuBaseKvStorePath := fmt.Sprintf(cmn.CBasePathOnuKVStore, oo.cm.Backend.PathPrefix)
1153 logger.Debugw(ctx, "SetOnuKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": onuBaseKvStorePath,
1154 "device-id": aDeviceID})
1155 onuKvbackend := &db.Backend{
1156 Client: oo.kvClient,
1157 StoreType: oo.KVStoreType,
1158 Address: oo.KVStoreAddress,
1159 Timeout: oo.KVStoreTimeout,
1160 PathPrefix: onuBaseKvStorePath,
1161 }
1162 err := onuKvbackend.DeleteWithPrefix(ctx, aDeviceID)
1163 if err != nil {
1164 logger.Errorw(ctx, "unable to delete in KVstore", log.Fields{"service": onuBaseKvStorePath, "device-id": aDeviceID, "err": err})
1165 // continue to delete kv data, but accumulate any errors
1166 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001167 }
Girish Gowdraf10379e2022-02-02 21:49:44 -08001168 // delete pm data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001169 pmBaseKvStorePath := fmt.Sprintf(pmmgr.CPmKvStorePrefixBase, oo.cm.Backend.PathPrefix)
1170 logger.Debugw(ctx, "SetPmKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": pmBaseKvStorePath,
1171 "device-id": aDeviceID})
Girish Gowdraf10379e2022-02-02 21:49:44 -08001172 pmKvbackend := &db.Backend{
1173 Client: oo.kvClient,
1174 StoreType: oo.KVStoreType,
1175 Address: oo.KVStoreAddress,
1176 Timeout: oo.KVStoreTimeout,
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001177 PathPrefix: pmBaseKvStorePath,
Girish Gowdraf10379e2022-02-02 21:49:44 -08001178 }
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001179 err = pmKvbackend.DeleteWithPrefix(ctx, aDeviceID)
Girish Gowdraf10379e2022-02-02 21:49:44 -08001180 if err != nil {
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001181 logger.Errorw(ctx, "unable to delete PM in KVstore", log.Fields{"service": pmBaseKvStorePath, "device-id": aDeviceID, "err": err})
Girish Gowdraf10379e2022-02-02 21:49:44 -08001182 // accumulate any errors
1183 errorsList = append(errorsList, err)
1184 }
1185 if len(errorsList) > 0 {
1186 return fmt.Errorf("one or more error deleting kv data, error: %v", errorsList)
1187 }
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001188 return nil
1189}
1190
khenaidoof3333552021-12-15 16:52:31 -05001191// GetHealthStatus is used by the voltha core to open a streaming connection with the onu adapter.
1192func (oo *OpenONUAC) GetHealthStatus(stream adapter_service.AdapterService_GetHealthStatusServer) error {
1193 ctx := context.Background()
1194 logger.Debugw(ctx, "receive-stream-connection", log.Fields{"stream": stream})
1195
1196 if stream == nil {
1197 return fmt.Errorf("conn-is-nil %v", stream)
1198 }
1199 initialRequestTime := time.Now()
1200 var remoteClient *common.Connection
1201 var tempClient *common.Connection
1202 var err error
1203loop:
1204 for {
1205 tempClient, err = stream.Recv()
1206 if err != nil {
1207 logger.Warnw(ctx, "received-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1208 break loop
1209 }
1210 // Send a response back
1211 err = stream.Send(&health.HealthStatus{State: health.HealthStatus_HEALTHY})
1212 if err != nil {
1213 logger.Warnw(ctx, "sending-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1214 break loop
1215 }
1216 remoteClient = tempClient
1217
1218 logger.Debugw(ctx, "received-keep-alive", log.Fields{"remote-client": remoteClient})
1219
1220 select {
1221 case <-stream.Context().Done():
1222 logger.Infow(ctx, "stream-keep-alive-context-done", log.Fields{"remote-client": remoteClient, "error": stream.Context().Err()})
1223 break loop
1224 case <-oo.exitChannel:
1225 logger.Warnw(ctx, "received-stop", log.Fields{"remote-client": remoteClient, "initial-conn-time": initialRequestTime})
1226 break loop
1227 default:
1228 }
1229 }
1230 logger.Errorw(ctx, "connection-down", log.Fields{"remote-client": remoteClient, "error": err, "initial-conn-time": initialRequestTime})
1231 return err
1232}
1233
khenaidoo7d3c5582021-08-11 18:09:44 -04001234/*
1235 *
1236 * Unimplemented APIs
1237 *
1238 */
1239
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301240// GetOfpDeviceInfo returns OFP information for the given device. Method not implemented as per [VOL-3202].
khenaidoo7d3c5582021-08-11 18:09:44 -04001241// OF port info is now to be delivered within UniPort create cmp changes in onu_uni_port.go::CreateVolthaPort()
khenaidoo42dcdfd2021-10-19 17:34:12 -04001242func (oo *OpenONUAC) GetOfpDeviceInfo(ctx context.Context, device *voltha.Device) (*ca.SwitchCapability, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001243 return nil, errors.New("unImplemented")
1244}
1245
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301246// SimulateAlarm is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001247func (oo *OpenONUAC) SimulateAlarm(context.Context, *ca.SimulateAlarmMessage) (*common.OperationResp, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001248 return nil, errors.New("unImplemented")
1249}
1250
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301251// SetExtValue is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001252func (oo *OpenONUAC) SetExtValue(context.Context, *ca.SetExtValueMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001253 return nil, errors.New("unImplemented")
1254}
1255
Akash Soni3c176c62024-12-04 13:30:43 +05301256// SetSingleValue sets a single value based on the given request and returns the response.
1257func (oo *OpenONUAC) SetSingleValue(ctx context.Context, request *extension.SingleSetValueRequest) (*extension.SingleSetValueResponse, error) {
1258 logger.Infow(ctx, "single_set_value_request", log.Fields{"request": request})
1259
1260 errResp := func(status extension.SetValueResponse_Status,
1261 reason extension.SetValueResponse_ErrorReason) *extension.SingleSetValueResponse {
1262 return &extension.SingleSetValueResponse{
1263 Response: &extension.SetValueResponse{
1264 Status: status,
1265 ErrReason: reason,
1266 },
1267 }
1268 }
1269 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
1270 switch reqType := request.GetRequest().GetRequest().(type) {
1271 case *extension.SetValueRequest_AppOffloadOnuConfig:
1272 return handler.setOnuOffloadStats(ctx, reqType.AppOffloadOnuConfig), nil
1273 default:
1274 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_UNSUPPORTED), nil
1275 }
1276 }
1277
1278 logger.Infow(ctx, "Single_set_value_request failed ", log.Fields{"request": request})
1279 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_INVALID_DEVICE_ID), nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001280}
1281
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301282// StartOmciTest not implemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001283func (oo *OpenONUAC) StartOmciTest(ctx context.Context, test *ca.OMCITest) (*omci.TestResponse, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001284 return nil, errors.New("unImplemented")
1285}
1286
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301287// SuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001288func (oo *OpenONUAC) SuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1289 return nil, errors.New("unImplemented")
1290}
1291
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301292// UnSuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001293func (oo *OpenONUAC) UnSuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1294 return nil, errors.New("unImplemented")
1295}
1296
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301297// GetImageDownloadStatus is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001298func (oo *OpenONUAC) GetImageDownloadStatus(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001299 return nil, errors.New("unImplemented")
1300}
1301
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301302// CancelImageDownload is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001303func (oo *OpenONUAC) CancelImageDownload(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001304 return nil, errors.New("unImplemented")
1305}
1306
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301307// RevertImageUpdate is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001308func (oo *OpenONUAC) RevertImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001309 return nil, errors.New("unImplemented")
1310}
1311
1312// UpdateFlowsBulk is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001313func (oo *OpenONUAC) UpdateFlowsBulk(ctx context.Context, flows *ca.BulkFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001314 return nil, errors.New("unImplemented")
1315}
1316
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301317// SelfTestDevice unimplented
khenaidoo7d3c5582021-08-11 18:09:44 -04001318func (oo *OpenONUAC) SelfTestDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
1319 return nil, errors.New("unImplemented")
1320}
1321
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301322// SendPacketOut sends packet out to the device
khenaidoo42dcdfd2021-10-19 17:34:12 -04001323func (oo *OpenONUAC) SendPacketOut(ctx context.Context, packet *ca.PacketOut) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001324 return nil, errors.New("unImplemented")
1325}
1326
1327// EnablePort to Enable PON/NNI interface - seems not to be used/required according to python code
1328func (oo *OpenONUAC) EnablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1329 return nil, errors.New("unImplemented")
1330}
1331
1332// DisablePort to Disable pon/nni interface - seems not to be used/required according to python code
1333func (oo *OpenONUAC) DisablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1334 return nil, errors.New("unImplemented")
1335}
1336
1337// GetExtValue - unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001338func (oo *OpenONUAC) GetExtValue(ctx context.Context, extInfo *ca.GetExtValueMessage) (*extension.ReturnValues, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001339 return nil, errors.New("unImplemented")
1340}
1341
1342// ChildDeviceLost - unimplemented
1343func (oo *OpenONUAC) ChildDeviceLost(ctx context.Context, childDevice *voltha.Device) (*empty.Empty, error) {
1344 return nil, errors.New("unImplemented")
1345}
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +00001346
1347// GetSupportedFsms - TODO: add comment
1348func (oo *OpenONUAC) GetSupportedFsms() *cmn.OmciDeviceFsms {
1349 return oo.pSupportedFsms
1350}
1351
1352// LockMutexMibTemplateGenerated - TODO: add comment
1353func (oo *OpenONUAC) LockMutexMibTemplateGenerated() {
1354 oo.mutexMibTemplateGenerated.Lock()
1355}
1356
1357// UnlockMutexMibTemplateGenerated - TODO: add comment
1358func (oo *OpenONUAC) UnlockMutexMibTemplateGenerated() {
1359 oo.mutexMibTemplateGenerated.Unlock()
1360}
1361
1362// GetMibTemplatesGenerated - TODO: add comment
1363func (oo *OpenONUAC) GetMibTemplatesGenerated(mibTemplatePath string) (value bool, exist bool) {
1364 value, exist = oo.mibTemplatesGenerated[mibTemplatePath]
1365 return value, exist
1366}
1367
1368// SetMibTemplatesGenerated - TODO: add comment
1369func (oo *OpenONUAC) SetMibTemplatesGenerated(mibTemplatePath string, value bool) {
1370 oo.mibTemplatesGenerated[mibTemplatePath] = value
1371}
1372
1373// RLockMutexDeviceHandlersMap - TODO: add comment
1374func (oo *OpenONUAC) RLockMutexDeviceHandlersMap() {
1375 oo.mutexDeviceHandlersMap.RLock()
1376}
1377
1378// RUnlockMutexDeviceHandlersMap - TODO: add comment
1379func (oo *OpenONUAC) RUnlockMutexDeviceHandlersMap() {
1380 oo.mutexDeviceHandlersMap.RUnlock()
1381}
1382
1383// GetDeviceHandler - TODO: add comment
1384func (oo *OpenONUAC) GetDeviceHandler(deviceID string) (value cmn.IdeviceHandler, exist bool) {
1385 value, exist = oo.deviceHandlers[deviceID]
1386 return value, exist
1387}
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +05301388
1389// GetONUMIBDBMap - Returns the Map corresponding to ONT type and the MIB common Instance.
1390func (oo *OpenONUAC) GetONUMIBDBMap() devdb.OnuMCmnMEDBMap {
1391 return oo.MibDatabaseMap
1392}
1393
1394// RLockMutexMIBDatabaseMap acquires a read lock on the mutex associated with the MIBDatabaseMap.
1395func (oo *OpenONUAC) RLockMutexMIBDatabaseMap() {
1396 oo.mutexMibDatabaseMap.RLock()
1397}
1398
1399// RUnlockMutexMIBDatabaseMap releases the read lock on the mutex associated with the MIBDatabaseMap.
1400func (oo *OpenONUAC) RUnlockMutexMIBDatabaseMap() {
1401 oo.mutexMibDatabaseMap.RUnlock()
1402}
1403
1404// LockMutexMIBDatabaseMap locks the mutex associated with the MIBDatabaseMap.
1405// Should be called before any operations that modify or read from the MIBDatabaseMap.
1406func (oo *OpenONUAC) LockMutexMIBDatabaseMap() {
1407 oo.mutexMibDatabaseMap.Lock()
1408}
1409
1410// UnlockMutexMIBDatabaseMap unlocks the mutex associated with the MIBDatabaseMap.
1411// Should be called after completing operations that require exclusive access
1412// to the MIBDatabaseMap, ensuring the mutex is released for other goroutines.
1413func (oo *OpenONUAC) UnlockMutexMIBDatabaseMap() {
1414 oo.mutexMibDatabaseMap.Unlock()
1415}
1416
1417// CreateEntryAtMibDatabaseMap adds an entry to the MibDatabaseMap if it doesn't exist
1418func (oo *OpenONUAC) CreateEntryAtMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, error) {
1419 oo.mutexMibDatabaseMap.Lock()
1420 defer oo.mutexMibDatabaseMap.Unlock()
1421
1422 // Check if the key already exists
1423 if mibEntry, exists := oo.MibDatabaseMap[key]; exists {
1424 logger.Warnw(ctx, "Entry already exists in MIB Database Map", log.Fields{"remote-client": key})
1425 return mibEntry, fmt.Errorf("entry already exists for key: %s", key)
1426 }
1427
1428 value := devdb.NewOnuCmnMEDB(ctx)
1429
1430 logger.Infow(ctx, "Created a new Common MIB Database Entry", log.Fields{"remote-client": key})
1431 oo.MibDatabaseMap[key] = value
1432
1433 return value, nil
1434}
1435
1436// FetchEntryFromMibDatabaseMap fetches a references to common ME DB for a MIB Template from the MibDatabaseMap
1437// If a valid entry exists returns pointer to cmnDB else returns nil.
1438func (oo *OpenONUAC) FetchEntryFromMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, bool) {
1439 oo.mutexMibDatabaseMap.RLock()
1440 defer oo.mutexMibDatabaseMap.RUnlock()
1441 value, exists := oo.MibDatabaseMap[key]
1442 if !exists {
1443 return nil, false
1444 }
1445 return value, true
1446
1447}
1448
1449// ResetEntryFromMibDatabaseMap resets the ME values from the Maps.
1450func (oo *OpenONUAC) ResetEntryFromMibDatabaseMap(ctx context.Context, key string) {
1451 oo.mutexMibDatabaseMap.RLock()
1452 onuCmnMEDB, exists := oo.MibDatabaseMap[key]
1453 oo.mutexMibDatabaseMap.RUnlock()
1454 if exists {
1455 // Lock the MeDbLock to ensure thread-safe operation
1456 onuCmnMEDB.MeDbLock.Lock()
1457 defer onuCmnMEDB.MeDbLock.Unlock()
1458
1459 // Reset the MeDb and UnknownMeAndAttribDb maps
1460 onuCmnMEDB.MeDb = make(devdb.MeDbMap)
1461 onuCmnMEDB.UnknownMeAndAttribDb = make(devdb.UnknownMeAndAttribDbMap)
1462
1463 }
1464}
1465
1466// DeleteEntryFromMibDatabaseMap deletes an entry from the MibDatabaseMap
1467func (oo *OpenONUAC) DeleteEntryFromMibDatabaseMap(key string) {
1468 oo.mutexMibDatabaseMap.Lock()
1469 defer oo.mutexMibDatabaseMap.Unlock()
1470 delete(oo.MibDatabaseMap, key)
1471}