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