Fixing bug in O-DU slice assurance app
[nonrtric.git] / test / usecases / odusliceassurance / goversion / stub / simulator.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package main
22
23 import (
24         "encoding/csv"
25         "encoding/json"
26         "flag"
27         "fmt"
28         "math/rand"
29         "net/http"
30         "os"
31         "strconv"
32         "sync"
33         "time"
34
35         "github.com/gorilla/mux"
36         "oransc.org/usecase/oduclosedloop/messages"
37
38         log "github.com/sirupsen/logrus"
39 )
40
41 const THRESHOLD_TPUT int = 700
42
43 type SliceAssuranceInformation struct {
44         duId                 string
45         cellId               string
46         sd                   int
47         sst                  int
48         metricName           string
49         metricValue          int
50         policyRatioId        string
51         policyMaxRatio       int
52         policyMinRatio       int
53         policyDedicatedRatio int
54 }
55
56 var data []*SliceAssuranceInformation
57 var messagesToSend []messages.Measurement
58
59 func loadData() {
60         lines, err := GetCsvFromFile("test-data.csv")
61         if err != nil {
62                 panic(err)
63         }
64         for _, line := range lines {
65                 sai := SliceAssuranceInformation{
66                         duId:                 line[0],
67                         cellId:               line[1],
68                         sd:                   toInt(line[2]),
69                         sst:                  toInt(line[3]),
70                         metricName:           line[4],
71                         metricValue:          toInt(line[5]),
72                         policyRatioId:        line[6],
73                         policyMaxRatio:       toInt(line[7]),
74                         policyMinRatio:       toInt(line[8]),
75                         policyDedicatedRatio: toInt(line[9]),
76                 }
77                 data = append(data, &sai)
78         }
79 }
80
81 func GetCsvFromFile(name string) ([][]string, error) {
82         if csvFile, err := os.Open(name); err == nil {
83                 defer csvFile.Close()
84                 reader := csv.NewReader(csvFile)
85                 reader.FieldsPerRecord = -1
86                 if csvData, err := reader.ReadAll(); err == nil {
87                         return csvData, nil
88                 } else {
89                         return nil, err
90                 }
91         } else {
92                 return nil, err
93         }
94 }
95
96 func toInt(num string) int {
97         res, err := strconv.Atoi(num)
98         if err != nil {
99                 return -1
100         }
101         return res
102 }
103
104 func main() {
105         rand.Seed(time.Now().UnixNano())
106
107         portSdnr := flag.Int("sdnr-port", 3904, "The port this SDNR stub will listen on")
108         portDmaapMR := flag.Int("dmaap-port", 3905, "The port this Dmaap message router will listen on")
109         flag.Parse()
110
111         loadData()
112
113         wg := new(sync.WaitGroup)
114         wg.Add(2)
115
116         go func() {
117
118                 r := mux.NewRouter()
119                 r.HandleFunc("/rests/data/network-topology:network-topology/topology=topology-netconf/node={NODE-ID}/yang-ext:mount/o-ran-sc-du-hello-world:network-function/distributed-unit-functions={O-DU-ID}", getSdnrResponseMessage).Methods(http.MethodGet)
120                 r.HandleFunc("/rests/data/network-topology:network-topology/topology=topology-netconf/node={NODE-ID}/yang-ext:mount/o-ran-sc-du-hello-world:network-function/distributed-unit-functions={O-DU-ID}/radio-resource-management-policy-ratio={POLICY-ID}", updateRRMPolicyDedicatedRatio).Methods(http.MethodPost)
121
122                 fmt.Println("Starting SDNR stub on port: ", *portSdnr)
123
124                 log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", *portSdnr), r))
125                 wg.Done()
126         }()
127
128         go func() {
129
130                 r := mux.NewRouter()
131                 r.HandleFunc("/events/unauthenticated.VES_O_RAN_SC_HELLO_WORLD_PM_STREAMING_OUTPUT/myG/C1", sendDmaapMRMessages).Methods(http.MethodGet)
132
133                 fmt.Println("Starting DmaapMR stub on port: ", *portDmaapMR)
134
135                 log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", *portDmaapMR), r))
136                 wg.Done()
137         }()
138
139         wg.Wait()
140 }
141
142 func getSdnrResponseMessage(w http.ResponseWriter, r *http.Request) {
143         vars := mux.Vars(r)
144         log.Info("Get messages for RRM Policy Ratio information for O-Du ID ", vars["O-DU-ID"])
145
146         message := messages.ORanDuRestConf{
147                 DistributedUnitFunction: messages.DistributedUnitFunction{
148                         Id:             vars["O-DU-ID"],
149                         RRMPolicyRatio: getPolicyRatioMessage(),
150                 },
151         }
152         respondWithJSON(w, http.StatusOK, message)
153 }
154
155 func getPolicyRatioMessage() []messages.RRMPolicyRatio {
156         var policies []messages.RRMPolicyRatio
157
158         for _, entry := range data {
159
160                 message := messages.RRMPolicyRatio{
161                         Id:                      entry.policyRatioId,
162                         AdmState:                "locked",
163                         UserLabel:               entry.policyRatioId,
164                         RRMPolicyMaxRatio:       entry.policyMaxRatio,
165                         RRMPolicyMinRatio:       entry.policyMinRatio,
166                         RRMPolicyDedicatedRatio: entry.policyDedicatedRatio,
167                         ResourceType:            "prb",
168                         RRMPolicyMembers: []messages.RRMPolicyMember{
169                                 {
170                                         MobileCountryCode:   "046",
171                                         MobileNetworkCode:   "651",
172                                         SliceDifferentiator: entry.sd,
173                                         SliceServiceType:    entry.sst,
174                                 },
175                         },
176                 }
177                 policies = append(policies, message)
178         }
179         return policies
180 }
181
182 func updateRRMPolicyDedicatedRatio(w http.ResponseWriter, r *http.Request) {
183
184         var prMessages []messages.RRMPolicyRatio
185         decoder := json.NewDecoder(r.Body)
186
187         if err := decoder.Decode(&prMessages); err != nil {
188                 respondWithError(w, http.StatusBadRequest, "Invalid request payload")
189                 return
190         }
191         defer r.Body.Close()
192
193         log.Infof("Post request to update RRMPolicyDedicatedRatio %+v", prMessages)
194
195         findAndUpdatePolicy(prMessages)
196         respondWithJSON(w, http.StatusOK, map[string]string{"status": "200"})
197 }
198
199 func findAndUpdatePolicy(rRMPolicyRatio []messages.RRMPolicyRatio) {
200         for _, policy := range rRMPolicyRatio {
201                 for _, entry := range data {
202                         if entry.policyRatioId == policy.Id {
203                                 log.Infof("update Policy Dedicated Ratio: value for policy %+v\n Old value: %v New value: %v ", policy, entry.policyDedicatedRatio, policy.RRMPolicyDedicatedRatio)
204                                 entry.policyDedicatedRatio = policy.RRMPolicyDedicatedRatio
205                                 if entry.metricValue > THRESHOLD_TPUT {
206                                         entry.metricValue = rand.Intn(THRESHOLD_TPUT)
207                                 }
208                                 messagesToSend = append(messagesToSend, generateMeasurementEntry(entry))
209                         }
210                 }
211         }
212 }
213
214 func respondWithError(w http.ResponseWriter, code int, message string) {
215         respondWithJSON(w, code, map[string]string{"error": message})
216 }
217
218 func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
219         response, _ := json.Marshal(payload)
220
221         w.Header().Set("Content-Type", "application/json")
222         w.WriteHeader(code)
223         w.Write(response)
224 }
225
226 func sendDmaapMRMessages(w http.ResponseWriter, r *http.Request) {
227         log.Info("Send Dmaap messages")
228         entry := data[rand.Intn(5)]
229
230         maxTput := THRESHOLD_TPUT + 100
231         randomTput := rand.Intn(maxTput-THRESHOLD_TPUT+1) + THRESHOLD_TPUT
232         if randomTput%3 == 0 {
233                 log.Info("Using tput value higher than THRESHOLD_TPUT ", randomTput)
234                 entry.metricValue = randomTput
235         }
236
237         messagesToSend = append(messagesToSend, generateMeasurementEntry(entry))
238
239         message := messages.StdDefinedMessage{
240                 Event: messages.Event{
241                         CommonEventHeader: messages.CommonEventHeader{
242                                 Domain:                  "stndDefined",
243                                 EventId:                 "pm-1_1644252450",
244                                 EventName:               "stndDefined_performanceMeasurementStreaming",
245                                 EventType:               "performanceMeasurementStreaming",
246                                 Sequence:                825,
247                                 Priority:                "Low",
248                                 ReportingEntityId:       "",
249                                 ReportingEntityName:     "O-DU-1122",
250                                 SourceId:                "",
251                                 SourceName:              "O-DU-1122",
252                                 StartEpochMicrosec:      1644252450000000,
253                                 LastEpochMicrosec:       1644252480000000,
254                                 NfNamingCode:            "SIM-O-DU",
255                                 NfVendorName:            "O-RAN-SC SIM Project",
256                                 StndDefinedNamespace:    "o-ran-sc-du-hello-world-pm-streaming-oas3",
257                                 TimeZoneOffset:          "+00:00",
258                                 Version:                 "4.1",
259                                 VesEventListenerVersion: "7.2.1",
260                         },
261                         StndDefinedFields: messages.StndDefinedFields{
262                                 StndDefinedFieldsVersion: "1.0",
263                                 SchemaReference:          "https://gerrit.o-ran-sc.org/r/gitweb?p=scp/oam/modeling.git;a=blob_plain;f=data-model/oas3/experimental/o-ran-sc-du-hello-world-oas3.json;hb=refs/heads/master",
264                                 Data: messages.Data{
265                                         DataId:              "pm-1_1644252450",
266                                         StartTime:           "2022-02-07T16:47:30.0Z",
267                                         AdministrativeState: "unlocked",
268                                         OperationalState:    "enabled",
269                                         UserLabel:           "pm",
270                                         JobTag:              "my-job-tag",
271                                         GranularityPeriod:   30,
272                                         Measurements:        messagesToSend,
273                                 },
274                         },
275                 },
276         }
277
278         fmt.Printf("Send Dmaap messages\n %+v\n", message)
279
280         time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
281         respondWithJSON(w, http.StatusOK, message)
282
283         messagesToSend = nil
284 }
285
286 func generateMeasurementEntry(entry *SliceAssuranceInformation) messages.Measurement {
287
288         measurementTypeInstanceReference := "/o-ran-sc-du-hello-world:network-function/distributed-unit-functions[id='" + entry.duId + "']/cell[id='" + entry.cellId + "']/supported-measurements/performance-measurement-type='(urn:o-ran-sc:yang:o-ran-sc-du-hello-world?revision=2021-11-23)" + entry.metricName + "']/supported-snssai-subcounter-instances[slice-differentiator='" + strconv.Itoa(entry.sd) + "'][slice-service-type='" + strconv.Itoa(entry.sst) + "']"
289         meas := messages.Measurement{
290
291                 MeasurementTypeInstanceReference: measurementTypeInstanceReference,
292                 Value:                            entry.metricValue,
293                 Unit:                             "kbit/s",
294         }
295         return meas
296 }