blob: 9e46c54a3f18b139aa86df3f341fdd2e52b638bc [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001/*
Joey Armstrong89c812c2024-01-12 19:00:20 -05002 * Copyright 2020-2024 Open Networking Foundation (ONF) and the ONF Contributors
Holger Hildebrandtfa074992020-03-27 15:42:06 +00003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
praneeth nalmas5a0a5502022-12-23 15:57:00 +053017// Package core provides the utility for onu devices, flows and statistics
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000018package core
Holger Hildebrandtfa074992020-03-27 15:42:06 +000019
20import (
21 "context"
22 "errors"
23 "fmt"
khenaidoo55cebc62021-12-08 14:44:41 -050024 "hash/fnv"
Holger Hildebrandt52f271b2022-06-02 09:32:27 +000025 "strings"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000026 "sync"
27 "time"
28
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +053029 grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
30 "github.com/opencord/voltha-lib-go/v7/pkg/db"
31 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
32 codes "google.golang.org/grpc/codes"
33
khenaidoo7d3c5582021-08-11 18:09:44 -040034 conf "github.com/opencord/voltha-lib-go/v7/pkg/config"
khenaidoof3333552021-12-15 16:52:31 -050035 "github.com/opencord/voltha-protos/v5/go/adapter_service"
khenaidoo7d3c5582021-08-11 18:09:44 -040036 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoo42dcdfd2021-10-19 17:34:12 -040037 "github.com/opencord/voltha-protos/v5/go/health"
38 "github.com/opencord/voltha-protos/v5/go/olt_inter_adapter_service"
khenaidoo7d3c5582021-08-11 18:09:44 -040039 "google.golang.org/grpc"
khenaidoo55cebc62021-12-08 14:44:41 -050040 "google.golang.org/grpc/status"
khenaidoo7d3c5582021-08-11 18:09:44 -040041
42 "github.com/golang/protobuf/ptypes/empty"
43 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
44 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
45 "github.com/opencord/voltha-lib-go/v7/pkg/log"
khenaidoo42dcdfd2021-10-19 17:34:12 -040046 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo7d3c5582021-08-11 18:09:44 -040047 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoo42dcdfd2021-10-19 17:34:12 -040048 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
49 "github.com/opencord/voltha-protos/v5/go/omci"
khenaidoo7d3c5582021-08-11 18:09:44 -040050 "github.com/opencord/voltha-protos/v5/go/voltha"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000051
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000052 cmn "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/common"
Matteo Scandolo761f7512020-11-23 15:52:40 -080053 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/config"
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +053054 devdb "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/devdb"
Holger Hildebrandt60652202021-11-02 11:09:36 +000055 pmmgr "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/pmmgr"
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000056 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/swupg"
57 uniprt "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/uniprt"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000058)
59
khenaidoo55cebc62021-12-08 14:44:41 -050060type reachabilityFromRemote struct {
61 lastKeepAlive time.Time
62 keepAliveInterval int64
63}
64
praneeth nalmas5a0a5502022-12-23 15:57:00 +053065// OpenONUAC structure holds the ONU core information
Holger Hildebrandtfa074992020-03-27 15:42:06 +000066type OpenONUAC struct {
Himani Chawla6d2ae152020-09-02 13:11:20 +053067 deviceHandlers map[string]*deviceHandler
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +000068 deviceHandlersCreateChan map[string]chan bool //channels for deviceHandler create events
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000069 mutexDeviceHandlersMap sync.RWMutex
khenaidoo7d3c5582021-08-11 18:09:44 -040070 coreClient *vgrpc.Client
71 parentAdapterClients map[string]*vgrpc.Client
72 lockParentAdapterClients sync.RWMutex
khenaidoo55cebc62021-12-08 14:44:41 -050073 reachableFromRemote map[string]*reachabilityFromRemote
74 lockReachableFromRemote sync.RWMutex
Himani Chawlac07fda02020-12-09 16:21:21 +053075 eventProxy eventif.EventProxy
mpagenkoaf801632020-07-03 10:00:42 +000076 kvClient kvstore.Client
Matteo Scandolof1f39a72020-11-24 12:08:11 -080077 cm *conf.ConfigManager
Holger Hildebrandtfa074992020-03-27 15:42:06 +000078 config *config.AdapterFlags
79 numOnus int
Matteo Scandolo127c59d2021-01-28 11:31:18 -080080 KVStoreAddress string
Holger Hildebrandtfa074992020-03-27 15:42:06 +000081 KVStoreType string
mpagenkoaf801632020-07-03 10:00:42 +000082 KVStoreTimeout time.Duration
Holger Hildebrandt61b24d02020-11-16 13:36:40 +000083 mibTemplatesGenerated map[string]bool
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000084 mutexMibTemplateGenerated sync.RWMutex
Holger Hildebrandtfa074992020-03-27 15:42:06 +000085 exitChannel chan int
86 HeartbeatCheckInterval time.Duration
87 HeartbeatFailReportInterval time.Duration
mpagenkodff5dda2020-08-28 11:52:01 +000088 AcceptIncrementalEvto bool
khenaidoo55cebc62021-12-08 14:44:41 -050089 pSupportedFsms *cmn.OmciDeviceFsms
90 maxTimeoutInterAdapterComm time.Duration
91 maxTimeoutReconciling time.Duration
92 pDownloadManager *swupg.AdapterDownloadManager
93 pFileManager *swupg.FileDownloadManager //let coexist 'old and new' DownloadManager as long as 'old' does not get obsolete
94 MetricsEnabled bool
Holger Hildebrandtc572e622022-06-22 09:19:17 +000095 ExtendedOmciSupportEnabled bool
khenaidoo55cebc62021-12-08 14:44:41 -050096 mibAuditInterval time.Duration
97 omciTimeout int // in seconds
98 alarmAuditInterval time.Duration
99 dlToOnuTimeout4M time.Duration
100 rpcTimeout time.Duration
101 maxConcurrentFlowsPerUni int
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530102 skipOnuConfig bool
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +0530103 mutexMibDatabaseMap sync.RWMutex
104 MibDatabaseMap devdb.OnuMCmnMEDBMap
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000105}
106
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530107// NewOpenONUAC returns a new instance of OpenONU_AC
khenaidoo7d3c5582021-08-11 18:09:44 -0400108func NewOpenONUAC(ctx context.Context, coreClient *vgrpc.Client, eventProxy eventif.EventProxy,
109 kvClient kvstore.Client, cfg *config.AdapterFlags, cm *conf.ConfigManager) *OpenONUAC {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000110 var openOnuAc OpenONUAC
111 openOnuAc.exitChannel = make(chan int, 1)
Himani Chawla6d2ae152020-09-02 13:11:20 +0530112 openOnuAc.deviceHandlers = make(map[string]*deviceHandler)
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000113 openOnuAc.deviceHandlersCreateChan = make(map[string]chan bool)
khenaidoo7d3c5582021-08-11 18:09:44 -0400114 openOnuAc.parentAdapterClients = make(map[string]*vgrpc.Client)
khenaidoo55cebc62021-12-08 14:44:41 -0500115 openOnuAc.reachableFromRemote = make(map[string]*reachabilityFromRemote)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000116 openOnuAc.mutexDeviceHandlersMap = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000117 openOnuAc.config = cfg
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800118 openOnuAc.cm = cm
khenaidoo7d3c5582021-08-11 18:09:44 -0400119 openOnuAc.coreClient = coreClient
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000120 openOnuAc.numOnus = cfg.OnuNumber
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000121 openOnuAc.eventProxy = eventProxy
mpagenkoaf801632020-07-03 10:00:42 +0000122 openOnuAc.kvClient = kvClient
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800123 openOnuAc.KVStoreAddress = cfg.KVStoreAddress
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000124 openOnuAc.KVStoreType = cfg.KVStoreType
mpagenkoaf801632020-07-03 10:00:42 +0000125 openOnuAc.KVStoreTimeout = cfg.KVStoreTimeout
Holger Hildebrandt61b24d02020-11-16 13:36:40 +0000126 openOnuAc.mibTemplatesGenerated = make(map[string]bool)
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000127 openOnuAc.mutexMibTemplateGenerated = sync.RWMutex{}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000128 openOnuAc.HeartbeatCheckInterval = cfg.HeartbeatCheckInterval
129 openOnuAc.HeartbeatFailReportInterval = cfg.HeartbeatFailReportInterval
mpagenkodff5dda2020-08-28 11:52:01 +0000130 openOnuAc.AcceptIncrementalEvto = cfg.AccIncrEvto
Himani Chawlad96df182020-09-28 11:12:02 +0530131 openOnuAc.maxTimeoutInterAdapterComm = cfg.MaxTimeoutInterAdapterComm
Holger Hildebrandt38985dc2021-02-18 16:25:20 +0000132 openOnuAc.maxTimeoutReconciling = cfg.MaxTimeoutReconciling
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000133 //openOnuAc.GrpcTimeoutInterval = cfg.GrpcTimeoutInterval
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000134 openOnuAc.MetricsEnabled = cfg.MetricsEnabled
Holger Hildebrandtc572e622022-06-22 09:19:17 +0000135 openOnuAc.ExtendedOmciSupportEnabled = cfg.ExtendedOmciSupportEnabled
Holger Hildebrandte3677f12021-02-05 14:50:56 +0000136 openOnuAc.mibAuditInterval = cfg.MibAuditInterval
Girish Gowdra0b235842021-03-09 13:06:46 -0800137 // since consumers of OMCI timeout value everywhere in code is in "int seconds", do this useful conversion
138 openOnuAc.omciTimeout = int(cfg.OmciTimeout.Seconds())
Himani Chawla075f1642021-03-15 19:23:24 +0530139 openOnuAc.alarmAuditInterval = cfg.AlarmAuditInterval
mpagenkoc26d4c02021-05-06 14:27:57 +0000140 openOnuAc.dlToOnuTimeout4M = cfg.DownloadToOnuTimeout4MB
khenaidoo7d3c5582021-08-11 18:09:44 -0400141 openOnuAc.rpcTimeout = cfg.RPCTimeout
Girish Gowdrae95687a2021-09-08 16:30:58 -0700142 openOnuAc.maxConcurrentFlowsPerUni = cfg.MaxConcurrentFlowsPerUni
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000143
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000144 openOnuAc.pSupportedFsms = &cmn.OmciDeviceFsms{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000145 "mib-synchronizer": {
146 //mibSyncFsm, // Implements the MIB synchronization state machine
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000147 DatabaseClass: mibDbVolatileDictImpl, // Implements volatile ME MIB database
Himani Chawla4d908332020-08-31 12:30:20 +0530148 //true, // Advertise events on OpenOMCI event bus
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000149 AuditInterval: openOnuAc.mibAuditInterval, // Time to wait between MIB audits. 0 to disable audits.
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000150 // map[string]func() error{
151 // "mib-upload": onuDeviceEntry.MibUploadTask,
152 // "mib-template": onuDeviceEntry.MibTemplateTask,
153 // "get-mds": onuDeviceEntry.GetMdsTask,
154 // "mib-audit": onuDeviceEntry.GetMdsTask,
155 // "mib-resync": onuDeviceEntry.MibResyncTask,
156 // "mib-reconcile": onuDeviceEntry.MibReconcileTask,
157 // },
158 },
159 }
160
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000161 openOnuAc.pDownloadManager = swupg.NewAdapterDownloadManager(ctx)
162 openOnuAc.pFileManager = swupg.NewFileDownloadManager(ctx)
mpagenkoc26d4c02021-05-06 14:27:57 +0000163 openOnuAc.pFileManager.SetDownloadTimeout(ctx, cfg.DownloadToAdapterTimeout)
Praneeth Kumar Nalmas77ab2f32024-04-17 11:14:27 +0530164 openOnuAc.skipOnuConfig = cfg.SkipOnuConfig
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +0530165 openOnuAc.mutexMibDatabaseMap = sync.RWMutex{}
166 openOnuAc.MibDatabaseMap = make(map[string]*devdb.OnuCmnMEDB)
mpagenkoc8bba412021-01-15 15:38:44 +0000167
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000168 return &openOnuAc
169}
170
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530171// Start starts (logs) the adapter
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000172func (oo *OpenONUAC) Start(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000173 logger.Info(ctx, "starting-openonu-adapter")
mpagenkoc8bba412021-01-15 15:38:44 +0000174
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000175 return nil
176}
177
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530178// Stop terminates the session
khenaidoof3333552021-12-15 16:52:31 -0500179func (oo *OpenONUAC) Stop(ctx context.Context) error {
180 logger.Info(ctx, "stopping-device-manager")
181 close(oo.exitChannel)
182 oo.stopAllGrpcClients(ctx)
183 logger.Info(ctx, "device-manager-stopped")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000184 return nil
185}
186
Himani Chawla6d2ae152020-09-02 13:11:20 +0530187func (oo *OpenONUAC) addDeviceHandlerToMap(ctx context.Context, agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000188 oo.mutexDeviceHandlersMap.Lock()
189 defer oo.mutexDeviceHandlersMap.Unlock()
190 if _, exist := oo.deviceHandlers[agent.DeviceID]; !exist {
191 oo.deviceHandlers[agent.DeviceID] = agent
192 oo.deviceHandlers[agent.DeviceID].start(ctx)
193 if _, exist := oo.deviceHandlersCreateChan[agent.DeviceID]; exist {
194 logger.Debugw(ctx, "deviceHandler created - trigger processing of pending ONU_IND_REQUEST", log.Fields{"device-id": agent.DeviceID})
195 oo.deviceHandlersCreateChan[agent.DeviceID] <- true
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000196 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000197 }
198}
199
Himani Chawla6d2ae152020-09-02 13:11:20 +0530200func (oo *OpenONUAC) deleteDeviceHandlerToMap(agent *deviceHandler) {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000201 oo.mutexDeviceHandlersMap.Lock()
202 defer oo.mutexDeviceHandlersMap.Unlock()
203 delete(oo.deviceHandlers, agent.DeviceID)
204 delete(oo.deviceHandlersCreateChan, agent.DeviceID)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000205}
206
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530207// getDeviceHandler gets the ONU deviceHandler and may wait until it is created
dbainbri4d3a0dc2020-12-02 00:33:42 +0000208func (oo *OpenONUAC) getDeviceHandler(ctx context.Context, deviceID string, aWait bool) *deviceHandler {
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000209 oo.mutexDeviceHandlersMap.Lock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000210 agent, ok := oo.deviceHandlers[deviceID]
211 if aWait && !ok {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000212 logger.Infow(ctx, "Race condition: deviceHandler not present - wait for creation or timeout",
Holger Hildebrandt6c1fb0a2020-11-25 15:41:01 +0000213 log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000214 if _, exist := oo.deviceHandlersCreateChan[deviceID]; !exist {
215 oo.deviceHandlersCreateChan[deviceID] = make(chan bool, 1)
216 }
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800217 deviceCreateChan := oo.deviceHandlersCreateChan[deviceID]
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000218 //keep the read sema short to allow for subsequent write
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000219 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000220 // based on concurrent processing the deviceHandler creation may not yet be finished at his point
221 // so it might be needed to wait here for that event with some timeout
222 select {
Akash Soni71f44762024-12-11 16:12:21 +0530223 case <-time.After(20 * time.Second): //timer may be discussed ...
dbainbri4d3a0dc2020-12-02 00:33:42 +0000224 logger.Warnw(ctx, "No valid deviceHandler created after max WaitTime", log.Fields{"device-id": deviceID})
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000225 return nil
Girish Gowdra7407a4d2020-11-12 12:44:53 -0800226 case <-deviceCreateChan:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000227 logger.Debugw(ctx, "deviceHandler is ready now - continue", log.Fields{"device-id": deviceID})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000228 oo.mutexDeviceHandlersMap.RLock()
229 defer oo.mutexDeviceHandlersMap.RUnlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000230 return oo.deviceHandlers[deviceID]
231 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000232 }
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000233 oo.mutexDeviceHandlersMap.Unlock()
Holger Hildebrandtf07b44a2020-11-10 13:07:54 +0000234 return agent
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000235}
236
khenaidoo7d3c5582021-08-11 18:09:44 -0400237// AdoptDevice creates a new device handler if not present already and then adopts the device
238func (oo *OpenONUAC) AdoptDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000239 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000240 logger.Warn(ctx, "voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400241 return nil, errors.New("nil-device")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000242 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000243 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id})
Himani Chawla6d2ae152020-09-02 13:11:20 +0530244 var handler *deviceHandler
dbainbri4d3a0dc2020-12-02 00:33:42 +0000245 if handler = oo.getDeviceHandler(ctx, device.Id, false); handler == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -0400246 handler := newDeviceHandler(ctx, oo.coreClient, oo.eventProxy, device, oo)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000247 oo.addDeviceHandlerToMap(ctx, handler)
khenaidoo7d3c5582021-08-11 18:09:44 -0400248
249 // Setup the grpc communication with the parent adapter
250 if err := oo.setupParentInterAdapterClient(ctx, device.ProxyAddress.AdapterEndpoint); err != nil {
251 // TODO: Cleanup on failure needed
252 return nil, err
253 }
254
255 go handler.adoptOrReconcileDevice(log.WithSpanFromContext(context.Background(), ctx), device)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000256 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400257 return &empty.Empty{}, nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000258}
259
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530260// ReconcileDevice is called once when the adapter needs to re-create device - usually on core restart
khenaidoo7d3c5582021-08-11 18:09:44 -0400261func (oo *OpenONUAC) ReconcileDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000262 if device == nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000263 logger.Warn(ctx, "reconcile-device-voltha-device-is-nil")
khenaidoo7d3c5582021-08-11 18:09:44 -0400264 return nil, errors.New("nil-device")
Holger Hildebrandtf41a1602020-08-19 09:52:50 +0000265 }
khenaidoo55cebc62021-12-08 14:44:41 -0500266 logger.Infow(ctx, "reconcile-device", log.Fields{"device-id": device.Id, "parent-id": device.ParentId})
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})
khenaidoo7d3c5582021-08-11 18:09:44 -0400304 return nil, fmt.Errorf(fmt.Sprintf("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})
khenaidoo7d3c5582021-08-11 18:09:44 -0400315 return nil, fmt.Errorf(fmt.Sprintf("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})
404 return nil, fmt.Errorf(fmt.Sprintf("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})
417 return nil, fmt.Errorf(fmt.Sprintf("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})
462 return nil, fmt.Errorf(fmt.Sprintf("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})
465 return nil, fmt.Errorf(fmt.Sprintf("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
kesavandfdf77632021-01-26 23:40:33 -0500501 default:
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000502 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_UNSUPPORTED), nil
kesavandfdf77632021-01-26 23:40:33 -0500503 }
504 }
505 logger.Errorw(ctx, "Single_get_value_request failed ", log.Fields{"request": request})
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +0000506 return uniprt.PostUniStatusErrResponse(extension.GetValueResponse_INVALID_DEVICE_ID), nil
mpagenkoc8bba412021-01-15 15:38:44 +0000507}
508
mpagenko83144272021-04-27 10:06:22 +0000509//if update >= 4.3.0
mpagenkoc26d4c02021-05-06 14:27:57 +0000510// Note: already with the implementation of the 'old' download interface problems were detected when the argument name used here is not the same
511// as defined in the adapter interface file. That sounds strange and the effects were strange as well.
512// The reason for that was never finally investigated.
513// To be on the safe side argument names are left here always as defined in iAdapter.go .
mpagenko83144272021-04-27 10:06:22 +0000514
khenaidoo7d3c5582021-08-11 18:09:44 -0400515// DownloadOnuImage downloads (and optionally activates and commits) the indicated ONU image to the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530516//
517// if the image is not yet present on the adapter it has to be automatically downloaded
khenaidoo7d3c5582021-08-11 18:09:44 -0400518func (oo *OpenONUAC) DownloadOnuImage(ctx context.Context, request *voltha.DeviceImageDownloadRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000519 if request != nil && len((*request).DeviceId) > 0 && (*request).Image.Version != "" {
Holger Hildebrandt52f271b2022-06-02 09:32:27 +0000520 if strings.Contains((*request).Image.Url, "https:") {
521 return nil, errors.New("image download via https not supported")
522 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000523 loResponse := voltha.DeviceImageResponse{}
524 imageIdentifier := (*request).Image.Version
mpagenkoc497ee32021-11-10 17:30:20 +0000525 downloadStartDone := false
mpagenkoc26d4c02021-05-06 14:27:57 +0000526 firstDevice := true
527 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000528 var onuVolthaDevice *voltha.Device
529 var devErr error
mpagenkoc26d4c02021-05-06 14:27:57 +0000530 for _, pCommonID := range (*request).DeviceId {
mpagenko38662d02021-08-11 09:45:19 +0000531 vendorIDMatch := true
mpagenkoc26d4c02021-05-06 14:27:57 +0000532 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000533 loDeviceImageState := voltha.DeviceImageState{}
534 loDeviceImageState.DeviceId = loDeviceID
535 loImageState := voltha.ImageState{}
536 loDeviceImageState.ImageState = &loImageState
537 loDeviceImageState.ImageState.Version = (*request).Image.Version
mpagenko38662d02021-08-11 09:45:19 +0000538
mpagenko59862f02021-10-11 08:53:18 +0000539 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400540 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000541 if handler != nil {
542 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
543 } else {
544 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
545 devErr = errors.New("no handler found for device-id")
khenaidoo7d3c5582021-08-11 18:09:44 -0400546 }
mpagenko59862f02021-10-11 08:53:18 +0000547 if devErr != nil || onuVolthaDevice == nil {
548 logger.Warnw(ctx, "Failed to fetch ONU device for image download",
549 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000550 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
551 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //proto restriction, better option: 'INVALID_DEVICE'
mpagenkoc26d4c02021-05-06 14:27:57 +0000552 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000553 } else {
mpagenko38662d02021-08-11 09:45:19 +0000554 if firstDevice {
555 //start/verify download of the image to the adapter based on first found device only
556 // use the OnuVendor identification from first given device
mpagenkoc497ee32021-11-10 17:30:20 +0000557
558 // note: if the request was done for a list of devices on the Voltha interface, rwCore
559 // 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 +0000560 firstDevice = false
561 vendorID = onuVolthaDevice.VendorId
562 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
mpagenkoc497ee32021-11-10 17:30:20 +0000563 logger.Infow(ctx, "download request for file",
564 log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000565
mpagenkoc497ee32021-11-10 17:30:20 +0000566 // call the StartDownload synchronously to detect 'immediate' download problems
567 // the real download itself is later done in background
568 if fileState, err := oo.pFileManager.StartDownload(ctx, imageIdentifier, (*request).Image.Url); err == nil {
mpagenko38662d02021-08-11 09:45:19 +0000569 // note: If the image (with vendorId+name) has already been downloaded before from some other
mpagenkoc497ee32021-11-10 17:30:20 +0000570 // valid URL, the current download request is not executed (current code delivers URL error).
571 // If the operators want to ensure that the new URL
mpagenko38662d02021-08-11 09:45:19 +0000572 // is really used, then they first have to use the 'abort' API to remove the existing image!
573 // (abort API can be used also after some successful download to just remove the image from adapter)
mpagenkoc497ee32021-11-10 17:30:20 +0000574 if fileState == swupg.CFileStateDlSucceeded || fileState == swupg.CFileStateDlStarted {
575 downloadStartDone = true
576 } //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 +0000577 }
578 } else {
579 //for all following devices verify the matching vendorID
580 if onuVolthaDevice.VendorId != vendorID {
581 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
582 log.Fields{"onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
583 vendorIDMatch = false
584 }
585 }
mpagenkoc497ee32021-11-10 17:30:20 +0000586 if downloadStartDone && vendorIDMatch {
mpagenko38662d02021-08-11 09:45:19 +0000587 // start the ONU download activity for each possible device
mpagenkoc497ee32021-11-10 17:30:20 +0000588 logger.Infow(ctx, "request image download to ONU on omci ", log.Fields{
mpagenko59862f02021-10-11 08:53:18 +0000589 "image-id": imageIdentifier, "device-id": loDeviceID})
590 //onu upgrade handling called in background without immediate error evaluation here
591 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
592 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
593 go handler.onuSwUpgradeAfterDownload(ctx, request, oo.pFileManager, imageIdentifier)
594 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_STARTED
595 loDeviceImageState.ImageState.Reason = voltha.ImageState_NO_ERROR
596 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenko38662d02021-08-11 09:45:19 +0000597 } else {
598 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
mpagenkoc497ee32021-11-10 17:30:20 +0000599 if !downloadStartDone {
600 //based on above fileState more descriptive error codes would be possible, e.g
601 // IMAGE_EXISTS_WITH_DIFFERENT_URL - would require proto buf update
mpagenko38662d02021-08-11 09:45:19 +0000602 loDeviceImageState.ImageState.Reason = voltha.ImageState_INVALID_URL
603 } else { //only logical option is !vendorIDMatch
604 loDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
605 }
606 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
607 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000608 }
mpagenko2f2f2362021-06-07 08:25:22 +0000609 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000610 } //for all requested devices
mpagenkoc26d4c02021-05-06 14:27:57 +0000611 pImageResp := &loResponse
612 return pImageResp, nil
613 }
614 return nil, errors.New("invalid image download parameters")
mpagenko83144272021-04-27 10:06:22 +0000615}
616
khenaidoo7d3c5582021-08-11 18:09:44 -0400617// GetOnuImageStatus delivers the adapter-related information about the download/activation/commitment
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530618//
619// status for the requested image
khenaidoo7d3c5582021-08-11 18:09:44 -0400620func (oo *OpenONUAC) GetOnuImageStatus(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000621 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
622 loResponse := voltha.DeviceImageResponse{}
mpagenkoaa3afe92021-05-21 16:20:58 +0000623 imageIdentifier := (*in).Version
mpagenko38662d02021-08-11 09:45:19 +0000624 var vendorIDSet bool
mpagenkoaa3afe92021-05-21 16:20:58 +0000625 firstDevice := true
626 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000627 var onuVolthaDevice *voltha.Device
628 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000629 for _, pCommonID := range (*in).DeviceId {
630 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400631 pDeviceImageState := &voltha.DeviceImageState{DeviceId: loDeviceID}
mpagenko59862f02021-10-11 08:53:18 +0000632 vendorIDSet = false
633 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400634 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000635 if handler != nil {
636 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
637 } else {
638 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
639 devErr = errors.New("no handler found for device-id")
mpagenko38662d02021-08-11 09:45:19 +0000640 }
mpagenko59862f02021-10-11 08:53:18 +0000641 if devErr != nil || onuVolthaDevice == nil {
mpagenkoaa3afe92021-05-21 16:20:58 +0000642 logger.Warnw(ctx, "Failed to fetch Onu device to get image status",
mpagenko59862f02021-10-11 08:53:18 +0000643 log.Fields{"device-id": loDeviceID, "err": devErr})
mpagenko38662d02021-08-11 09:45:19 +0000644 pImageState := &voltha.ImageState{
645 Version: (*in).Version,
646 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //no statement about last activity possible
647 Reason: voltha.ImageState_UNKNOWN_ERROR, //something like "DEVICE_NOT_EXISTS" would be better (proto def)
648 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
mpagenkoaa3afe92021-05-21 16:20:58 +0000649 }
mpagenko38662d02021-08-11 09:45:19 +0000650 pDeviceImageState.ImageState = pImageState
mpagenkoaa3afe92021-05-21 16:20:58 +0000651 } else {
mpagenko38662d02021-08-11 09:45:19 +0000652 if firstDevice {
653 //start/verify download of the image to the adapter based on first found device only
654 // use the OnuVendor identification from first given device
655 firstDevice = false
656 vendorID = onuVolthaDevice.VendorId
657 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
658 vendorIDSet = true
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000659 logger.Debugw(ctx, "status request for image", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko38662d02021-08-11 09:45:19 +0000660 } else {
661 //for all following devices verify the matching vendorID
662 if onuVolthaDevice.VendorId != vendorID {
663 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000664 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko38662d02021-08-11 09:45:19 +0000665 } else {
666 vendorIDSet = true
667 }
668 }
669 if !vendorIDSet {
670 pImageState := &voltha.ImageState{
671 Version: (*in).Version,
672 DownloadState: voltha.ImageState_DOWNLOAD_UNKNOWN, //can't be sure that download for this device was really tried
673 Reason: voltha.ImageState_VENDOR_DEVICE_MISMATCH,
674 ImageState: voltha.ImageState_IMAGE_UNKNOWN,
675 }
676 pDeviceImageState.ImageState = pImageState
677 } else {
khenaidoo7d3c5582021-08-11 18:09:44 -0400678 logger.Debugw(ctx, "image status request for", log.Fields{
679 "image-id": imageIdentifier, "device-id": loDeviceID})
680 //status request is called synchronously to collect the indications for all concerned devices
681 pDeviceImageState.ImageState = handler.requestOnuSwUpgradeState(ctx, imageIdentifier, (*in).Version)
mpagenko38662d02021-08-11 09:45:19 +0000682 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000683 }
684 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000685 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000686 pImageResp := &loResponse
687 return pImageResp, nil
688 }
689 return nil, errors.New("invalid image status request parameters")
mpagenko83144272021-04-27 10:06:22 +0000690}
691
khenaidoo7d3c5582021-08-11 18:09:44 -0400692// AbortOnuImageUpgrade stops the actual download/activation/commitment process (on next possibly step)
693func (oo *OpenONUAC) AbortOnuImageUpgrade(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoaa3afe92021-05-21 16:20:58 +0000694 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
695 loResponse := voltha.DeviceImageResponse{}
696 imageIdentifier := (*in).Version
697 firstDevice := true
698 var vendorID string
mpagenko59862f02021-10-11 08:53:18 +0000699 var vendorIDSet bool
700 var onuVolthaDevice *voltha.Device
701 var devErr error
mpagenkoaa3afe92021-05-21 16:20:58 +0000702 for _, pCommonID := range (*in).DeviceId {
703 loDeviceID := (*pCommonID).Id
khenaidoo7d3c5582021-08-11 18:09:44 -0400704 pDeviceImageState := &voltha.DeviceImageState{}
705 loImageState := voltha.ImageState{}
706 pDeviceImageState.ImageState = &loImageState
mpagenko59862f02021-10-11 08:53:18 +0000707 vendorIDSet = false
708 onuVolthaDevice = nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400709 handler := oo.getDeviceHandler(ctx, loDeviceID, false)
mpagenko59862f02021-10-11 08:53:18 +0000710 if handler != nil {
711 onuVolthaDevice, devErr = handler.getDeviceFromCore(ctx, loDeviceID)
712 } else {
713 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
714 devErr = errors.New("no handler found for device-id")
715 }
716 if devErr != nil || onuVolthaDevice == nil {
717 logger.Warnw(ctx, "Failed to fetch Onu device to abort its download",
718 log.Fields{"device-id": loDeviceID, "err": devErr})
khenaidoo7d3c5582021-08-11 18:09:44 -0400719 pDeviceImageState.DeviceId = loDeviceID
720 pDeviceImageState.ImageState.Version = (*in).Version
mpagenko59862f02021-10-11 08:53:18 +0000721 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
722 pDeviceImageState.ImageState.Reason = voltha.ImageState_CANCELLED_ON_REQUEST //something better could be considered (MissingHandler) - proto
khenaidoo7d3c5582021-08-11 18:09:44 -0400723 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
mpagenkoaa3afe92021-05-21 16:20:58 +0000724 } else {
mpagenko59862f02021-10-11 08:53:18 +0000725 if firstDevice {
726 //start/verify download of the image to the adapter based on first found device only
727 // use the OnuVendor identification from first given device
728 firstDevice = false
729 vendorID = onuVolthaDevice.VendorId
730 vendorIDSet = true
731 imageIdentifier = vendorID + imageIdentifier //head on vendor ID of the ONU
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000732 logger.Debugw(ctx, "abort request for file", log.Fields{"device-id": loDeviceID, "image-id": imageIdentifier})
mpagenko59862f02021-10-11 08:53:18 +0000733 } else {
734 //for all following devices verify the matching vendorID
735 if onuVolthaDevice.VendorId != vendorID {
736 logger.Warnw(ctx, "onu vendor id does not match image vendor id, device ignored",
Holger Hildebrandtabfef032022-02-25 12:40:20 +0000737 log.Fields{"device-id": loDeviceID, "onu-vendor-id": onuVolthaDevice.VendorId, "image-vendor-id": vendorID})
mpagenko59862f02021-10-11 08:53:18 +0000738 pDeviceImageState.DeviceId = loDeviceID
739 pDeviceImageState.ImageState.Version = (*in).Version
740 pDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
741 pDeviceImageState.ImageState.Reason = voltha.ImageState_VENDOR_DEVICE_MISMATCH
742 pDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_UNKNOWN
743 } else {
744 vendorIDSet = true
745 }
746 }
747 if vendorIDSet {
748 // cancel the ONU upgrade activity for each possible device
749 logger.Debugw(ctx, "image upgrade abort requested", log.Fields{
750 "image-id": imageIdentifier, "device-id": loDeviceID})
751 //upgrade cancel is called synchronously to collect the imageResponse indications for all concerned devices
752 handler.cancelOnuSwUpgrade(ctx, imageIdentifier, (*in).Version, pDeviceImageState)
mpagenkoaa3afe92021-05-21 16:20:58 +0000753 }
754 }
mpagenkoaa3afe92021-05-21 16:20:58 +0000755 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, pDeviceImageState)
mpagenko59862f02021-10-11 08:53:18 +0000756 } //for all requested devices
mpagenkoaa3afe92021-05-21 16:20:58 +0000757 if !firstDevice {
758 //if at least one valid device was found cancel also a possibly running download to adapter and remove the image
759 // this is to be done after the upgradeOnu cancel activities in order to not subduct the file for still running processes
760 oo.pFileManager.CancelDownload(ctx, imageIdentifier)
761 }
762 pImageResp := &loResponse
763 return pImageResp, nil
764 }
765 return nil, errors.New("invalid image upgrade abort parameters")
mpagenko83144272021-04-27 10:06:22 +0000766}
767
khenaidoo7d3c5582021-08-11 18:09:44 -0400768// GetOnuImages retrieves the ONU SW image status information via OMCI
769func (oo *OpenONUAC) GetOnuImages(ctx context.Context, id *common.ID) (*voltha.OnuImages, error) {
770 logger.Infow(ctx, "Get_onu_images", log.Fields{"device-id": id.Id})
771 if handler := oo.getDeviceHandler(ctx, id.Id, false); handler != nil {
Himani Chawla69992ab2021-07-08 15:13:02 +0530772 images, err := handler.getOnuImages(ctx)
773 if err == nil {
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000774 return images, nil
775 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400776 return nil, fmt.Errorf(fmt.Sprintf("%s-%s", err, id.Id))
Holger Hildebrandtfb402a62021-05-26 14:40:49 +0000777 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400778 logger.Warnw(ctx, "no handler found for Get_onu_images", log.Fields{"device-id": id.Id})
779 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", id.Id))
mpagenko83144272021-04-27 10:06:22 +0000780}
781
khenaidoo7d3c5582021-08-11 18:09:44 -0400782// ActivateOnuImage initiates the activation of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530783//
784// precondition: image downloaded and not yet activated or image refers to current inactive image
khenaidoo7d3c5582021-08-11 18:09:44 -0400785func (oo *OpenONUAC) ActivateOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000786 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
787 loResponse := voltha.DeviceImageResponse{}
788 imageIdentifier := (*in).Version
789 //let the deviceHandler find the adequate way of requesting the image activation
790 for _, pCommonID := range (*in).DeviceId {
791 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000792 loDeviceImageState := voltha.DeviceImageState{}
793 loDeviceImageState.DeviceId = loDeviceID
794 loImageState := voltha.ImageState{}
795 loDeviceImageState.ImageState = &loImageState
796 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000797 //compared to download procedure the vendorID (from device) is secondary here
798 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
799 // start image activation activity for each possible device
800 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
801 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
802 logger.Debugw(ctx, "onu image activation requested", log.Fields{
803 "image-id": imageIdentifier, "device-id": loDeviceID})
804 //onu activation handling called in background without immediate error evaluation here
805 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
806 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000807 if pImageStates, err := handler.onuSwActivateRequest(ctx, imageIdentifier, (*in).CommitOnSuccess); err != nil {
808 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
809 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
810 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
811 } else {
812 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
813 loDeviceImageState.ImageState.Reason = pImageStates.Reason
814 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
815 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000816 } else {
817 //cannot start SW activation for requested device
818 logger.Warnw(ctx, "no handler found for image activation", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000819 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000820 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
821 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_ACTIVATION_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000822 }
mpagenko2f2f2362021-06-07 08:25:22 +0000823 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000824 }
825 pImageResp := &loResponse
826 return pImageResp, nil
827 }
828 return nil, errors.New("invalid image activation parameters")
mpagenko83144272021-04-27 10:06:22 +0000829}
830
khenaidoo7d3c5582021-08-11 18:09:44 -0400831// CommitOnuImage enforces the commitment of the image for the requested ONU(s)
praneeth nalmas5a0a5502022-12-23 15:57:00 +0530832//
833// precondition: image activated and not yet committed
khenaidoo7d3c5582021-08-11 18:09:44 -0400834func (oo *OpenONUAC) CommitOnuImage(ctx context.Context, in *voltha.DeviceImageRequest) (*voltha.DeviceImageResponse, error) {
mpagenkoc26d4c02021-05-06 14:27:57 +0000835 if in != nil && len((*in).DeviceId) > 0 && (*in).Version != "" {
836 loResponse := voltha.DeviceImageResponse{}
837 imageIdentifier := (*in).Version
838 //let the deviceHandler find the adequate way of requesting the image activation
839 for _, pCommonID := range (*in).DeviceId {
840 loDeviceID := (*pCommonID).Id
mpagenko2f2f2362021-06-07 08:25:22 +0000841 loDeviceImageState := voltha.DeviceImageState{}
842 loDeviceImageState.DeviceId = loDeviceID
843 loImageState := voltha.ImageState{}
844 loDeviceImageState.ImageState = &loImageState
845 loDeviceImageState.ImageState.Version = imageIdentifier
mpagenkoc26d4c02021-05-06 14:27:57 +0000846 //compared to download procedure the vendorID (from device) is secondary here
847 // and only needed in case the upgrade process is based on some ongoing download process (and can be retrieved in deviceHandler if needed)
848 // start image activation activity for each possible device
849 // assumption here is, that the concerned device was already created (automatic start after device creation not supported)
850 if handler := oo.getDeviceHandler(ctx, loDeviceID, false); handler != nil {
851 logger.Debugw(ctx, "onu image commitment requested", log.Fields{
852 "image-id": imageIdentifier, "device-id": loDeviceID})
853 //onu commitment handling called in background without immediate error evaluation here
854 // as the processing can be done for multiple ONU's and an error on one ONU should not stop processing for others
855 // state/progress/success of the request has to be verified using the Get_onu_image_status() API
mpagenko183647c2021-06-08 15:25:04 +0000856 if pImageStates, err := handler.onuSwCommitRequest(ctx, imageIdentifier); err != nil {
mpagenko38662d02021-08-11 09:45:19 +0000857 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_FAILED
858 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR //can be multiple reasons here
mpagenko183647c2021-06-08 15:25:04 +0000859 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
860 } else {
861 loDeviceImageState.ImageState.DownloadState = pImageStates.DownloadState
862 loDeviceImageState.ImageState.Reason = pImageStates.Reason
863 loDeviceImageState.ImageState.ImageState = pImageStates.ImageState
864 }
mpagenkoc26d4c02021-05-06 14:27:57 +0000865 } else {
866 //cannot start SW commitment for requested device
867 logger.Warnw(ctx, "no handler found for image commitment", log.Fields{"device-id": loDeviceID})
mpagenko183647c2021-06-08 15:25:04 +0000868 loDeviceImageState.ImageState.DownloadState = voltha.ImageState_DOWNLOAD_UNKNOWN
mpagenkoc26d4c02021-05-06 14:27:57 +0000869 loDeviceImageState.ImageState.Reason = voltha.ImageState_UNKNOWN_ERROR
870 loDeviceImageState.ImageState.ImageState = voltha.ImageState_IMAGE_COMMIT_ABORTED
mpagenkoc26d4c02021-05-06 14:27:57 +0000871 }
mpagenko2f2f2362021-06-07 08:25:22 +0000872 loResponse.DeviceImageStates = append(loResponse.DeviceImageStates, &loDeviceImageState)
mpagenkoc26d4c02021-05-06 14:27:57 +0000873 }
874 pImageResp := &loResponse
875 return pImageResp, nil
876 }
877 return nil, errors.New("invalid image commitment parameters")
mpagenko83144272021-04-27 10:06:22 +0000878}
879
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000880// Adapter interface required methods ################ end #########
881// #################################################################
khenaidoo7d3c5582021-08-11 18:09:44 -0400882
883/*
884 *
885 * ONU inter adapter service
886 *
887 */
888
889// OnuIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400890func (oo *OpenONUAC) OnuIndication(ctx context.Context, onuInd *ia.OnuIndicationMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400891 logger.Debugw(ctx, "onu-indication", log.Fields{"onu-indication": onuInd})
892
893 if onuInd == nil || onuInd.OnuIndication == nil {
894 return nil, fmt.Errorf("invalid-onu-indication-%v", onuInd)
895 }
896
897 onuIndication := onuInd.OnuIndication
898 onuOperstate := onuIndication.GetOperState()
899 waitForDhInstPresent := false
900 if onuOperstate == "up" {
901 //Race condition (relevant in BBSIM-environment only): Due to unsynchronized processing of olt-adapter and rw_core,
902 //ONU_IND_REQUEST msg by olt-adapter could arrive a little bit earlier than rw_core was able to announce the corresponding
903 //ONU by RPC of Adopt_device(). Therefore it could be necessary to wait with processing of ONU_IND_REQUEST until call of
904 //Adopt_device() arrived and DeviceHandler instance was created
905 waitForDhInstPresent = true
906 }
907 if handler := oo.getDeviceHandler(ctx, onuInd.DeviceId, waitForDhInstPresent); handler != nil {
908 logger.Infow(ctx, "onu-ind-request", log.Fields{"device-id": onuInd.DeviceId,
909 "OnuId": onuIndication.GetOnuId(),
910 "AdminState": onuIndication.GetAdminState(), "OperState": onuOperstate,
911 "SNR": onuIndication.GetSerialNumber()})
912
913 if onuOperstate == "up" {
914 if err := handler.createInterface(ctx, onuIndication); err != nil {
915 return nil, err
916 }
917 return &empty.Empty{}, nil
918 } else if (onuOperstate == "down") || (onuOperstate == "unreachable") {
Holger Hildebrandt68854a82022-09-05 07:00:21 +0000919 if err := handler.UpdateInterface(ctx); err != nil {
ozgecanetsia76db57a2022-02-03 15:32:03 +0300920 return nil, err
921 }
922 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400923 } else {
924 logger.Errorw(ctx, "unknown-onu-ind-request operState", log.Fields{"OnuId": onuIndication.GetOnuId()})
925 return nil, fmt.Errorf("invalidOperState: %s, %s", onuOperstate, onuInd.DeviceId)
926 }
927 }
928 logger.Warnw(ctx, "no handler found for received onu-ind-request", log.Fields{
929 "msgToDeviceId": onuInd.DeviceId})
930 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", onuInd.DeviceId))
931}
932
933// OmciIndication is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400934func (oo *OpenONUAC) OmciIndication(ctx context.Context, msg *ia.OmciMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400935 logger.Debugw(ctx, "omci-response", log.Fields{"parent-device-id": msg.ParentDeviceId, "child-device-id": msg.ChildDeviceId})
936
937 if handler := oo.getDeviceHandler(ctx, msg.ChildDeviceId, false); handler != nil {
938 if err := handler.handleOMCIIndication(log.WithSpanFromContext(context.Background(), ctx), msg); err != nil {
939 return nil, err
940 }
941 return &empty.Empty{}, nil
942 }
943 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", msg.ChildDeviceId))
944}
945
946// DownloadTechProfile is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400947func (oo *OpenONUAC) DownloadTechProfile(ctx context.Context, tProfile *ia.TechProfileDownloadMessage) (*empty.Empty, error) {
nikesh.krishnan1ffb8132023-05-23 03:44:13 +0530948 logger.Info(ctx, "download-tech-profile", log.Fields{"device-id": tProfile.DeviceId, "uni-id": tProfile.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400949
950 if handler := oo.getDeviceHandler(ctx, tProfile.DeviceId, false); handler != nil {
Praneeth Nalmas04600be2024-12-08 20:12:32 +0530951 handler.RLockMutexDeletionInProgressFlag()
952 if handler.GetDeletionInProgress() {
953 logger.Warnw(ctx, "Device deletion in progress - avoid processing Tech Profile", log.Fields{"device-id": tProfile.DeviceId})
954
955 handler.RUnlockMutexDeletionInProgressFlag()
956 return nil, fmt.Errorf(fmt.Sprintf("Can't proceed, device deletion is in progress-%s", tProfile.DeviceId))
957 }
958 handler.RUnlockMutexDeletionInProgressFlag()
khenaidoo7d3c5582021-08-11 18:09:44 -0400959 if err := handler.handleTechProfileDownloadRequest(log.WithSpanFromContext(context.Background(), ctx), tProfile); err != nil {
960 return nil, err
961 }
962 return &empty.Empty{}, nil
963 }
964 return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", tProfile.DeviceId))
965}
966
967// DeleteGemPort is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400968func (oo *OpenONUAC) DeleteGemPort(ctx context.Context, gPort *ia.DeleteGemPortMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -0400969 logger.Debugw(ctx, "delete-gem-port", log.Fields{"device-id": gPort.DeviceId, "uni-id": gPort.UniId})
khenaidoo7d3c5582021-08-11 18:09:44 -0400970 if handler := oo.getDeviceHandler(ctx, gPort.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530971 if handler.GetDeletionInProgress() {
972 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": gPort.DeviceId})
973 return nil, fmt.Errorf("device deletion in progress for device-id: %s", gPort.DeviceId)
974 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400975 if err := handler.handleDeleteGemPortRequest(log.WithSpanFromContext(context.Background(), ctx), gPort); err != nil {
976 return nil, err
977 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000978 } else {
979 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": gPort.DeviceId})
980 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400981 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000982 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -0400983}
984
985// DeleteTCont is part of the ONU Inter-adapter service API.
khenaidoo42dcdfd2021-10-19 17:34:12 -0400986func (oo *OpenONUAC) DeleteTCont(ctx context.Context, tConf *ia.DeleteTcontMessage) (*empty.Empty, error) {
Holger Hildebrandtba6fbe82021-12-03 14:29:42 +0000987 logger.Debugw(ctx, "delete-tcont", log.Fields{"device-id": tConf.DeviceId, "tconf": tConf})
khenaidoo7d3c5582021-08-11 18:09:44 -0400988 if handler := oo.getDeviceHandler(ctx, tConf.DeviceId, false); handler != nil {
nikesh.krishnan1249be92023-11-27 04:20:12 +0530989 if handler.GetDeletionInProgress() {
990 logger.Error(ctx, "device deletion in progres", log.Fields{"device-id": tConf.DeviceId})
991 return nil, fmt.Errorf("device deletion in progress for device-id: %s", tConf.DeviceId)
992 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400993 if err := handler.handleDeleteTcontRequest(log.WithSpanFromContext(context.Background(), ctx), tConf); err != nil {
994 return nil, err
995 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +0000996 } else {
997 logger.Debugw(ctx, "deviceHandler not found", log.Fields{"device-id": tConf.DeviceId})
998 // delete requests for objects of an already deleted ONU should be acknowledged positively - continue
khenaidoo7d3c5582021-08-11 18:09:44 -0400999 }
Holger Hildebrandt5b774062021-11-10 10:24:29 +00001000 return &empty.Empty{}, nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001001}
1002
1003/*
1004 * Parent GRPC clients
1005 */
1006
khenaidoo55cebc62021-12-08 14:44:41 -05001007func getHash(endpoint, contextInfo string) string {
1008 strToHash := endpoint + contextInfo
1009 h := fnv.New128().Sum([]byte(strToHash))
1010 return string(h)
1011}
1012
1013func (oo *OpenONUAC) updateReachabilityFromRemote(ctx context.Context, remote *common.Connection) {
1014 logger.Debugw(context.Background(), "updating-remote-connection-status", log.Fields{"remote": remote})
1015 oo.lockReachableFromRemote.Lock()
1016 defer oo.lockReachableFromRemote.Unlock()
1017 endpointHash := getHash(remote.Endpoint, remote.ContextInfo)
1018 if _, ok := oo.reachableFromRemote[endpointHash]; ok {
1019 oo.reachableFromRemote[endpointHash].lastKeepAlive = time.Now()
1020 oo.reachableFromRemote[endpointHash].keepAliveInterval = remote.KeepAliveInterval
1021 return
1022 }
1023 logger.Debugw(context.Background(), "initial-remote-connection", log.Fields{"remote": remote})
1024 oo.reachableFromRemote[endpointHash] = &reachabilityFromRemote{lastKeepAlive: time.Now(), keepAliveInterval: remote.KeepAliveInterval}
1025}
1026
Akash Soni931f9b92024-12-11 18:36:36 +05301027// func (oo *OpenONUAC) isReachableFromRemote(ctx context.Context, endpoint string, contextInfo string) bool {
1028// logger.Debugw(ctx, "checking-remote-reachability", log.Fields{"endpoint": endpoint, "context": contextInfo})
1029// oo.lockReachableFromRemote.RLock()
1030// defer oo.lockReachableFromRemote.RUnlock()
1031// endpointHash := getHash(endpoint, contextInfo)
1032// if _, ok := oo.reachableFromRemote[endpointHash]; ok {
1033// logger.Debugw(ctx, "endpoint-exists", log.Fields{"last-keep-alive": time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive)})
1034// // Assume the connection is down if we did not receive 2 keep alives in succession
1035// maxKeepAliveWait := time.Duration(oo.reachableFromRemote[endpointHash].keepAliveInterval * 2)
1036// return time.Since(oo.reachableFromRemote[endpointHash].lastKeepAlive) <= maxKeepAliveWait
1037// }
1038// return false
1039// }
khenaidoo55cebc62021-12-08 14:44:41 -05001040
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301041// stopAllGrpcClients stops all grpc clients in use
khenaidoof3333552021-12-15 16:52:31 -05001042func (oo *OpenONUAC) stopAllGrpcClients(ctx context.Context) {
1043 // Stop the clients that connect to the parent
1044 oo.lockParentAdapterClients.Lock()
1045 for key := range oo.parentAdapterClients {
1046 oo.parentAdapterClients[key].Stop(ctx)
1047 delete(oo.parentAdapterClients, key)
1048 }
1049 oo.lockParentAdapterClients.Unlock()
1050
1051 // Stop core client connection
1052 oo.coreClient.Stop(ctx)
1053}
1054
khenaidoo7d3c5582021-08-11 18:09:44 -04001055func (oo *OpenONUAC) setupParentInterAdapterClient(ctx context.Context, endpoint string) error {
1056 logger.Infow(ctx, "setting-parent-adapter-connection", log.Fields{"parent-endpoint": endpoint})
1057 oo.lockParentAdapterClients.Lock()
1058 defer oo.lockParentAdapterClients.Unlock()
1059 if _, ok := oo.parentAdapterClients[endpoint]; ok {
1060 return nil
1061 }
1062
khenaidoo55cebc62021-12-08 14:44:41 -05001063 childClient, err := vgrpc.NewClient(
1064 oo.config.AdapterEndpoint,
1065 endpoint,
khenaidoof3333552021-12-15 16:52:31 -05001066 "olt_inter_adapter_service.OltInterAdapterService",
khenaidoo55cebc62021-12-08 14:44:41 -05001067 oo.oltAdapterRestarted)
khenaidoo7d3c5582021-08-11 18:09:44 -04001068
1069 if err != nil {
1070 return err
1071 }
nikesh.krishnance4879a2023-08-01 18:36:57 +05301072 retryCodes := []codes.Code{
1073 codes.Unavailable, // server is currently unavailable
1074 codes.DeadlineExceeded, // deadline for the operation was exceeded
1075 }
1076 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(oo.config.PerRPCRetryTimeout, 0.2))
1077 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 -04001078
1079 oo.parentAdapterClients[endpoint] = childClient
nikesh.krishnance4879a2023-08-01 18:36:57 +05301080 go oo.parentAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), getOltInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo7d3c5582021-08-11 18:09:44 -04001081 // Wait until we have a connection to the child adapter.
1082 // Unlimited retries or until context expires
1083 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
1084 backoff := vgrpc.NewBackoff(oo.config.MinBackoffRetryDelay, oo.config.MaxBackoffRetryDelay, 0)
1085 for {
1086 client, err := oo.parentAdapterClients[endpoint].GetOltInterAdapterServiceClient()
1087 if err == nil && client != nil {
1088 logger.Infow(subCtx, "connected-to-parent-adapter", log.Fields{"parent-endpoint": endpoint})
1089 break
1090 }
1091 logger.Warnw(subCtx, "connection-to-parent-adapter-not-ready", log.Fields{"error": err, "parent-endpoint": endpoint})
1092 // Backoff
1093 if err = backoff.Backoff(subCtx); err != nil {
1094 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "parent-endpoint": endpoint})
1095 break
1096 }
1097 }
1098 return nil
1099}
1100
khenaidoo42dcdfd2021-10-19 17:34:12 -04001101func (oo *OpenONUAC) getParentAdapterServiceClient(endpoint string) (olt_inter_adapter_service.OltInterAdapterServiceClient, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001102 // First check from cache
1103 oo.lockParentAdapterClients.RLock()
1104 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1105 oo.lockParentAdapterClients.RUnlock()
1106 return pgClient.GetOltInterAdapterServiceClient()
1107 }
1108 oo.lockParentAdapterClients.RUnlock()
1109
1110 // Set the parent connection - can occur on restarts
1111 ctx, cancel := context.WithTimeout(context.Background(), oo.config.RPCTimeout)
1112 err := oo.setupParentInterAdapterClient(ctx, endpoint)
1113 cancel()
1114 if err != nil {
1115 return nil, err
1116 }
1117
1118 // Get the parent client now
1119 oo.lockParentAdapterClients.RLock()
1120 defer oo.lockParentAdapterClients.RUnlock()
1121 if pgClient, ok := oo.parentAdapterClients[endpoint]; ok {
1122 return pgClient.GetOltInterAdapterServiceClient()
1123 }
1124
1125 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
1126}
1127
1128// TODO: Any action the adapter needs to do following an olt adapter restart?
1129func (oo *OpenONUAC) oltAdapterRestarted(ctx context.Context, endPoint string) error {
1130 logger.Errorw(ctx, "olt-adapter-restarted", log.Fields{"endpoint": endPoint})
1131 return nil
1132}
1133
khenaidoof3333552021-12-15 16:52:31 -05001134// getOltInterAdapterServiceClientHandler is used to setup the remote gRPC service
1135func getOltInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
1136 if conn == nil {
khenaidoo7d3c5582021-08-11 18:09:44 -04001137 return nil
1138 }
khenaidoof3333552021-12-15 16:52:31 -05001139 return olt_inter_adapter_service.NewOltInterAdapterServiceClient(conn)
khenaidoo7d3c5582021-08-11 18:09:44 -04001140}
1141
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001142func (oo *OpenONUAC) forceDeleteDeviceKvData(ctx context.Context, aDeviceID string) error {
1143 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 -08001144 var errorsList []error
1145 // delete onu persitent data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001146 onuBaseKvStorePath := fmt.Sprintf(cmn.CBasePathOnuKVStore, oo.cm.Backend.PathPrefix)
1147 logger.Debugw(ctx, "SetOnuKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": onuBaseKvStorePath,
1148 "device-id": aDeviceID})
1149 onuKvbackend := &db.Backend{
1150 Client: oo.kvClient,
1151 StoreType: oo.KVStoreType,
1152 Address: oo.KVStoreAddress,
1153 Timeout: oo.KVStoreTimeout,
1154 PathPrefix: onuBaseKvStorePath,
1155 }
1156 err := onuKvbackend.DeleteWithPrefix(ctx, aDeviceID)
1157 if err != nil {
1158 logger.Errorw(ctx, "unable to delete in KVstore", log.Fields{"service": onuBaseKvStorePath, "device-id": aDeviceID, "err": err})
1159 // continue to delete kv data, but accumulate any errors
1160 errorsList = append(errorsList, err)
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001161 }
Girish Gowdraf10379e2022-02-02 21:49:44 -08001162 // delete pm data
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001163 pmBaseKvStorePath := fmt.Sprintf(pmmgr.CPmKvStorePrefixBase, oo.cm.Backend.PathPrefix)
1164 logger.Debugw(ctx, "SetPmKVStoreBackend", log.Fields{"IpTarget": oo.KVStoreAddress, "BasePathKvStore": pmBaseKvStorePath,
1165 "device-id": aDeviceID})
Girish Gowdraf10379e2022-02-02 21:49:44 -08001166 pmKvbackend := &db.Backend{
1167 Client: oo.kvClient,
1168 StoreType: oo.KVStoreType,
1169 Address: oo.KVStoreAddress,
1170 Timeout: oo.KVStoreTimeout,
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001171 PathPrefix: pmBaseKvStorePath,
Girish Gowdraf10379e2022-02-02 21:49:44 -08001172 }
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001173 err = pmKvbackend.DeleteWithPrefix(ctx, aDeviceID)
Girish Gowdraf10379e2022-02-02 21:49:44 -08001174 if err != nil {
Girish Gowdrae9ff2612022-02-04 11:34:33 -08001175 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 -08001176 // accumulate any errors
1177 errorsList = append(errorsList, err)
1178 }
1179 if len(errorsList) > 0 {
1180 return fmt.Errorf("one or more error deleting kv data, error: %v", errorsList)
1181 }
Holger Hildebrandtc69f0742021-11-16 13:48:00 +00001182 return nil
1183}
1184
khenaidoof3333552021-12-15 16:52:31 -05001185// GetHealthStatus is used by the voltha core to open a streaming connection with the onu adapter.
1186func (oo *OpenONUAC) GetHealthStatus(stream adapter_service.AdapterService_GetHealthStatusServer) error {
1187 ctx := context.Background()
1188 logger.Debugw(ctx, "receive-stream-connection", log.Fields{"stream": stream})
1189
1190 if stream == nil {
1191 return fmt.Errorf("conn-is-nil %v", stream)
1192 }
1193 initialRequestTime := time.Now()
1194 var remoteClient *common.Connection
1195 var tempClient *common.Connection
1196 var err error
1197loop:
1198 for {
1199 tempClient, err = stream.Recv()
1200 if err != nil {
1201 logger.Warnw(ctx, "received-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1202 break loop
1203 }
1204 // Send a response back
1205 err = stream.Send(&health.HealthStatus{State: health.HealthStatus_HEALTHY})
1206 if err != nil {
1207 logger.Warnw(ctx, "sending-stream-error", log.Fields{"remote-client": remoteClient, "error": err})
1208 break loop
1209 }
1210 remoteClient = tempClient
1211
1212 logger.Debugw(ctx, "received-keep-alive", log.Fields{"remote-client": remoteClient})
1213
1214 select {
1215 case <-stream.Context().Done():
1216 logger.Infow(ctx, "stream-keep-alive-context-done", log.Fields{"remote-client": remoteClient, "error": stream.Context().Err()})
1217 break loop
1218 case <-oo.exitChannel:
1219 logger.Warnw(ctx, "received-stop", log.Fields{"remote-client": remoteClient, "initial-conn-time": initialRequestTime})
1220 break loop
1221 default:
1222 }
1223 }
1224 logger.Errorw(ctx, "connection-down", log.Fields{"remote-client": remoteClient, "error": err, "initial-conn-time": initialRequestTime})
1225 return err
1226}
1227
khenaidoo7d3c5582021-08-11 18:09:44 -04001228/*
1229 *
1230 * Unimplemented APIs
1231 *
1232 */
1233
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301234// GetOfpDeviceInfo returns OFP information for the given device. Method not implemented as per [VOL-3202].
khenaidoo7d3c5582021-08-11 18:09:44 -04001235// 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 -04001236func (oo *OpenONUAC) GetOfpDeviceInfo(ctx context.Context, device *voltha.Device) (*ca.SwitchCapability, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001237 return nil, errors.New("unImplemented")
1238}
1239
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301240// SimulateAlarm is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001241func (oo *OpenONUAC) SimulateAlarm(context.Context, *ca.SimulateAlarmMessage) (*common.OperationResp, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001242 return nil, errors.New("unImplemented")
1243}
1244
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301245// SetExtValue is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001246func (oo *OpenONUAC) SetExtValue(context.Context, *ca.SetExtValueMessage) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001247 return nil, errors.New("unImplemented")
1248}
1249
Akash Soni3c176c62024-12-04 13:30:43 +05301250// SetSingleValue sets a single value based on the given request and returns the response.
1251func (oo *OpenONUAC) SetSingleValue(ctx context.Context, request *extension.SingleSetValueRequest) (*extension.SingleSetValueResponse, error) {
1252 logger.Infow(ctx, "single_set_value_request", log.Fields{"request": request})
1253
1254 errResp := func(status extension.SetValueResponse_Status,
1255 reason extension.SetValueResponse_ErrorReason) *extension.SingleSetValueResponse {
1256 return &extension.SingleSetValueResponse{
1257 Response: &extension.SetValueResponse{
1258 Status: status,
1259 ErrReason: reason,
1260 },
1261 }
1262 }
1263 if handler := oo.getDeviceHandler(ctx, request.TargetId, false); handler != nil {
1264 switch reqType := request.GetRequest().GetRequest().(type) {
1265 case *extension.SetValueRequest_AppOffloadOnuConfig:
1266 return handler.setOnuOffloadStats(ctx, reqType.AppOffloadOnuConfig), nil
1267 default:
1268 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_UNSUPPORTED), nil
1269 }
1270 }
1271
1272 logger.Infow(ctx, "Single_set_value_request failed ", log.Fields{"request": request})
1273 return errResp(extension.SetValueResponse_ERROR, extension.SetValueResponse_INVALID_DEVICE_ID), nil
khenaidoo7d3c5582021-08-11 18:09:44 -04001274}
1275
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301276// StartOmciTest not implemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001277func (oo *OpenONUAC) StartOmciTest(ctx context.Context, test *ca.OMCITest) (*omci.TestResponse, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001278 return nil, errors.New("unImplemented")
1279}
1280
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301281// SuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001282func (oo *OpenONUAC) SuppressEvent(ctx context.Context, filter *voltha.EventFilter) (*empty.Empty, error) {
1283 return nil, errors.New("unImplemented")
1284}
1285
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301286// UnSuppressEvent unimplemented
khenaidoo7d3c5582021-08-11 18:09:44 -04001287func (oo *OpenONUAC) UnSuppressEvent(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// GetImageDownloadStatus is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001292func (oo *OpenONUAC) GetImageDownloadStatus(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001293 return nil, errors.New("unImplemented")
1294}
1295
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301296// CancelImageDownload is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001297func (oo *OpenONUAC) CancelImageDownload(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// RevertImageUpdate is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001302func (oo *OpenONUAC) RevertImageUpdate(ctx context.Context, imageInfo *ca.ImageDownloadMessage) (*voltha.ImageDownload, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001303 return nil, errors.New("unImplemented")
1304}
1305
1306// UpdateFlowsBulk is unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001307func (oo *OpenONUAC) UpdateFlowsBulk(ctx context.Context, flows *ca.BulkFlows) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001308 return nil, errors.New("unImplemented")
1309}
1310
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301311// SelfTestDevice unimplented
khenaidoo7d3c5582021-08-11 18:09:44 -04001312func (oo *OpenONUAC) SelfTestDevice(ctx context.Context, device *voltha.Device) (*empty.Empty, error) {
1313 return nil, errors.New("unImplemented")
1314}
1315
praneeth nalmas5a0a5502022-12-23 15:57:00 +05301316// SendPacketOut sends packet out to the device
khenaidoo42dcdfd2021-10-19 17:34:12 -04001317func (oo *OpenONUAC) SendPacketOut(ctx context.Context, packet *ca.PacketOut) (*empty.Empty, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001318 return nil, errors.New("unImplemented")
1319}
1320
1321// EnablePort to Enable PON/NNI interface - seems not to be used/required according to python code
1322func (oo *OpenONUAC) EnablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1323 return nil, errors.New("unImplemented")
1324}
1325
1326// DisablePort to Disable pon/nni interface - seems not to be used/required according to python code
1327func (oo *OpenONUAC) DisablePort(ctx context.Context, port *voltha.Port) (*empty.Empty, error) {
1328 return nil, errors.New("unImplemented")
1329}
1330
1331// GetExtValue - unimplemented
khenaidoo42dcdfd2021-10-19 17:34:12 -04001332func (oo *OpenONUAC) GetExtValue(ctx context.Context, extInfo *ca.GetExtValueMessage) (*extension.ReturnValues, error) {
khenaidoo7d3c5582021-08-11 18:09:44 -04001333 return nil, errors.New("unImplemented")
1334}
1335
1336// ChildDeviceLost - unimplemented
1337func (oo *OpenONUAC) ChildDeviceLost(ctx context.Context, childDevice *voltha.Device) (*empty.Empty, error) {
1338 return nil, errors.New("unImplemented")
1339}
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +00001340
1341// GetSupportedFsms - TODO: add comment
1342func (oo *OpenONUAC) GetSupportedFsms() *cmn.OmciDeviceFsms {
1343 return oo.pSupportedFsms
1344}
1345
1346// LockMutexMibTemplateGenerated - TODO: add comment
1347func (oo *OpenONUAC) LockMutexMibTemplateGenerated() {
1348 oo.mutexMibTemplateGenerated.Lock()
1349}
1350
1351// UnlockMutexMibTemplateGenerated - TODO: add comment
1352func (oo *OpenONUAC) UnlockMutexMibTemplateGenerated() {
1353 oo.mutexMibTemplateGenerated.Unlock()
1354}
1355
1356// GetMibTemplatesGenerated - TODO: add comment
1357func (oo *OpenONUAC) GetMibTemplatesGenerated(mibTemplatePath string) (value bool, exist bool) {
1358 value, exist = oo.mibTemplatesGenerated[mibTemplatePath]
1359 return value, exist
1360}
1361
1362// SetMibTemplatesGenerated - TODO: add comment
1363func (oo *OpenONUAC) SetMibTemplatesGenerated(mibTemplatePath string, value bool) {
1364 oo.mibTemplatesGenerated[mibTemplatePath] = value
1365}
1366
1367// RLockMutexDeviceHandlersMap - TODO: add comment
1368func (oo *OpenONUAC) RLockMutexDeviceHandlersMap() {
1369 oo.mutexDeviceHandlersMap.RLock()
1370}
1371
1372// RUnlockMutexDeviceHandlersMap - TODO: add comment
1373func (oo *OpenONUAC) RUnlockMutexDeviceHandlersMap() {
1374 oo.mutexDeviceHandlersMap.RUnlock()
1375}
1376
1377// GetDeviceHandler - TODO: add comment
1378func (oo *OpenONUAC) GetDeviceHandler(deviceID string) (value cmn.IdeviceHandler, exist bool) {
1379 value, exist = oo.deviceHandlers[deviceID]
1380 return value, exist
1381}
Praneeth Kumar Nalmas8f8f0c02024-10-22 19:29:09 +05301382
1383// GetONUMIBDBMap - Returns the Map corresponding to ONT type and the MIB common Instance.
1384func (oo *OpenONUAC) GetONUMIBDBMap() devdb.OnuMCmnMEDBMap {
1385 return oo.MibDatabaseMap
1386}
1387
1388// RLockMutexMIBDatabaseMap acquires a read lock on the mutex associated with the MIBDatabaseMap.
1389func (oo *OpenONUAC) RLockMutexMIBDatabaseMap() {
1390 oo.mutexMibDatabaseMap.RLock()
1391}
1392
1393// RUnlockMutexMIBDatabaseMap releases the read lock on the mutex associated with the MIBDatabaseMap.
1394func (oo *OpenONUAC) RUnlockMutexMIBDatabaseMap() {
1395 oo.mutexMibDatabaseMap.RUnlock()
1396}
1397
1398// LockMutexMIBDatabaseMap locks the mutex associated with the MIBDatabaseMap.
1399// Should be called before any operations that modify or read from the MIBDatabaseMap.
1400func (oo *OpenONUAC) LockMutexMIBDatabaseMap() {
1401 oo.mutexMibDatabaseMap.Lock()
1402}
1403
1404// UnlockMutexMIBDatabaseMap unlocks the mutex associated with the MIBDatabaseMap.
1405// Should be called after completing operations that require exclusive access
1406// to the MIBDatabaseMap, ensuring the mutex is released for other goroutines.
1407func (oo *OpenONUAC) UnlockMutexMIBDatabaseMap() {
1408 oo.mutexMibDatabaseMap.Unlock()
1409}
1410
1411// CreateEntryAtMibDatabaseMap adds an entry to the MibDatabaseMap if it doesn't exist
1412func (oo *OpenONUAC) CreateEntryAtMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, error) {
1413 oo.mutexMibDatabaseMap.Lock()
1414 defer oo.mutexMibDatabaseMap.Unlock()
1415
1416 // Check if the key already exists
1417 if mibEntry, exists := oo.MibDatabaseMap[key]; exists {
1418 logger.Warnw(ctx, "Entry already exists in MIB Database Map", log.Fields{"remote-client": key})
1419 return mibEntry, fmt.Errorf("entry already exists for key: %s", key)
1420 }
1421
1422 value := devdb.NewOnuCmnMEDB(ctx)
1423
1424 logger.Infow(ctx, "Created a new Common MIB Database Entry", log.Fields{"remote-client": key})
1425 oo.MibDatabaseMap[key] = value
1426
1427 return value, nil
1428}
1429
1430// FetchEntryFromMibDatabaseMap fetches a references to common ME DB for a MIB Template from the MibDatabaseMap
1431// If a valid entry exists returns pointer to cmnDB else returns nil.
1432func (oo *OpenONUAC) FetchEntryFromMibDatabaseMap(ctx context.Context, key string) (*devdb.OnuCmnMEDB, bool) {
1433 oo.mutexMibDatabaseMap.RLock()
1434 defer oo.mutexMibDatabaseMap.RUnlock()
1435 value, exists := oo.MibDatabaseMap[key]
1436 if !exists {
1437 return nil, false
1438 }
1439 return value, true
1440
1441}
1442
1443// ResetEntryFromMibDatabaseMap resets the ME values from the Maps.
1444func (oo *OpenONUAC) ResetEntryFromMibDatabaseMap(ctx context.Context, key string) {
1445 oo.mutexMibDatabaseMap.RLock()
1446 onuCmnMEDB, exists := oo.MibDatabaseMap[key]
1447 oo.mutexMibDatabaseMap.RUnlock()
1448 if exists {
1449 // Lock the MeDbLock to ensure thread-safe operation
1450 onuCmnMEDB.MeDbLock.Lock()
1451 defer onuCmnMEDB.MeDbLock.Unlock()
1452
1453 // Reset the MeDb and UnknownMeAndAttribDb maps
1454 onuCmnMEDB.MeDb = make(devdb.MeDbMap)
1455 onuCmnMEDB.UnknownMeAndAttribDb = make(devdb.UnknownMeAndAttribDbMap)
1456
1457 }
1458}
1459
1460// DeleteEntryFromMibDatabaseMap deletes an entry from the MibDatabaseMap
1461func (oo *OpenONUAC) DeleteEntryFromMibDatabaseMap(key string) {
1462 oo.mutexMibDatabaseMap.Lock()
1463 defer oo.mutexMibDatabaseMap.Unlock()
1464 delete(oo.MibDatabaseMap, key)
1465}