blob: 75ba35e17acb0bec4b66e24b45c84ac00fab490e [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 Chawlac07fda02020-12-09 16:21:21 +053067 eventProxy eventif.EventProxy
mpagenkoaf801632020-07-03 10:00:42 +000068 kvClient kvstore.Client
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053069 deviceHandlers map[string]*deviceHandler
70 deviceHandlersCreateChan map[string]chan bool //channels for deviceHandler create events
71 coreClient *vgrpc.Client
72 parentAdapterClients map[string]*vgrpc.Client
73 reachableFromRemote map[string]*reachabilityFromRemote
Matteo Scandolof1f39a72020-11-24 12:08:11 -080074 cm *conf.ConfigManager
Holger Hildebrandtfa074992020-03-27 15:42:06 +000075 config *config.AdapterFlags
Holger Hildebrandt61b24d02020-11-16 13:36:40 +000076 mibTemplatesGenerated map[string]bool
Holger Hildebrandtfa074992020-03-27 15:42:06 +000077 exitChannel chan int
khenaidoo55cebc62021-12-08 14:44:41 -050078 pSupportedFsms *cmn.OmciDeviceFsms
khenaidoo55cebc62021-12-08 14:44:41 -050079 pDownloadManager *swupg.AdapterDownloadManager
80 pFileManager *swupg.FileDownloadManager //let coexist 'old and new' DownloadManager as long as 'old' does not get obsolete
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053081 MibDatabaseMap devdb.OnuMCmnMEDBMap
82 KVStoreAddress string
83 KVStoreType string
84 numOnus int
85 KVStoreTimeout time.Duration
86 HeartbeatCheckInterval time.Duration
87 HeartbeatFailReportInterval time.Duration
88 maxTimeoutInterAdapterComm time.Duration
89 maxTimeoutReconciling time.Duration
khenaidoo55cebc62021-12-08 14:44:41 -050090 mibAuditInterval time.Duration
91 omciTimeout int // in seconds
92 alarmAuditInterval time.Duration
93 dlToOnuTimeout4M time.Duration
94 rpcTimeout time.Duration
95 maxConcurrentFlowsPerUni int
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053096 mutexDeviceHandlersMap sync.RWMutex
97 lockParentAdapterClients sync.RWMutex
98 lockReachableFromRemote sync.RWMutex
99 mutexMibTemplateGenerated sync.RWMutex
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +0530100 mutexMibDatabaseMap sync.RWMutex
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530101 AcceptIncrementalEvto bool
102 MetricsEnabled bool
103 ExtendedOmciSupportEnabled bool
104 skipOnuConfig bool
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{
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530145 "mib-synchronizer": cmn.ActivityDescr{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000146 //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})
Himani Chawla6d2ae152020-09-02 13:11:20 +0530267 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000268 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400269 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530270 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 +0000271 handler.device = device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400272 if err := handler.updateDeviceStateInCore(log.WithSpanFromContext(context.Background(), ctx), &ca.DeviceStateFilter{
khenaidoo7d3c5582021-08-11 18:09:44 -0400273 DeviceId: device.Id,
274 OperStatus: voltha.OperStatus_RECONCILING,
275 ConnStatus: device.ConnectStatus,
276 }); err != nil {
277 return nil, fmt.Errorf("not able to update device state to reconciling. Err : %s", err.Error())
Maninderb5187552021-03-23 22:23:42 +0530278 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400279 // Setup the grpc communication with the parent adapter
280 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
281 // TODO: Cleanup on failure needed
282 return nil, err
283 }
Akash Soni931f9b92024-12-11 18:36:36 +0530284 // Add device handler to map only if adapter and core connections are up
285 oo.addDeviceHandlerToMap(ctx, handler)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000286 handler.StartReconciling(log.WithSpanFromContext(context.Background(), ctx), false)
khenaidoo7d3c5582021-08-11 18:09:44 -0400287 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), handler.device)
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000288 // reconcilement will be continued after onu-device entry is added
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000289 } else {
nikesh.krishnan9d2bbf72023-12-11 07:36:57 +0530290 logger.Warnf(ctx, "device-already-reconciled-or-active", log.Fields{"device-id": device.Id, "parent-id": device.ParentId})
291 return &empty.Empty{}, status.Errorf(codes.AlreadyExists, "handler exists: %s", device.Id)
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000292 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400293 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000294}
295
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530296// DisableDevice disables the given device
khenaidoo7d3c5582021-08-11 18:09:44 -0400297func (oo *OpenONUAC) DisableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000298 logger.Infow(ctx, "disable-device", log.Fields{"device-id": device.Id})
299 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400300 go handler.disableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
301 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300302 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000303 logger.Warnw(ctx, "no handler found for device-disable", log.Fields{"device-id": device.Id})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530304 return nil, fmt.Errorf("handler-not-found-%s", device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000305}
306
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530307// ReEnableDevice enables the onu device after disable
khenaidoo7d3c5582021-08-11 18:09:44 -0400308func (oo *OpenONUAC) ReEnableDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000309 logger.Infow(ctx, "reenable-device", log.Fields{"device-id": device.Id})
310 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400311 go handler.reEnableDevice(log.WithSpanFromContext(context.Background(), ctx), device)
312 return &empty.Empty{}, nil
ozgecanetsiafce57b12020-05-25 14:39:35 +0300313 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000314 logger.Warnw(ctx, "no handler found for device-reenable", log.Fields{"device-id": device.Id})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530315 return nil, fmt.Errorf("handler-not-found-%s", device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000316}
317
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530318// RebootDevice reboots the given device
khenaidoo7d3c5582021-08-11 18:09:44 -0400319func (oo *OpenONUAC) RebootDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000320 logger.Infow(ctx, "reboot-device", log.Fields{"device-id": device.Id})
321 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400322 go handler.rebootDevice(log.WithSpanFromContext(context.Background(), ctx), true, device) //reboot request with device checking
323 return &empty.Empty{}, nil
ozgecanetsiae11479f2020-07-06 09:44:47 +0300324 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000325 logger.Warnw(ctx, "no handler found for device-reboot", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400326 return nil, fmt.Errorf("handler-not-found-for-device: %s", device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000327}
328
khenaidoo7d3c5582021-08-11 18:09:44 -0400329// DeleteDevice deletes the given device
330func (oo *OpenONUAC) DeleteDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
331 nctx := log.WithSpanFromContext(context.Background(), ctx)
khenaidoo7d3c5582021-08-11 18:09:44 -0400332 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 +0000333
dbainbri4d3a0dc2020-12-02 00:33:42 +0000334 if handler := oo.getDeviceHandler(ctx, device.Id, false); handler != nil {
Girish Gowdra0e533642021-03-02 22:02:51 -0800335 var errorsList []error
Holger Hildebrandtff05b682021-03-16 15:02:05 +0000336
337 handler.mutexDeletionInProgressFlag.Lock()
338 handler.deletionInProgress = true
339 handler.mutexDeletionInProgressFlag.Unlock()
340
Girish Gowdraabcceb12022-04-13 23:35:22 -0700341 // 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 +0530342 if handler.pOnuMetricsMgr != nil {
343 handler.pOnuMetricsMgr.SetdeviceDeletionInProgress(true)
344 }
praneeth nalmasf405e962023-08-07 15:02:03 +0530345
346 handler.deviceDeleteCommChan <- true
Holger Hildebrandt60652202021-11-02 11:09:36 +0000347 if err := handler.resetFsms(ctx, true); err != nil {
348 errorsList = append(errorsList, err)
349 }
Girish Gowdrae95687a2021-09-08 16:30:58 -0700350 for _, uni := range handler.uniEntityMap {
351 if handler.GetFlowMonitoringIsRunning(uni.UniID) {
352 handler.stopFlowMonitoringRoutine[uni.UniID] <- true
353 logger.Debugw(ctx, "sent stop signal to self flow monitoring routine", log.Fields{"device-id": device.Id})
354 }
355 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000356 //don't leave any garbage in kv-store
357 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
358 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000359 }
Holger Hildebrandte7cc6092022-02-01 11:37:03 +0000360 oo.deleteDeviceHandlerToMap(handler)
361 go handler.PrepareForGarbageCollection(ctx, handler.DeviceID)
Holger Hildebrandt60652202021-11-02 11:09:36 +0000362
Girish Gowdra0e533642021-03-02 22:02:51 -0800363 if len(errorsList) > 0 {
364 logger.Errorw(ctx, "one-or-more-error-during-device-delete", log.Fields{"device-id": device.Id})
khenaidoo7d3c5582021-08-11 18:09:44 -0400365 return nil, fmt.Errorf("one-or-more-error-during-device-delete, errors:%v", errorsList)
Girish Gowdra0e533642021-03-02 22:02:51 -0800366 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400367 return &empty.Empty{}, nil
Holger Hildebrandt9ca8b132020-08-07 14:45:03 +0000368 }
Holger Hildebrandt60652202021-11-02 11:09:36 +0000369 logger.Infow(ctx, "no handler found for device-deletion - trying to delete remaining data in the kv-store ", log.Fields{"device-id": device.Id})
370
Holger Hildebrandtc69f0742021-11-16 13:48:00 +0000371 if err := oo.forceDeleteDeviceKvData(ctx, device.Id); err != nil {
372 return nil, err
Holger Hildebrandt60652202021-11-02 11:09:36 +0000373 }
374 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000375}
376
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530377// UpdateFlowsIncrementally updates (add/remove) the flows on a given device
khenaidoo42dcdfd2021-10-19 17:34:12 -0400378func (oo *OpenONUAC) UpdateFlowsIncrementally(ctx context.Context, incrFlows *ca.IncrementalFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400379 logger.Infow(ctx, "update-flows-incrementally", log.Fields{"device-id": incrFlows.Device.Id})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000380
mpagenkofc4f56e2020-11-04 17:17:49 +0000381 //flow config is relayed to handler even if the device might be in some 'inactive' state
382 // let the handler or related FSM's decide, what to do with the modified flow state info
383 // 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 +0000384
385 // For now, there is no support for group changes (as in the actual Py-adapter code)
mpagenkofc4f56e2020-11-04 17:17:49 +0000386 // but processing is continued for flowUpdate possibly also set in the request
khenaidoo7d3c5582021-08-11 18:09:44 -0400387 if incrFlows.Groups.ToAdd != nil && incrFlows.Groups.ToAdd.Items != nil {
388 logger.Warnw(ctx, "Update-flow-incr: group add not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000389 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400390 if incrFlows.Groups.ToRemove != nil && incrFlows.Groups.ToRemove.Items != nil {
391 logger.Warnw(ctx, "Update-flow-incr: group remove not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000392 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400393 if incrFlows.Groups.ToUpdate != nil && incrFlows.Groups.ToUpdate.Items != nil {
394 logger.Warnw(ctx, "Update-flow-incr: group update not supported (ignored)", log.Fields{"device-id": incrFlows.Device.Id})
mpagenkodff5dda2020-08-28 11:52:01 +0000395 }
396
khenaidoo7d3c5582021-08-11 18:09:44 -0400397 if handler := oo.getDeviceHandler(ctx, incrFlows.Device.Id, false); handler != nil {
398 if err := handler.FlowUpdateIncremental(log.WithSpanFromContext(context.Background(), ctx), incrFlows.Flows, incrFlows.Groups, incrFlows.FlowMetadata); err != nil {
399 return nil, err
400 }
401 return &empty.Empty{}, nil
mpagenkodff5dda2020-08-28 11:52:01 +0000402 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400403 logger.Warnw(ctx, "no handler found for incremental flow update", log.Fields{"device-id": incrFlows.Device.Id})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530404 return nil, fmt.Errorf("handler-not-found-%s", incrFlows.Device.Id)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000405}
406
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530407// UpdatePmConfig returns PmConfigs nil or error
khenaidoo42dcdfd2021-10-19 17:34:12 -0400408func (oo *OpenONUAC) UpdatePmConfig(ctx context.Context, configs *ca.PmConfigsInfo) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400409 logger.Infow(ctx, "update-pm-config", log.Fields{"device-id": configs.DeviceId})
410 if handler := oo.getDeviceHandler(ctx, configs.DeviceId, false); handler != nil {
411 if err := handler.updatePmConfig(log.WithSpanFromContext(context.Background(), ctx), configs.PmConfigs); err != nil {
412 return nil, err
413 }
414 return &empty.Empty{}, nil
Girish Gowdrae09a6202021-01-12 18:10:59 -0800415 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400416 logger.Warnw(ctx, "no handler found for update-pm-config", log.Fields{"device-id": configs.DeviceId})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530417 return nil, fmt.Errorf("handler-not-found-%s", configs.DeviceId)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000418}
419
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530420// DownloadImage requests downloading some image according to indications as given in request
421// The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400422func (oo *OpenONUAC) DownloadImage(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400423 ctx = log.WithSpanFromContext(context.Background(), ctx)
424 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt52f271b2022-06-02 09:32:27 +0000425 if strings.Contains(imageInfo.Image.Url, "https:") {
426 return nil, errors.New("image download via https not supported")
427 }
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000428 if !oo.pDownloadManager.ImageExists(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400429 logger.Debugw(ctx, "start image download", log.Fields{"image-description": imageInfo.Image})
mpagenko15ff4a52021-03-02 10:09:20 +0000430 // Download_image is not supposed to be blocking, anyway let's call the DownloadManager still synchronously to detect 'fast' problems
431 // the download itself is later done in background
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000432 if err := oo.pDownloadManager.StartDownload(ctx, imageInfo.Image); err != nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400433 return nil, err
434 }
435 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000436 }
437 // image already exists
khenaidoo7d3c5582021-08-11 18:09:44 -0400438 logger.Debugw(ctx, "image already downloaded", log.Fields{"image-description": imageInfo.Image})
439 return imageInfo.Image, nil
mpagenkoc8bba412021-01-15 15:38:44 +0000440 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400441
442 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000443}
444
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530445// ActivateImageUpdate requests downloading some Onu Software image to the ONU via OMCI
446//
447// according to indications as given in request and on success activate the image on the ONU
448//
449// The ImageDownload needs to be called `request`due to library reflection requirements
khenaidoo42dcdfd2021-10-19 17:34:12 -0400450func (oo *OpenONUAC) ActivateImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400451 if imageInfo != nil && imageInfo.Image != nil && imageInfo.Image.Name != "" {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000452 if oo.pDownloadManager.ImageLocallyDownloaded(ctx, imageInfo.Image) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400453 if handler := oo.getDeviceHandler(ctx, imageInfo.Device.Id, false); handler != nil {
mpagenko15ff4a52021-03-02 10:09:20 +0000454 logger.Debugw(ctx, "image download on omci requested", log.Fields{
khenaidoo7d3c5582021-08-11 18:09:44 -0400455 "image-description": imageInfo.Image, "device-id": imageInfo.Device.Id})
456 if err := handler.doOnuSwUpgrade(ctx, imageInfo.Image, oo.pDownloadManager); err != nil {
457 return nil, err
458 }
459 return imageInfo.Image, nil
mpagenko15ff4a52021-03-02 10:09:20 +0000460 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400461 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": imageInfo.Device.Id})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530462 return nil, fmt.Errorf("handler-not-found - device-id: %s", imageInfo.Device.Id)
mpagenko057889c2021-01-21 16:51:58 +0000463 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400464 logger.Debugw(ctx, "image not yet downloaded on activate request", log.Fields{"image-description": imageInfo.Image})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530465 return nil, fmt.Errorf("image-not-yet-downloaded - device-id: %s", imageInfo.Device.Id)
mpagenkoc8bba412021-01-15 15:38:44 +0000466 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400467 return nil, errors.New("invalid image definition")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000468}
469
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530470// GetSingleValue handles the core request to retrieve uni status
khenaidoo7d3c5582021-08-11 18:09:44 -0400471func (oo *OpenONUAC) GetSingleValue(ctx context.Context, request *extension.SingleGetValueRequest) (*extension.SingleGetValueResponse, error) {
kesavandfdf77632021-01-26 23:40:33 -0500472 logger.Infow(ctx, "Single_get_value_request", log.Fields{"request": request})
473
474 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
475 switch reqType := request.GetRequest().GetRequest().(type) {
476 case *extension.GetValueRequest_UniInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000477 return handler.GetUniPortStatus(ctx, reqType.UniInfo), nil
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700478 case *extension.GetValueRequest_OnuOpticalInfo:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000479 CommChan := make(chan cmn.Message)
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700480 respChan := make(chan extension.SingleGetValueResponse)
481 // Initiate the self test request
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000482 if err := handler.pSelfTestHdlr.SelfTestRequestStart(ctx, *request, CommChan, respChan); err != nil {
Girish Gowdra6afb56a2021-04-27 17:47:57 -0700483 return &extension.SingleGetValueResponse{
484 Response: &extension.GetValueResponse{
485 Status: extension.GetValueResponse_ERROR,
486 ErrReason: extension.GetValueResponse_INTERNAL_ERROR,
487 },
488 }, err
489 }
490 // The timeout handling is already implemented in omci_self_test_handler module
491 resp := <-respChan
492 return &resp, nil
Himani Chawla43f95ff2021-06-03 00:24:12 +0530493 case *extension.GetValueRequest_OnuInfo:
494 return handler.getOnuOMCICounters(ctx, reqType.OnuInfo), nil
Holger Hildebrandt66af5ce2022-09-07 13:38:02 +0000495 case *extension.GetValueRequest_OnuOmciStats:
496 return handler.getOnuOMCIStats(ctx)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530497 case *extension.GetValueRequest_OnuActiveAlarms:
498 resp := handler.getOnuActiveAlarms(ctx)
499 logger.Infow(ctx, "Received response for on demand active alarms request ", log.Fields{"response": resp})
500 return resp, nil
Akash Reddy Kankanalac28f0e22025-06-16 11:00:55 +0530501 case *extension.GetValueRequest_OnuAllocGemStats:
502 resp := handler.getONUGEMStatsInfo(ctx)
503 logger.Infow(ctx, "Received response for on demand active alarms request ", log.Fields{"response": resp})
504 return resp, nil
kesavandfdf77632021-01-26 23:40:33 -0500505 default:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000506 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_UNSUPPORTED), nil
kesavandfdf77632021-01-26 23:40:33 -0500507 }
508 }
509 logger.Errorw(ctx, "Single_get_value_request failed ", log.Fields{"request": request})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000510 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_INVALID_DEVICE_ID), nil
mpagenkoc8bba412021-01-15 15:38:44 +0000511}
512
mpagenko83144272021-04-27 10:06:22 +0000513//if update >= 4.3.0
mpagenkoc26d4c02021-05-06 14:27:57 +0000514// Note: already with the implementation of the 'old' download interface problems were detected when the argument name used here is not the same
515// as defined in the adapter interface file. That sounds strange and the effects were strange as well.
516// The reason for that was never finally investigated.
517// To be on the safe side argument names are left here always as defined in iAdapter.go .
mpagenko83144272021-04-27 10:06:22 +0000518
khenaidoo7d3c5582021-08-11 18:09:44 -0400519// DownloadOnuImage downloads (and optionally activates and commits) the indicated ONU image to the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530520//
521// if the image is not yet present on the adapter it has to be automatically downloaded
khenaidoo7d3c5582021-08-11 18:09:44 -0400522func (oo *OpenONUAC) DownloadOnuImage(ctx context.Context, request *voltha.DeviceImageDownloadRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000523 if request != nil && len((*request).DeviceId) > 0 && (*request).Image.Version != "" {
Holger Hildebrandt52f271b2022-06-02 09:32:27 +0000524 if strings.Contains((*request).Image.Url, "https:") {
525 return nil, errors.New("image download via https not supported")
526 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000527 loResponse := voltha.DeviceImageResponse{}
528 imageIdentifier := (*request).Image.Version
mpagenkoc497ee32021-11-10 17:30:20 +0000529 downloadStartDone := false
mpagenkoc26d4c02021-05-06 14:27:57 +0000530 firstDevice := true
531 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000532 var onuVolthaDevice *voltha.Device
533 var devErr error
mpagenkoc26d4c02021-05-06 14:27:57 +0000534 for _, pCommonID := range (*request).DeviceId {
mpagenko38662d02021-08-11 09:45:19 +0000535 vendorIDMatch := true
mpagenkoc26d4c02021-05-06 14:27:57 +0000536 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000537 loDeviceImageState := voltha.DeviceImageState{}
538 loDeviceImageState.DeviceId = loDeviceID
539 loImageState := voltha.ImageState{}
540 loDeviceImageState.ImageState = &loImageState
541 loDeviceImageState.ImageState.Version = (*request).Image.Version
mpagenko38662d02021-08-11 09:45:19 +0000542
mpagenko59862f02021-10-11 08:53:18 +0000543 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400544 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000545 if handler != nil {
546 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
547 } else {
548 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
549 devErr = errors.New("no handler found for device-id")
khenaidoo7d3c5582021-08-11 18:09:44 -0400550 }
mpagenko59862f02021-10-11 08:53:18 +0000551 if devErr != nil || onuVolthaDevice == nil {
552 logger.Warnw(ctx, "Failed to fetch ONU device for image download",
553 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000554 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
555 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //proto restriction, better option: 'INVALID_DEVICE'
mpagenkoc26d4c02021-05-06 14:27:57 +0000556 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000557 } else {
mpagenko38662d02021-08-11 09:45:19 +0000558 if firstDevice {
559 //start/verify download of the image to the adapter based on first found device only
560 // use the OnuVendor identification from first given device
mpagenkoc497ee32021-11-10 17:30:20 +0000561
562 // note: if the request was done for a list of devices on the Voltha interface, rwCore
563 // 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 +0000564 firstDevice = false
565 vendorID = onuVolthaDevice.VendorId
566 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
mpagenkoc497ee32021-11-10 17:30:20 +0000567 logger.Infow(ctx, "download request for file",
568 log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000569
mpagenkoc497ee32021-11-10 17:30:20 +0000570 // call the StartDownload synchronously to detect 'immediate' download problems
571 // the real download itself is later done in background
572 if fileState, err := oo.pFileManager.StartDownload(ctx, imageIdentifier, (*request).Image.Url); err == nil {
mpagenko38662d02021-08-11 09:45:19 +0000573 // note: If the image (with vendorId+name) has already been downloaded before from some other
mpagenkoc497ee32021-11-10 17:30:20 +0000574 // valid URL, the current download request is not executed (current code delivers URL error).
575 // If the operators want to ensure that the new URL
mpagenko38662d02021-08-11 09:45:19 +0000576 // is really used, then they first have to use the 'abort' API to remove the existing image!
577 // (abort API can be used also after some successful download to just remove the image from adapter)
mpagenkoc497ee32021-11-10 17:30:20 +0000578 if fileState == swupg.CFileStateDlSucceeded || fileState == swupg.CFileStateDlStarted {
579 downloadStartDone = true
580 } //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 +0000581 }
582 } else {
583 //for all following devices verify the matching vendorID
584 if onuVolthaDevice.VendorId != vendorID {
585 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
586 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
587 vendorIDMatch = false
588 }
589 }
mpagenkoc497ee32021-11-10 17:30:20 +0000590 if downloadStartDone && vendorIDMatch {
mpagenko38662d02021-08-11 09:45:19 +0000591 // start the ONU download activity for each possible device
mpagenkoc497ee32021-11-10 17:30:20 +0000592 logger.Infow(ctx, "request image download to ONU on omci ", log.Fields{
mpagenko59862f02021-10-11 08:53:18 +0000593 "image-id": imageIdentifier, "device-id": loDeviceID})
594 //onu upgrade handling called in background without immediate error evaluation here
595 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
596 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
597 go handler.onuSwUpgradeAfterDownload(ctx, request, oo.pFileManager, imageIdentifier)
598 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_STARTED
599 loDeviceImageState.ImageState.Reason = voltha.ImageState_NO_ERROR
600 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenko38662d02021-08-11 09:45:19 +0000601 } else {
602 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
mpagenkoc497ee32021-11-10 17:30:20 +0000603 if !downloadStartDone {
604 //based on above fileState more descriptive error codes would be possible, e.g
605 // IMAGE_EXISTS_WITH_DIFFERENT_URL - would require proto buf update
mpagenko38662d02021-08-11 09:45:19 +0000606 loDeviceImageState.ImageState.Reason = voltha.ImageState_INVALID_URL
607 } else { //only logical option is !vendorIDMatch
608 loDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
609 }
610 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
611 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000612 }
mpagenko2f2f2362021-06-07 08:25:22 +0000613 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000614 } //for all requested devices
mpagenkoc26d4c02021-05-06 14:27:57 +0000615 pImageResp := &loResponse
616 return pImageResp, nil
617 }
618 return nil, errors.New("invalid image download parameters")
mpagenko83144272021-04-27 10:06:22 +0000619}
620
khenaidoo7d3c5582021-08-11 18:09:44 -0400621// GetOnuImageStatus delivers the adapter-related information about the download/activation/commitment
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530622//
623// status for the requested image
khenaidoo7d3c5582021-08-11 18:09:44 -0400624func (oo *OpenONUAC) GetOnuImageStatus(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000625 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
626 loResponse := voltha.DeviceImageResponse{}
mpagenkoaa3afe92021-05-21 16:20:58 +0000627 imageIdentifier := (*in).Version
mpagenko38662d02021-08-11 09:45:19 +0000628 var vendorIDSet bool
mpagenkoaa3afe92021-05-21 16:20:58 +0000629 firstDevice := true
630 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000631 var onuVolthaDevice *voltha.Device
632 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000633 for _, pCommonID := range (*in).DeviceId {
634 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400635 pDeviceImageState := &voltha.DeviceImageState{DeviceId: loDeviceID}
mpagenko59862f02021-10-11 08:53:18 +0000636 vendorIDSet = false
637 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400638 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000639 if handler != nil {
640 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
641 } else {
642 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
643 devErr = errors.New("no handler found for device-id")
mpagenko38662d02021-08-11 09:45:19 +0000644 }
mpagenko59862f02021-10-11 08:53:18 +0000645 if devErr != nil || onuVolthaDevice == nil {
mpagenkoaa3afe92021-05-21 16:20:58 +0000646 logger.Warnw(ctx, "Failed to fetch Onu device to get image status",
mpagenko59862f02021-10-11 08:53:18 +0000647 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000648 pImageState := &voltha.ImageState{
649 Version: (*in).Version,
650 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //no statement about last activity possible
651 Reason: voltha.ImageState_UNKNOWN_ERROR, //something like "DEVICE_NOT_EXISTS" would be better (proto def)
652 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
mpagenkoaa3afe92021-05-21 16:20:58 +0000653 }
mpagenko38662d02021-08-11 09:45:19 +0000654 pDeviceImageState.ImageState = pImageState
mpagenkoaa3afe92021-05-21 16:20:58 +0000655 } else {
mpagenko38662d02021-08-11 09:45:19 +0000656 if firstDevice {
657 //start/verify download of the image to the adapter based on first found device only
658 // use the OnuVendor identification from first given device
659 firstDevice = false
660 vendorID = onuVolthaDevice.VendorId
661 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
662 vendorIDSet = true
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000663 logger.Debugw(ctx, "status request for image", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000664 } else {
665 //for all following devices verify the matching vendorID
666 if onuVolthaDevice.VendorId != vendorID {
667 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000668 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko38662d02021-08-11 09:45:19 +0000669 } else {
670 vendorIDSet = true
671 }
672 }
673 if !vendorIDSet {
674 pImageState := &voltha.ImageState{
675 Version: (*in).Version,
676 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //can't be sure that download for this device was really tried
677 Reason: voltha.ImageState_VENDOR_DEVICE_MISMATCH,
678 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
679 }
680 pDeviceImageState.ImageState = pImageState
681 } else {
khenaidoo7d3c5582021-08-11 18:09:44 -0400682 logger.Debugw(ctx, "image status request for", log.Fields{
683 "image-id": imageIdentifier, "device-id": loDeviceID})
684 //status request is called synchronously to collect the indications for all concerned devices
685 pDeviceImageState.ImageState = handler.requestOnuSwUpgradeState(ctx, imageIdentifier, (*in).Version)
mpagenko38662d02021-08-11 09:45:19 +0000686 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000687 }
688 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000689 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000690 pImageResp := &loResponse
691 return pImageResp, nil
692 }
693 return nil, errors.New("invalid image status request parameters")
mpagenko83144272021-04-27 10:06:22 +0000694}
695
khenaidoo7d3c5582021-08-11 18:09:44 -0400696// AbortOnuImageUpgrade stops the actual download/activation/commitment process (on next possibly step)
697func (oo *OpenONUAC) AbortOnuImageUpgrade(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000698 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
699 loResponse := voltha.DeviceImageResponse{}
700 imageIdentifier := (*in).Version
701 firstDevice := true
702 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000703 var vendorIDSet bool
704 var onuVolthaDevice *voltha.Device
705 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000706 for _, pCommonID := range (*in).DeviceId {
707 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400708 pDeviceImageState := &voltha.DeviceImageState{}
709 loImageState := voltha.ImageState{}
710 pDeviceImageState.ImageState = &loImageState
mpagenko59862f02021-10-11 08:53:18 +0000711 vendorIDSet = false
712 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400713 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000714 if handler != nil {
715 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
716 } else {
717 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
718 devErr = errors.New("no handler found for device-id")
719 }
720 if devErr != nil || onuVolthaDevice == nil {
721 logger.Warnw(ctx, "Failed to fetch Onu device to abort its download",
722 log.Fields{"device-id": loDeviceID, "err": devErr})
khenaidoo7d3c5582021-08-11 18:09:44 -0400723 pDeviceImageState.DeviceId = loDeviceID
724 pDeviceImageState.ImageState.Version = (*in).Version
mpagenko59862f02021-10-11 08:53:18 +0000725 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
726 pDeviceImageState.ImageState.Reason = voltha.ImageState_CANCELLED_ON_REQUEST //something better could be considered (MissingHandler) - proto
khenaidoo7d3c5582021-08-11 18:09:44 -0400727 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoaa3afe92021-05-21 16:20:58 +0000728 } else {
mpagenko59862f02021-10-11 08:53:18 +0000729 if firstDevice {
730 //start/verify download of the image to the adapter based on first found device only
731 // use the OnuVendor identification from first given device
732 firstDevice = false
733 vendorID = onuVolthaDevice.VendorId
734 vendorIDSet = true
735 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000736 logger.Debugw(ctx, "abort request for file", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko59862f02021-10-11 08:53:18 +0000737 } else {
738 //for all following devices verify the matching vendorID
739 if onuVolthaDevice.VendorId != vendorID {
740 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000741 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko59862f02021-10-11 08:53:18 +0000742 pDeviceImageState.DeviceId = loDeviceID
743 pDeviceImageState.ImageState.Version = (*in).Version
744 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
745 pDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
746 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
747 } else {
748 vendorIDSet = true
749 }
750 }
751 if vendorIDSet {
752 // cancel the ONU upgrade activity for each possible device
753 logger.Debugw(ctx, "image upgrade abort requested", log.Fields{
754 "image-id": imageIdentifier, "device-id": loDeviceID})
755 //upgrade cancel is called synchronously to collect the imageResponse indications for all concerned devices
756 handler.cancelOnuSwUpgrade(ctx, imageIdentifier, (*in).Version, pDeviceImageState)
mpagenkoaa3afe92021-05-21 16:20:58 +0000757 }
758 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000759 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000760 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000761 if !firstDevice {
762 //if at least one valid device was found cancel also a possibly running download to adapter and remove the image
763 // this is to be done after the upgradeOnu cancel activities in order to not subduct the file for still running processes
764 oo.pFileManager.CancelDownload(ctx, imageIdentifier)
765 }
766 pImageResp := &loResponse
767 return pImageResp, nil
768 }
769 return nil, errors.New("invalid image upgrade abort parameters")
mpagenko83144272021-04-27 10:06:22 +0000770}
771
khenaidoo7d3c5582021-08-11 18:09:44 -0400772// GetOnuImages retrieves the ONU SW image status information via OMCI
773func (oo *OpenONUAC) GetOnuImages(ctx context.Context, id *common.ID) (*voltha.OnuImages, error) {
774 logger.Infow(ctx, "Get_onu_images", log.Fields{"device-id": id.Id})
775 if handler := oo.getDeviceHandler(ctx, id.Id, false); handler != nil {
Himani Chawla69992ab2021-07-08 15:13:02 +0530776 images, err := handler.getOnuImages(ctx)
777 if err == nil {
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000778 return images, nil
779 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530780 return nil, fmt.Errorf("%s-%s", err, id.Id)
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000781 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400782 logger.Warnw(ctx, "no handler found for Get_onu_images", log.Fields{"device-id": id.Id})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530783 return nil, fmt.Errorf("handler-not-found-%s", id.Id)
mpagenko83144272021-04-27 10:06:22 +0000784}
785
khenaidoo7d3c5582021-08-11 18:09:44 -0400786// ActivateOnuImage initiates the activation of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530787//
788// precondition: image downloaded and not yet activated or image refers to current inactive image
khenaidoo7d3c5582021-08-11 18:09:44 -0400789func (oo *OpenONUAC) ActivateOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000790 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
791 loResponse := voltha.DeviceImageResponse{}
792 imageIdentifier := (*in).Version
793 //let the deviceHandler find the adequate way of requesting the image activation
794 for _, pCommonID := range (*in).DeviceId {
795 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000796 loDeviceImageState := voltha.DeviceImageState{}
797 loDeviceImageState.DeviceId = loDeviceID
798 loImageState := voltha.ImageState{}
799 loDeviceImageState.ImageState = &loImageState
800 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000801 //compared to download procedure the vendorID (from device) is secondary here
802 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
803 // start image activation activity for each possible device
804 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
805 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
806 logger.Debugw(ctx, "onu image activation requested", log.Fields{
807 "image-id": imageIdentifier, "device-id": loDeviceID})
808 //onu activation handling called in background without immediate error evaluation here
809 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
810 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000811 if pImageStates, err := handler.onuSwActivateRequest(ctx, imageIdentifier, (*in).CommitOnSuccess); err != nil {
812 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
813 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
814 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
815 } else {
816 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
817 loDeviceImageState.ImageState.Reason = pImageStates.Reason
818 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
819 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000820 } else {
821 //cannot start SW activation for requested device
822 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000823 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000824 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
825 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000826 }
mpagenko2f2f2362021-06-07 08:25:22 +0000827 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000828 }
829 pImageResp := &loResponse
830 return pImageResp, nil
831 }
832 return nil, errors.New("invalid image activation parameters")
mpagenko83144272021-04-27 10:06:22 +0000833}
834
khenaidoo7d3c5582021-08-11 18:09:44 -0400835// CommitOnuImage enforces the commitment of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530836//
837// precondition: image activated and not yet committed
khenaidoo7d3c5582021-08-11 18:09:44 -0400838func (oo *OpenONUAC) CommitOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000839 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
840 loResponse := voltha.DeviceImageResponse{}
841 imageIdentifier := (*in).Version
842 //let the deviceHandler find the adequate way of requesting the image activation
843 for _, pCommonID := range (*in).DeviceId {
844 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000845 loDeviceImageState := voltha.DeviceImageState{}
846 loDeviceImageState.DeviceId = loDeviceID
847 loImageState := voltha.ImageState{}
848 loDeviceImageState.ImageState = &loImageState
849 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000850 //compared to download procedure the vendorID (from device) is secondary here
851 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
852 // start image activation activity for each possible device
853 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
854 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
855 logger.Debugw(ctx, "onu image commitment requested", log.Fields{
856 "image-id": imageIdentifier, "device-id": loDeviceID})
857 //onu commitment handling called in background without immediate error evaluation here
858 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
859 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000860 if pImageStates, err := handler.onuSwCommitRequest(ctx, imageIdentifier); err != nil {
mpagenko38662d02021-08-11 09:45:19 +0000861 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
862 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //can be multiple reasons here
mpagenko183647c2021-06-08 15:25:04 +0000863 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
864 } else {
865 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
866 loDeviceImageState.ImageState.Reason = pImageStates.Reason
867 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
868 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000869 } else {
870 //cannot start SW commitment for requested device
871 logger.Warnw(ctx, "no handler found for image commitment", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000872 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000873 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
874 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000875 }
mpagenko2f2f2362021-06-07 08:25:22 +0000876 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000877 }
878 pImageResp := &loResponse
879 return pImageResp, nil
880 }
881 return nil, errors.New("invalid image commitment parameters")
mpagenko83144272021-04-27 10:06:22 +0000882}
883
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000884// Adapter interface required methods ################ end #########
885// #################################################################
khenaidoo7d3c5582021-08-11 18:09:44 -0400886
887/*
888 *
889 * ONU inter adapter service
890 *
891 */
892
893// OnuIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400894func (oo *OpenONUAC) OnuIndication(ctx context.Context, onuInd *ia.OnuIndicationMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400895 logger.Debugw(ctx, "onu-indication", log.Fields{"onu-indication": onuInd})
896
897 if onuInd == nil || onuInd.OnuIndication == nil {
898 return nil, fmt.Errorf("invalid-onu-indication-%v", onuInd)
899 }
900
901 onuIndication := onuInd.OnuIndication
902 onuOperstate := onuIndication.GetOperState()
903 waitForDhInstPresent := false
904 if onuOperstate == "up" {
905 //Race condition (relevant in BBSIM-environment only): Due to unsynchronized processing of olt-adapter and rw_core,
906 //ONU_IND_REQUEST msg by olt-adapter could arrive a little bit earlier than rw_core was able to announce the corresponding
907 //ONU by RPC of Adopt_device(). Therefore it could be necessary to wait with processing of ONU_IND_REQUEST until call of
908 //Adopt_device() arrived and DeviceHandler instance was created
909 waitForDhInstPresent = true
910 }
911 if handler := oo.getDeviceHandler(ctx, onuInd.DeviceId, waitForDhInstPresent); handler != nil {
912 logger.Infow(ctx, "onu-ind-request", log.Fields{"device-id": onuInd.DeviceId,
913 "OnuId": onuIndication.GetOnuId(),
914 "AdminState": onuIndication.GetAdminState(), "OperState": onuOperstate,
915 "SNR": onuIndication.GetSerialNumber()})
916
917 if onuOperstate == "up" {
918 if err := handler.createInterface(ctx, onuIndication); err != nil {
919 return nil, err
920 }
921 return &empty.Empty{}, nil
922 } else if (onuOperstate == "down") || (onuOperstate == "unreachable") {
Holger Hildebrandt68854a82022-09-05 07:00:21 +0000923 if err := handler.UpdateInterface(ctx); err != nil {
ozgecanetsia76db57a2022-02-03 15:32:03 +0300924 return nil, err
925 }
926 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400927 } else {
928 logger.Errorw(ctx, "unknown-onu-ind-request operState", log.Fields{"OnuId": onuIndication.GetOnuId()})
929 return nil, fmt.Errorf("invalidOperState: %s, %s", onuOperstate, onuInd.DeviceId)
930 }
931 }
932 logger.Warnw(ctx, "no handler found for received onu-ind-request", log.Fields{
933 "msgToDeviceId": onuInd.DeviceId})
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530934 return nil, fmt.Errorf("handler-not-found-%s", onuInd.DeviceId)
khenaidoo7d3c5582021-08-11 18:09:44 -0400935}
936
937// OmciIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400938func (oo *OpenONUAC) OmciIndication(ctx context.Context, msg *ia.OmciMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400939 logger.Debugw(ctx, "omci-response", log.Fields{"parent-device-id": msg.ParentDeviceId, "child-device-id": msg.ChildDeviceId})
940
941 if handler := oo.getDeviceHandler(ctx, msg.ChildDeviceId, false); handler != nil {
942 if err := handler.handleOMCIIndication(log.WithSpanFromContext(context.Background(), ctx), msg); err != nil {
943 return nil, err
944 }
945 return &empty.Empty{}, nil
946 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530947 return nil, fmt.Errorf("handler-not-found-%s", msg.ChildDeviceId)
khenaidoo7d3c5582021-08-11 18:09:44 -0400948}
949
950// DownloadTechProfile is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400951func (oo *OpenONUAC) DownloadTechProfile(ctx context.Context, tProfile *ia.TechProfileDownloadMessage) (*empty.Empty, error) {
nikesh.krishnan1ffb8132023-05-23 03:44:13 +0530952 logger.Info(ctx, "download-tech-profile", log.Fields{"device-id": tProfile.DeviceId, "uni-id": tProfile.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400953
954 if handler := oo.getDeviceHandler(ctx, tProfile.DeviceId, false); handler != nil {
Praneeth Nalmas04600be2024-12-08 20:12:32 +0530955 handler.RLockMutexDeletionInProgressFlag()
956 if handler.GetDeletionInProgress() {
957 logger.Warnw(ctx, "Device deletion in progress - avoid processing Tech Profile", log.Fields{"device-id": tProfile.DeviceId})
958
959 handler.RUnlockMutexDeletionInProgressFlag()
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530960 return nil, fmt.Errorf("Can't proceed, device deletion is in progress-%s", tProfile.DeviceId)
Praneeth Nalmas04600be2024-12-08 20:12:32 +0530961 }
962 handler.RUnlockMutexDeletionInProgressFlag()
khenaidoo7d3c5582021-08-11 18:09:44 -0400963 if err := handler.handleTechProfileDownloadRequest(log.WithSpanFromContext(context.Background(), ctx), tProfile); err != nil {
964 return nil, err
965 }
966 return &empty.Empty{}, nil
967 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530968 return nil, fmt.Errorf("handler-not-found-%s", tProfile.DeviceId)
khenaidoo7d3c5582021-08-11 18:09:44 -0400969}
970
971// DeleteGemPort is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400972func (oo *OpenONUAC) DeleteGemPort(ctx context.Context, gPort *ia.DeleteGemPortMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400973 logger.Debugw(ctx, "delete-gem-port", log.Fields{"device-id": gPort.DeviceId, "uni-id": gPort.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400974 if handler := oo.getDeviceHandler(ctx, gPort.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530975 if handler.GetDeletionInProgress() {
976 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": gPort.DeviceId})
977 return nil, fmt.Errorf("device deletion in progress for device-id: %s", gPort.DeviceId)
978 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400979 if err := handler.handleDeleteGemPortRequest(log.WithSpanFromContext(context.Background(), ctx), gPort); err != nil {
980 return nil, err
981 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000982 } else {
983 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": gPort.DeviceId})
984 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400985 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000986 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400987}
988
989// DeleteTCont is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400990func (oo *OpenONUAC) DeleteTCont(ctx context.Context, tConf *ia.DeleteTcontMessage) (*empty.Empty, error) {
Holger Hildebrandtba6fbe82021-12-03 14:29:42 +0000991 logger.Debugw(ctx, "delete-tcont", log.Fields{"device-id": tConf.DeviceId, "tconf": tConf})
khenaidoo7d3c5582021-08-11 18:09:44 -0400992 if handler := oo.getDeviceHandler(ctx, tConf.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530993 if handler.GetDeletionInProgress() {
994 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": tConf.DeviceId})
995 return nil, fmt.Errorf("device deletion in progress for device-id: %s", tConf.DeviceId)
996 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400997 if err := handler.handleDeleteTcontRequest(log.WithSpanFromContext(context.Background(), ctx), tConf); err != nil {
998 return nil, err
999 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +00001000 } else {
1001 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": tConf.DeviceId})
1002 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -04001003 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +00001004 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001005}
1006
1007/*
1008 * Parent GRPC clients
1009 */
1010
khenaidoo55cebc62021-12-08 14:44:41 -05001011func getHash(endpoint, contextInfo string) string {
1012 strToHash := endpoint + contextInfo
1013 h := fnv.New128().Sum([]byte(strToHash))
1014 return string(h)
1015}
1016
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +05301017// nolint:unparam
khenaidoo55cebc62021-12-08 14:44:41 -05001018func (oo *OpenONUAC) updateReachabilityFromRemote(ctx context.Context, remote *common.Connection) {
1019 logger.Debugw(context.Background(), "updating-remote-connection-status", log.Fields{"remote": remote})
1020 oo.lockReachableFromRemote.Lock()
1021 defer oo.lockReachableFromRemote.Unlock()
1022 endpointHash := getHash(remote.Endpoint, remote.ContextInfo)
1023 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
1024 oo.reachableFromRemote[endpointHash].lastKeepAlive = time.Now()
1025 oo.reachableFromRemote[endpointHash].keepAliveInterval = remote.KeepAliveInterval
1026 return
1027 }
1028 logger.Debugw(context.Background(), "initial-remote-connection", log.Fields{"remote": remote})
1029 oo.reachableFromRemote[endpointHash] = &reachabilityFromRemote{lastKeepAlive: time.Now(), keepAliveInterval: remote.KeepAliveInterval}
1030}
1031
Akash Soni931f9b92024-12-11 18:36:36 +05301032// func (oo *OpenONUAC) isReachableFromRemote(ctx context.Context, endpoint string, contextInfo string) bool {
1033// logger.Debugw(ctx, "checking-remote-reachability", log.Fields{"endpoint": endpoint, "context": contextInfo})
1034// oo.lockReachableFromRemote.RLock()
1035// defer oo.lockReachableFromRemote.RUnlock()
1036// endpointHash := getHash(endpoint, contextInfo)
1037// if _, ok := oo.reachableFromRemote[endpointHash]; ok {
1038// logger.Debugw(ctx, "endpoint-exists", log.Fields{"last-keep-alive": time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive)})
1039// // Assume the connection is down if we did not receive 2 keep alives in succession
1040// maxKeepAliveWait := time.Duration(oo.reachableFromRemote[endpointHash].keepAliveInterval * 2)
1041// return time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive) <= maxKeepAliveWait
1042// }
1043// return false
1044// }
khenaidoo55cebc62021-12-08 14:44:41 -05001045
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301046// stopAllGrpcClients stops all grpc clients in use
khenaidoof3333552021-12-15 16:52:31 -05001047func (oo *OpenONUAC) stopAllGrpcClients(ctx context.Context) {
1048 // Stop the clients that connect to the parent
1049 oo.lockParentAdapterClients.Lock()
1050 for key := range oo.parentAdapterClients {
1051 oo.parentAdapterClients[key].Stop(ctx)
1052 delete(oo.parentAdapterClients, key)
1053 }
1054 oo.lockParentAdapterClients.Unlock()
1055
1056 // Stop core client connection
1057 oo.coreClient.Stop(ctx)
1058}
1059
khenaidoo7d3c5582021-08-11 18:09:44 -04001060func (oo *OpenONUAC) setupParentInterAdapterClient(ctx context.Context, endpoint string) error {
1061 logger.Infow(ctx, "setting-parent-adapter-connection", log.Fields{"parent-endpoint": endpoint})
1062 oo.lockParentAdapterClients.Lock()
1063 defer oo.lockParentAdapterClients.Unlock()
1064 if _, ok := oo.parentAdapterClients[endpoint]; ok {
1065 return nil
1066 }
1067
khenaidoo55cebc62021-12-08 14:44:41 -05001068 childClient, err := vgrpc.NewClient(
1069 oo.config.AdapterEndpoint,
1070 endpoint,
khenaidoof3333552021-12-15 16:52:31 -05001071 "olt_inter_adapter_service.OltInterAdapterService",
khenaidoo55cebc62021-12-08 14:44:41 -05001072 oo.oltAdapterRestarted)
khenaidoo7d3c5582021-08-11 18:09:44 -04001073
1074 if err != nil {
1075 return err
1076 }
nikesh.krishnance4879a2023-08-01 18:36:57 +05301077 retryCodes := []codes.Code{
1078 codes.Unavailable, // server is currently unavailable
1079 codes.DeadlineExceeded, // deadline for the operation was exceeded
1080 }
1081 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(oo.config.PerRPCRetryTimeout, 0.2))
1082 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 -04001083
1084 oo.parentAdapterClients[endpoint] = childClient
nikesh.krishnance4879a2023-08-01 18:36:57 +05301085 go oo.parentAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), getOltInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo7d3c5582021-08-11 18:09:44 -04001086 // Wait until we have a connection to the child adapter.
1087 // Unlimited retries or until context expires
1088 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
1089 backoff := vgrpc.NewBackoff(oo.config.MinBackoffRetryDelay, oo.config.MaxBackoffRetryDelay, 0)
1090 for {
1091 client, err := oo.parentAdapterClients[endpoint].GetOltInterAdapterServiceClient()
1092 if err == nil && client != nil {
1093 logger.Infow(subCtx, "connected-to-parent-adapter", log.Fields{"parent-endpoint": endpoint})
1094 break
1095 }
1096 logger.Warnw(subCtx, "connection-to-parent-adapter-not-ready", log.Fields{"error": err, "parent-endpoint": endpoint})
1097 // Backoff
1098 if err = backoff.Backoff(subCtx); err != nil {
1099 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "parent-endpoint": endpoint})
1100 break
1101 }
1102 }
1103 return nil
1104}
1105
khenaidoo42dcdfd2021-10-19 17:34:12 -04001106func (oo *OpenONUAC) getParentAdapterServiceClient(endpoint string) (olt_inter_adapter_service.OltInterAdapterServiceClient, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001107 // First check from cache
1108 oo.lockParentAdapterClients.RLock()
1109 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1110 oo.lockParentAdapterClients.RUnlock()
1111 return pgClient.GetOltInterAdapterServiceClient()
1112 }
1113 oo.lockParentAdapterClients.RUnlock()
1114
1115 // Set the parent connection - can occur on restarts
1116 ctx, cancel := context.WithTimeout(context.Background(), oo.config.RPCTimeout)
1117 err := oo.setupParentInterAdapterClient(ctx, endpoint)
1118 cancel()
1119 if err != nil {
1120 return nil, err
1121 }
1122
1123 // Get the parent client now
1124 oo.lockParentAdapterClients.RLock()
1125 defer oo.lockParentAdapterClients.RUnlock()
1126 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1127 return pgClient.GetOltInterAdapterServiceClient()
1128 }
1129
1130 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
1131}
1132
1133// TODO: Any action the adapter needs to do following an olt adapter restart?
1134func (oo *OpenONUAC) oltAdapterRestarted(ctx context.Context, endPoint string) error {
1135 logger.Errorw(ctx, "olt-adapter-restarted", log.Fields{"endpoint": endPoint})
1136 return nil
1137}
1138
khenaidoof3333552021-12-15 16:52:31 -05001139// getOltInterAdapterServiceClientHandler is used to setup the remote gRPC service
1140func getOltInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
1141 if conn == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -04001142 return nil
1143 }
khenaidoof3333552021-12-15 16:52:31 -05001144 return olt_inter_adapter_service.NewOltInterAdapterServiceClient(conn)
khenaidoo7d3c5582021-08-11 18:09:44 -04001145}
1146
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001147func (oo *OpenONUAC) forceDeleteDeviceKvData(ctx context.Context, aDeviceID string) error {
1148 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 -08001149 var errorsList []error
1150 // delete onu persitent data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001151 onuBaseKvStorePath := fmt.Sprintf(cmn.CBasePathOnuKVStore, oo.cm.Backend.PathPrefix)
1152 logger.Debugw(ctx, "SetOnuKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": onuBaseKvStorePath,
1153 "device-id": aDeviceID})
1154 onuKvbackend := &db.Backend{
1155 Client: oo.kvClient,
1156 StoreType: oo.KVStoreType,
1157 Address: oo.KVStoreAddress,
1158 Timeout: oo.KVStoreTimeout,
1159 PathPrefix: onuBaseKvStorePath,
1160 }
1161 err := onuKvbackend.DeleteWithPrefix(ctx, aDeviceID)
1162 if err != nil {
1163 logger.Errorw(ctx, "unable to delete in KVstore", log.Fields{"service": onuBaseKvStorePath, "device-id": aDeviceID, "err": err})
1164 // continue to delete kv data, but accumulate any errors
1165 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001166 }
Girish Gowdraf10379e2022-02-02 21:49:44 -08001167 // delete pm data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001168 pmBaseKvStorePath := fmt.Sprintf(pmmgr.CPmKvStorePrefixBase, oo.cm.Backend.PathPrefix)
1169 logger.Debugw(ctx, "SetPmKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": pmBaseKvStorePath,
1170 "device-id": aDeviceID})
Girish Gowdraf10379e2022-02-02 21:49:44 -08001171 pmKvbackend := &db.Backend{
1172 Client: oo.kvClient,
1173 StoreType: oo.KVStoreType,
1174 Address: oo.KVStoreAddress,
1175 Timeout: oo.KVStoreTimeout,
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001176 PathPrefix: pmBaseKvStorePath,
Girish Gowdraf10379e2022-02-02 21:49:44 -08001177 }
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001178 err = pmKvbackend.DeleteWithPrefix(ctx, aDeviceID)
Girish Gowdraf10379e2022-02-02 21:49:44 -08001179 if err != nil {
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001180 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 -08001181 // accumulate any errors
1182 errorsList = append(errorsList, err)
1183 }
1184 if len(errorsList) > 0 {
1185 return fmt.Errorf("one or more error deleting kv data, error: %v", errorsList)
1186 }
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001187 return nil
1188}
1189
khenaidoof3333552021-12-15 16:52:31 -05001190// GetHealthStatus is used by the voltha core to open a streaming connection with the onu adapter.
1191func (oo *OpenONUAC) GetHealthStatus(stream adapter_service.AdapterService_GetHealthStatusServer) error {
1192 ctx := context.Background()
1193 logger.Debugw(ctx, "receive-stream-connection", log.Fields{"stream": stream})
1194
1195 if stream == nil {
1196 return fmt.Errorf("conn-is-nil %v", stream)
1197 }
1198 initialRequestTime := time.Now()
1199 var remoteClient *common.Connection
1200 var tempClient *common.Connection
1201 var err error
1202loop:
1203 for {
1204 tempClient, err = stream.Recv()
1205 if err != nil {
1206 logger.Warnw(ctx, "received-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1207 break loop
1208 }
1209 // Send a response back
1210 err = stream.Send(&health.HealthStatus{State: health.HealthStatus_HEALTHY})
1211 if err != nil {
1212 logger.Warnw(ctx, "sending-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1213 break loop
1214 }
1215 remoteClient = tempClient
1216
1217 logger.Debugw(ctx, "received-keep-alive", log.Fields{"remote-client": remoteClient})
1218
1219 select {
1220 case <-stream.Context().Done():
1221 logger.Infow(ctx, "stream-keep-alive-context-done", log.Fields{"remote-client": remoteClient, "error": stream.Context().Err()})
1222 break loop
1223 case <-oo.exitChannel:
1224 logger.Warnw(ctx, "received-stop", log.Fields{"remote-client": remoteClient, "initial-conn-time": initialRequestTime})
1225 break loop
1226 default:
1227 }
1228 }
1229 logger.Errorw(ctx, "connection-down", log.Fields{"remote-client": remoteClient, "error": err, "initial-conn-time": initialRequestTime})
1230 return err
1231}
1232
khenaidoo7d3c5582021-08-11 18:09:44 -04001233/*
1234 *
1235 * Unimplemented APIs
1236 *
1237 */
1238
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301239// GetOfpDeviceInfo returns OFP information for the given device. Method not implemented as per [VOL-3202].
khenaidoo7d3c5582021-08-11 18:09:44 -04001240// 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 -04001241func (oo *OpenONUAC) GetOfpDeviceInfo(ctx context.Context, device *voltha.Device) (*ca.SwitchCapability, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001242 return nil, errors.New("unImplemented")
1243}
1244
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301245// SimulateAlarm is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001246func (oo *OpenONUAC) SimulateAlarm(context.Context, *ca.SimulateAlarmMessage) (*common.OperationResp, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001247 return nil, errors.New("unImplemented")
1248}
1249
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301250// SetExtValue is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001251func (oo *OpenONUAC) SetExtValue(context.Context, *ca.SetExtValueMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001252 return nil, errors.New("unImplemented")
1253}
1254
Akash Soni3c176c62024-12-04 13:30:43 +05301255// SetSingleValue sets a single value based on the given request and returns the response.
1256func (oo *OpenONUAC) SetSingleValue(ctx context.Context, request *extension.SingleSetValueRequest) (*extension.SingleSetValueResponse, error) {
1257 logger.Infow(ctx, "single_set_value_request", log.Fields{"request": request})
1258
1259 errResp := func(status extension.SetValueResponse_Status,
1260 reason extension.SetValueResponse_ErrorReason) *extension.SingleSetValueResponse {
1261 return &extension.SingleSetValueResponse{
1262 Response: &extension.SetValueResponse{
1263 Status: status,
1264 ErrReason: reason,
1265 },
1266 }
1267 }
1268 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
1269 switch reqType := request.GetRequest().GetRequest().(type) {
1270 case *extension.SetValueRequest_AppOffloadOnuConfig:
1271 return handler.setOnuOffloadStats(ctx, reqType.AppOffloadOnuConfig), nil
1272 default:
1273 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_UNSUPPORTED), nil
1274 }
1275 }
1276
1277 logger.Infow(ctx, "Single_set_value_request failed ", log.Fields{"request": request})
1278 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_INVALID_DEVICE_ID), nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001279}
1280
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301281// StartOmciTest not implemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001282func (oo *OpenONUAC) StartOmciTest(ctx context.Context, test *ca.OMCITest) (*omci.TestResponse, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001283 return nil, errors.New("unImplemented")
1284}
1285
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301286// SuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001287func (oo *OpenONUAC) SuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1288 return nil, errors.New("unImplemented")
1289}
1290
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301291// UnSuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001292func (oo *OpenONUAC) UnSuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1293 return nil, errors.New("unImplemented")
1294}
1295
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301296// GetImageDownloadStatus is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001297func (oo *OpenONUAC) GetImageDownloadStatus(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001298 return nil, errors.New("unImplemented")
1299}
1300
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301301// CancelImageDownload is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001302func (oo *OpenONUAC) CancelImageDownload(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001303 return nil, errors.New("unImplemented")
1304}
1305
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301306// RevertImageUpdate is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001307func (oo *OpenONUAC) RevertImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001308 return nil, errors.New("unImplemented")
1309}
1310
1311// UpdateFlowsBulk is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001312func (oo *OpenONUAC) UpdateFlowsBulk(ctx context.Context, flows *ca.BulkFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001313 return nil, errors.New("unImplemented")
1314}
1315
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301316// SelfTestDevice unimplented
khenaidoo7d3c5582021-08-11 18:09:44 -04001317func (oo *OpenONUAC) SelfTestDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
1318 return nil, errors.New("unImplemented")
1319}
1320
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301321// SendPacketOut sends packet out to the device
khenaidoo42dcdfd2021-10-19 17:34:12 -04001322func (oo *OpenONUAC) SendPacketOut(ctx context.Context, packet *ca.PacketOut) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001323 return nil, errors.New("unImplemented")
1324}
1325
1326// EnablePort to Enable PON/NNI interface - seems not to be used/required according to python code
1327func (oo *OpenONUAC) EnablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1328 return nil, errors.New("unImplemented")
1329}
1330
1331// DisablePort to Disable pon/nni interface - seems not to be used/required according to python code
1332func (oo *OpenONUAC) DisablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1333 return nil, errors.New("unImplemented")
1334}
1335
1336// GetExtValue - unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001337func (oo *OpenONUAC) GetExtValue(ctx context.Context, extInfo *ca.GetExtValueMessage) (*extension.ReturnValues, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001338 return nil, errors.New("unImplemented")
1339}
1340
1341// ChildDeviceLost - unimplemented
1342func (oo *OpenONUAC) ChildDeviceLost(ctx context.Context, childDevice *voltha.Device) (*empty.Empty, error) {
1343 return nil, errors.New("unImplemented")
1344}
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +00001345
1346// GetSupportedFsms - TODO: add comment
1347func (oo *OpenONUAC) GetSupportedFsms() *cmn.OmciDeviceFsms {
1348 return oo.pSupportedFsms
1349}
1350
1351// LockMutexMibTemplateGenerated - TODO: add comment
1352func (oo *OpenONUAC) LockMutexMibTemplateGenerated() {
1353 oo.mutexMibTemplateGenerated.Lock()
1354}
1355
1356// UnlockMutexMibTemplateGenerated - TODO: add comment
1357func (oo *OpenONUAC) UnlockMutexMibTemplateGenerated() {
1358 oo.mutexMibTemplateGenerated.Unlock()
1359}
1360
1361// GetMibTemplatesGenerated - TODO: add comment
1362func (oo *OpenONUAC) GetMibTemplatesGenerated(mibTemplatePath string) (value bool, exist bool) {
1363 value, exist = oo.mibTemplatesGenerated[mibTemplatePath]
1364 return value, exist
1365}
1366
1367// SetMibTemplatesGenerated - TODO: add comment
1368func (oo *OpenONUAC) SetMibTemplatesGenerated(mibTemplatePath string, value bool) {
1369 oo.mibTemplatesGenerated[mibTemplatePath] = value
1370}
1371
1372// RLockMutexDeviceHandlersMap - TODO: add comment
1373func (oo *OpenONUAC) RLockMutexDeviceHandlersMap() {
1374 oo.mutexDeviceHandlersMap.RLock()
1375}
1376
1377// RUnlockMutexDeviceHandlersMap - TODO: add comment
1378func (oo *OpenONUAC) RUnlockMutexDeviceHandlersMap() {
1379 oo.mutexDeviceHandlersMap.RUnlock()
1380}
1381
1382// GetDeviceHandler - TODO: add comment
1383func (oo *OpenONUAC) GetDeviceHandler(deviceID string) (value cmn.IdeviceHandler, exist bool) {
1384 value, exist = oo.deviceHandlers[deviceID]
1385 return value, exist
1386}
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +05301387
1388// GetONUMIBDBMap - Returns the Map corresponding to ONT type and the MIB common Instance.
1389func (oo *OpenONUAC) GetONUMIBDBMap() devdb.OnuMCmnMEDBMap {
1390 return oo.MibDatabaseMap
1391}
1392
1393// RLockMutexMIBDatabaseMap acquires a read lock on the mutex associated with the MIBDatabaseMap.
1394func (oo *OpenONUAC) RLockMutexMIBDatabaseMap() {
1395 oo.mutexMibDatabaseMap.RLock()
1396}
1397
1398// RUnlockMutexMIBDatabaseMap releases the read lock on the mutex associated with the MIBDatabaseMap.
1399func (oo *OpenONUAC) RUnlockMutexMIBDatabaseMap() {
1400 oo.mutexMibDatabaseMap.RUnlock()
1401}
1402
1403// LockMutexMIBDatabaseMap locks the mutex associated with the MIBDatabaseMap.
1404// Should be called before any operations that modify or read from the MIBDatabaseMap.
1405func (oo *OpenONUAC) LockMutexMIBDatabaseMap() {
1406 oo.mutexMibDatabaseMap.Lock()
1407}
1408
1409// UnlockMutexMIBDatabaseMap unlocks the mutex associated with the MIBDatabaseMap.
1410// Should be called after completing operations that require exclusive access
1411// to the MIBDatabaseMap, ensuring the mutex is released for other goroutines.
1412func (oo *OpenONUAC) UnlockMutexMIBDatabaseMap() {
1413 oo.mutexMibDatabaseMap.Unlock()
1414}
1415
1416// CreateEntryAtMibDatabaseMap adds an entry to the MibDatabaseMap if it doesn't exist
1417func (oo *OpenONUAC) CreateEntryAtMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, error) {
1418 oo.mutexMibDatabaseMap.Lock()
1419 defer oo.mutexMibDatabaseMap.Unlock()
1420
1421 // Check if the key already exists
1422 if mibEntry, exists := oo.MibDatabaseMap[key]; exists {
1423 logger.Warnw(ctx, "Entry already exists in MIB Database Map", log.Fields{"remote-client": key})
1424 return mibEntry, fmt.Errorf("entry already exists for key: %s", key)
1425 }
1426
1427 value := devdb.NewOnuCmnMEDB(ctx)
1428
1429 logger.Infow(ctx, "Created a new Common MIB Database Entry", log.Fields{"remote-client": key})
1430 oo.MibDatabaseMap[key] = value
1431
1432 return value, nil
1433}
1434
1435// FetchEntryFromMibDatabaseMap fetches a references to common ME DB for a MIB Template from the MibDatabaseMap
1436// If a valid entry exists returns pointer to cmnDB else returns nil.
1437func (oo *OpenONUAC) FetchEntryFromMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, bool) {
1438 oo.mutexMibDatabaseMap.RLock()
1439 defer oo.mutexMibDatabaseMap.RUnlock()
1440 value, exists := oo.MibDatabaseMap[key]
1441 if !exists {
1442 return nil, false
1443 }
1444 return value, true
1445
1446}
1447
1448// ResetEntryFromMibDatabaseMap resets the ME values from the Maps.
1449func (oo *OpenONUAC) ResetEntryFromMibDatabaseMap(ctx context.Context, key string) {
1450 oo.mutexMibDatabaseMap.RLock()
1451 onuCmnMEDB, exists := oo.MibDatabaseMap[key]
1452 oo.mutexMibDatabaseMap.RUnlock()
1453 if exists {
1454 // Lock the MeDbLock to ensure thread-safe operation
1455 onuCmnMEDB.MeDbLock.Lock()
1456 defer onuCmnMEDB.MeDbLock.Unlock()
1457
1458 // Reset the MeDb and UnknownMeAndAttribDb maps
1459 onuCmnMEDB.MeDb = make(devdb.MeDbMap)
1460 onuCmnMEDB.UnknownMeAndAttribDb = make(devdb.UnknownMeAndAttribDbMap)
1461
1462 }
1463}
1464
1465// DeleteEntryFromMibDatabaseMap deletes an entry from the MibDatabaseMap
1466func (oo *OpenONUAC) DeleteEntryFromMibDatabaseMap(key string) {
1467 oo.mutexMibDatabaseMap.Lock()
1468 defer oo.mutexMibDatabaseMap.Unlock()
1469 delete(oo.MibDatabaseMap, key)
1470}