blob: 6d18b7e35695259e3a085b55863f9574fbb275eb [file] [log] [blame]
Girish Gowdra64503432020-01-07 10:59:10 +05301/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package core
18
19import (
20 "context"
21 "encoding/hex"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "github.com/cenkalti/backoff/v3"
26 "github.com/opencord/openolt-scale-tester/config"
27 "github.com/opencord/voltha-lib-go/v2/pkg/db/kvstore"
28 "github.com/opencord/voltha-lib-go/v2/pkg/log"
29 "github.com/opencord/voltha-lib-go/v2/pkg/techprofile"
30 oop "github.com/opencord/voltha-protos/v2/go/openolt"
31 "google.golang.org/grpc"
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/status"
34 "io"
35 "io/ioutil"
36 "os"
37 "strconv"
38 "sync"
39 "syscall"
40 "time"
41)
42
43const (
44 ReasonOk = "OK"
45 TechProfileKVPath = "service/voltha/technology_profiles/%s/%d" // service/voltha/technology_profiles/xgspon/<tech_profile_tableID>
Thiyagarajan Subramanib83b0432020-01-08 13:43:28 +053046 DTWorkFlow = "DT"
Girish Gowdra64503432020-01-07 10:59:10 +053047)
48
49type OnuDeviceKey struct {
50 onuID uint32
51 ponInfID uint32
52}
53
54type OpenOltManager struct {
55 ipPort string
56 deviceInfo *oop.DeviceInfo
57 OnuDeviceMap map[OnuDeviceKey]*OnuDevice `json:"onuDeviceMap"`
58 TechProfile map[uint32]*techprofile.TechProfileIf
59 clientConn *grpc.ClientConn
60 openOltClient oop.OpenoltClient
61 testConfig *config.OpenOltScaleTesterConfig
62 rsrMgr *OpenOltResourceMgr
63 lockRsrAlloc sync.RWMutex
64}
65
66func init() {
67 _, _ = log.AddPackage(log.JSON, log.DebugLevel, nil)
68}
69
70func NewOpenOltManager(ipPort string) *OpenOltManager {
71 log.Infow("initialized openolt manager with ipPort", log.Fields{"ipPort": ipPort})
72 return &OpenOltManager{
73 ipPort: ipPort,
74 OnuDeviceMap: make(map[OnuDeviceKey]*OnuDevice),
75 lockRsrAlloc: sync.RWMutex{},
76 }
77}
78
79func (om *OpenOltManager) readAndLoadTPsToEtcd() {
80 var byteValue []byte
81 var err error
82 // Verify that etcd is up before starting the application.
83 etcdIpPort := "http://" + om.testConfig.KVStoreHost + ":" + strconv.Itoa(om.testConfig.KVStorePort)
84 client, err := kvstore.NewEtcdClient(etcdIpPort, 5)
85 if err != nil || client == nil {
86 log.Fatal("error-initializing-etcd-client")
87 return
88 }
89
90 // Load TPs to etcd for each of the specified tech-profiles
91 for _, tpID := range om.testConfig.TpIDList {
92 // Below should translate to something like "/app/ATT-64.json"
93 // The TP file should exist.
94 tpFilePath := "/app/" + om.testConfig.WorkflowName + "-" + strconv.Itoa(tpID) + ".json"
95 // Open our jsonFile
96 jsonFile, err := os.Open(tpFilePath)
97 // if we os.Open returns an error then handle it
98 if err != nil {
99 log.Fatalw("could-not-find-tech-profile", log.Fields{"err": err, "tpFile": tpFilePath})
100 }
101 log.Debugw("tp-file-opened-successfully", log.Fields{"tpFile": tpFilePath})
102
103 // read our opened json file as a byte array.
104 if byteValue, err = ioutil.ReadAll(jsonFile); err != nil {
105 log.Fatalw("could-not-read-tp-file", log.Fields{"err": err, "tpFile": tpFilePath})
106 }
107
108 var tp techprofile.TechProfile
109
110 if err = json.Unmarshal(byteValue, &tp); err != nil {
111 log.Fatalw("could-not-unmarshal-tp", log.Fields{"err": err, "tpFile": tpFilePath})
112 } else {
113 log.Infow("tp-read-from-file", log.Fields{"tp": tp, "tpFile": tpFilePath})
114 }
115 kvPath := fmt.Sprintf(TechProfileKVPath, om.deviceInfo.Technology, tpID)
116 tpJson, err := json.Marshal(tp)
117 err = client.Put(kvPath, tpJson, 2)
118 if err != nil {
119 log.Fatalw("tp-put-to-etcd-failed", log.Fields{"tpPath": kvPath, "err": err})
120 }
121 // verify the PUT succeeded.
122 kvResult, err := client.Get(kvPath, 2)
123 if kvResult == nil {
124 log.Fatal("tp-not-found-on-kv-after-load", log.Fields{"key": kvPath, "err": err})
125 } else {
126 var KvTpIns techprofile.TechProfile
127 var resPtr = &KvTpIns
128 if value, err := kvstore.ToByte(kvResult.Value); err == nil {
129 if err = json.Unmarshal(value, resPtr); err != nil {
130 log.Fatal("error-unmarshal-kv-result", log.Fields{"err": err, "key": kvPath, "value": value})
131 } else {
132 log.Infow("verified-ok-that-tp-load-was-good", log.Fields{"tpID": tpID, "kvPath": kvPath})
133 _ = jsonFile.Close()
134 continue
135 }
136 }
137 }
138 }
139}
140
141func (om *OpenOltManager) Start(testConfig *config.OpenOltScaleTesterConfig) error {
142 var err error
143 om.testConfig = testConfig
144
145 // Establish gRPC connection with the device
146 if om.clientConn, err = grpc.Dial(om.ipPort, grpc.WithInsecure(), grpc.WithBlock()); err != nil {
147 log.Errorw("Failed to dial device", log.Fields{"ipPort": om.ipPort, "err": err})
148 return err
149 }
150 om.openOltClient = oop.NewOpenoltClient(om.clientConn)
151
152 // Populate Device Info
153 if deviceInfo, err := om.populateDeviceInfo(); err != nil {
154 log.Error("error fetching device info", log.Fields{"err": err, "deviceInfo": deviceInfo})
155 return err
156 }
157
158 // Read and load TPs to etcd.
159 om.readAndLoadTPsToEtcd()
160
161 log.Info("etcd-up-and-running--tp-loaded-successfully")
162
163 if om.rsrMgr = NewResourceMgr("ABCD", om.testConfig.KVStoreHost+":"+strconv.Itoa(om.testConfig.KVStorePort),
164 "etcd", "openolt", om.deviceInfo); om.rsrMgr == nil {
165 log.Error("Error while instantiating resource manager")
166 return errors.New("instantiating resource manager failed")
167 }
168
169 om.TechProfile = make(map[uint32]*techprofile.TechProfileIf)
170 if err = om.populateTechProfilePerPonPort(); err != nil {
171 log.Error("Error while populating tech profile mgr\n")
172 return errors.New("error-loading-tech-profile-per-ponPort")
173 }
174
175 // Start reading indications
176 go om.readIndications()
177
178 // Provision OLT NNI Trap flows as needed by the Workflow
Thiyagarajan Subramanic4f8da82020-02-05 16:08:26 +0530179 if err = ProvisionNniTrapFlow(om.openOltClient, om.testConfig, om.rsrMgr); err != nil {
180 log.Error("failed-to-add-nni-trap-flow", log.Fields{"err": err})
Girish Gowdra64503432020-01-07 10:59:10 +0530181 }
182
183 // Provision ONUs one by one
184 go om.provisionONUs()
185
186 return nil
187
188}
189
190func (om *OpenOltManager) populateDeviceInfo() (*oop.DeviceInfo, error) {
191 var err error
192
193 if om.deviceInfo, err = om.openOltClient.GetDeviceInfo(context.Background(), new(oop.Empty)); err != nil {
194 log.Errorw("Failed to fetch device info", log.Fields{"err": err})
195 return nil, err
196 }
197
198 if om.deviceInfo == nil {
199 log.Errorw("Device info is nil", log.Fields{})
200 return nil, errors.New("failed to get device info from OLT")
201 }
202
203 log.Debugw("Fetched device info", log.Fields{"deviceInfo": om.deviceInfo})
204
205 return om.deviceInfo, nil
206}
207
208func (om *OpenOltManager) provisionONUs() {
209 var numOfONUsPerPon uint
210 var i, j, onuID uint32
211 var err error
212 oltChan := make(chan bool)
213 numOfONUsPerPon = om.testConfig.NumOfOnu / uint(om.deviceInfo.PonPorts)
214 if oddONUs := om.testConfig.NumOfOnu % uint(om.deviceInfo.PonPorts); oddONUs > 0 {
215 log.Warnw("Odd number ONUs left out of provisioning", log.Fields{"oddONUs": oddONUs})
216 }
217 totalOnusToProvision := numOfONUsPerPon * uint(om.deviceInfo.PonPorts)
218 log.Infow("***** all-onu-provision-started ******",
219 log.Fields{"totalNumOnus": totalOnusToProvision,
220 "numOfOnusPerPon": numOfONUsPerPon,
221 "numOfPons": om.deviceInfo.PonPorts})
222 for i = 0; i < om.deviceInfo.PonPorts; i++ {
223 for j = 0; j < uint32(numOfONUsPerPon); j++ {
224 // TODO: More work with ONU provisioning
225 om.lockRsrAlloc.Lock()
226 sn := GenerateNextONUSerialNumber()
227 om.lockRsrAlloc.Unlock()
228 log.Debugw("provisioning onu", log.Fields{"onuID": j, "ponPort": i, "serialNum": sn})
229 if onuID, err = om.rsrMgr.GetONUID(i); err != nil {
230 log.Errorw("error getting onu id", log.Fields{"err": err})
231 continue
232 }
233 log.Infow("onu-provision-started-from-olt-manager", log.Fields{"onuId": onuID, "ponIntf": i})
234 go om.activateONU(i, onuID, sn, om.stringifySerialNumber(sn), oltChan)
235 // Wait for complete ONU provision to succeed, including provisioning the subscriber
236 <-oltChan
237 log.Infow("onu-provision-completed-from-olt-manager", log.Fields{"onuId": onuID, "ponIntf": i})
238
239 // Sleep for configured time before provisioning next ONU
240 time.Sleep(time.Duration(om.testConfig.TimeIntervalBetweenSubs))
241 }
242 }
243 log.Info("******** all-onu-provisioning-completed *******")
244
245 // TODO: We need to dump the results at the end. But below json marshall does not work
246 // We will need custom Marshal function.
247 /*
248 e, err := json.Marshal(om)
249 if err != nil {
250 fmt.Println(err)
251 return
252 }
253 fmt.Println(string(e))
254 */
255
256 // Stop the process once the job is done
257 _ = syscall.Kill(syscall.Getpid(), syscall.SIGINT)
258}
259
260func (om *OpenOltManager) activateONU(intfID uint32, onuID uint32, serialNum *oop.SerialNumber, serialNumber string, oltCh chan bool) {
261 log.Debugw("activate-onu", log.Fields{"intfID": intfID, "onuID": onuID, "serialNum": serialNum, "serialNumber": serialNumber})
262 // TODO: need resource manager
263 var pir uint32 = 1000000
264 var onuDevice = OnuDevice{
265 SerialNum: serialNumber,
266 OnuID: onuID,
267 PonIntf: intfID,
268 openOltClient: om.openOltClient,
269 testConfig: om.testConfig,
270 rsrMgr: om.rsrMgr,
271 }
272 var err error
273 onuDeviceKey := OnuDeviceKey{onuID: onuID, ponInfID: intfID}
274 Onu := oop.Onu{IntfId: intfID, OnuId: onuID, SerialNumber: serialNum, Pir: pir}
275 now := time.Now()
276 nanos := now.UnixNano()
277 milliStart := nanos / 1000000
278 onuDevice.OnuProvisionStartTime = time.Unix(0, nanos)
279 if _, err = om.openOltClient.ActivateOnu(context.Background(), &Onu); err != nil {
280 st, _ := status.FromError(err)
281 if st.Code() == codes.AlreadyExists {
282 log.Debug("ONU activation is in progress", log.Fields{"SerialNumber": serialNumber})
283 oltCh <- false
284 } else {
285 nanos = now.UnixNano()
286 milliEnd := nanos / 1000000
287 onuDevice.OnuProvisionEndTime = time.Unix(0, nanos)
288 onuDevice.OnuProvisionDurationInMs = milliEnd - milliStart
289 log.Errorw("activate-onu-failed", log.Fields{"Onu": Onu, "err ": err})
290 onuDevice.Reason = err.Error()
291 oltCh <- false
292 }
293 } else {
294 nanos = now.UnixNano()
295 milliEnd := nanos / 1000000
296 onuDevice.OnuProvisionEndTime = time.Unix(0, nanos)
297 onuDevice.OnuProvisionDurationInMs = milliEnd - milliStart
298 onuDevice.Reason = ReasonOk
299 log.Infow("activated-onu", log.Fields{"SerialNumber": serialNumber})
300 }
301
302 om.OnuDeviceMap[onuDeviceKey] = &onuDevice
303
304 // If ONU activation was success provision the ONU
305 if err == nil {
306 // start provisioning the ONU
307 go om.OnuDeviceMap[onuDeviceKey].Start(oltCh)
308 }
309}
310
311func (om *OpenOltManager) stringifySerialNumber(serialNum *oop.SerialNumber) string {
312 if serialNum != nil {
313 return string(serialNum.VendorId) + om.stringifyVendorSpecific(serialNum.VendorSpecific)
314 }
315 return ""
316}
317
318func (om *OpenOltManager) stringifyVendorSpecific(vendorSpecific []byte) string {
319 tmp := fmt.Sprintf("%x", (uint32(vendorSpecific[0])>>4)&0x0f) +
320 fmt.Sprintf("%x", uint32(vendorSpecific[0]&0x0f)) +
321 fmt.Sprintf("%x", (uint32(vendorSpecific[1])>>4)&0x0f) +
322 fmt.Sprintf("%x", (uint32(vendorSpecific[1]))&0x0f) +
323 fmt.Sprintf("%x", (uint32(vendorSpecific[2])>>4)&0x0f) +
324 fmt.Sprintf("%x", (uint32(vendorSpecific[2]))&0x0f) +
325 fmt.Sprintf("%x", (uint32(vendorSpecific[3])>>4)&0x0f) +
326 fmt.Sprintf("%x", (uint32(vendorSpecific[3]))&0x0f)
327 return tmp
328}
329
330// readIndications to read the indications from the OLT device
331func (om *OpenOltManager) readIndications() {
332 defer log.Errorw("Indications ended", log.Fields{})
333 indications, err := om.openOltClient.EnableIndication(context.Background(), new(oop.Empty))
334 if err != nil {
335 log.Errorw("Failed to read indications", log.Fields{"err": err})
336 return
337 }
338 if indications == nil {
339 log.Errorw("Indications is nil", log.Fields{})
340 return
341 }
342
343 // Create an exponential backoff around re-enabling indications. The
344 // maximum elapsed time for the back off is set to 0 so that we will
345 // continue to retry. The max interval defaults to 1m, but is set
346 // here for code clarity
347 indicationBackoff := backoff.NewExponentialBackOff()
348 indicationBackoff.MaxElapsedTime = 0
349 indicationBackoff.MaxInterval = 1 * time.Minute
350 for {
351 indication, err := indications.Recv()
352 if err == io.EOF {
353 log.Infow("EOF for indications", log.Fields{"err": err})
354 // Use an exponential back off to prevent getting into a tight loop
355 duration := indicationBackoff.NextBackOff()
356 if duration == backoff.Stop {
357 // If we reach a maximum then warn and reset the backoff
358 // timer and keep attempting.
359 log.Warnw("Maximum indication backoff reached, resetting backoff timer",
360 log.Fields{"max_indication_backoff": indicationBackoff.MaxElapsedTime})
361 indicationBackoff.Reset()
362 }
363 time.Sleep(indicationBackoff.NextBackOff())
364 indications, err = om.openOltClient.EnableIndication(context.Background(), new(oop.Empty))
365 if err != nil {
366 log.Errorw("Failed to read indications", log.Fields{"err": err})
367 return
368 }
369 continue
370 }
371 if err != nil {
372 log.Infow("Failed to read from indications", log.Fields{"err": err})
373 break
374 }
375 // Reset backoff if we have a successful receive
376 indicationBackoff.Reset()
377 om.handleIndication(indication)
378
379 }
380}
381
382func (om *OpenOltManager) handleIndication(indication *oop.Indication) {
383 switch indication.Data.(type) {
384 case *oop.Indication_OltInd:
385 log.Info("received olt indication")
386 case *oop.Indication_IntfInd:
387 intfInd := indication.GetIntfInd()
388 log.Infow("Received interface indication ", log.Fields{"InterfaceInd": intfInd})
389 case *oop.Indication_IntfOperInd:
390 intfOperInd := indication.GetIntfOperInd()
391 if intfOperInd.GetType() == "nni" {
392 log.Info("received interface oper indication for nni port")
393 } else if intfOperInd.GetType() == "pon" {
394 log.Info("received interface oper indication for pon port")
395 }
396 /*
397 case *oop.Indication_OnuDiscInd:
398 onuDiscInd := indication.GetOnuDiscInd()
399 log.Infow("Received Onu discovery indication ", log.Fields{"OnuDiscInd": onuDiscInd})
400 */
401 case *oop.Indication_OnuInd:
402 onuInd := indication.GetOnuInd()
403 log.Infow("Received Onu indication ", log.Fields{"OnuInd": onuInd})
404 case *oop.Indication_OmciInd:
405 omciInd := indication.GetOmciInd()
406 log.Debugw("Received Omci indication ", log.Fields{"IntfId": omciInd.IntfId, "OnuId": omciInd.OnuId, "pkt": hex.EncodeToString(omciInd.Pkt)})
407 case *oop.Indication_PktInd:
408 pktInd := indication.GetPktInd()
409 log.Infow("Received pakcet indication ", log.Fields{"PktInd": pktInd})
410 /*
411 case *oop.Indication_PortStats:
412 portStats := indication.GetPortStats()
413 log.Infow("Received port stats", log.Fields{"portStats": portStats})
414 case *oop.Indication_FlowStats:
415 flowStats := indication.GetFlowStats()
416 log.Infow("Received flow stats", log.Fields{"FlowStats": flowStats})
417 */
418 case *oop.Indication_AlarmInd:
419 alarmInd := indication.GetAlarmInd()
420 log.Infow("Received alarm indication ", log.Fields{"AlarmInd": alarmInd})
421 }
422}
423
424func (om *OpenOltManager) populateTechProfilePerPonPort() error {
425 var tpCount int
426 for _, techRange := range om.deviceInfo.Ranges {
427 for _, intfID := range techRange.IntfIds {
428 om.TechProfile[intfID] = &(om.rsrMgr.ResourceMgrs[intfID].TechProfileMgr)
429 tpCount++
430 log.Debugw("Init tech profile done", log.Fields{"intfID": intfID})
431 }
432 }
433 //Make sure we have as many tech_profiles as there are pon ports on the device
434 if tpCount != int(om.deviceInfo.GetPonPorts()) {
435 log.Errorw("Error while populating techprofile",
436 log.Fields{"numofTech": tpCount, "numPonPorts": om.deviceInfo.GetPonPorts()})
437 return errors.New("error while populating techprofile mgrs")
438 }
439 log.Infow("Populated techprofile for ponports successfully",
440 log.Fields{"numofTech": tpCount, "numPonPorts": om.deviceInfo.GetPonPorts()})
441 return nil
442}