bd81127bf2baccb21c09635c616e164260290066
[ric-plt/submgr.git] / pkg / control / ut_ctrl_submgr_test.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package control
21
22 import (
23         "fmt"
24         "io/ioutil"
25         "net/http"
26         "strconv"
27         "strings"
28         "testing"
29         "time"
30
31         "gerrit.o-ran-sc.org/r/ric-plt/submgr/pkg/teststub"
32         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models"
33         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
34 )
35
36 //-----------------------------------------------------------------------------
37 //
38 //-----------------------------------------------------------------------------
39 type testingSubmgrControl struct {
40         teststub.RmrControl
41         c *Control
42 }
43
44 type Counter struct {
45         Name  string
46         Value uint64
47 }
48
49 type CountersToBeAdded []Counter
50
51 var countersBeforeMap map[string]Counter
52 var toBeAddedCountersMap map[string]Counter
53
54 func createSubmgrControl(srcId teststub.RmrSrcId, rtgSvc teststub.RmrRtgSvc) *testingSubmgrControl {
55         mainCtrl = &testingSubmgrControl{}
56         mainCtrl.RmrControl.Init("SUBMGRCTL", srcId, rtgSvc)
57         mainCtrl.c = NewControl()
58         xapp.Logger.Debug("Replacing real db with test db")
59         mainCtrl.c.db = CreateMock() // This overrides real database for testing
60         xapp.SetReadyCB(mainCtrl.ReadyCB, nil)
61         go xapp.RunWithParams(mainCtrl.c, false)
62         mainCtrl.WaitCB()
63         mainCtrl.c.ReadyCB(nil)
64         return mainCtrl
65 }
66
67 func (mc *testingSubmgrControl) SimulateRestart(t *testing.T) {
68         mc.TestLog(t, "Simulating submgr restart")
69         mainCtrl.c.registry.subIds = nil
70         // Initialize subIds slice and subscription map
71         mainCtrl.c.registry.Initialize()
72         restDuplicateCtrl.Init()
73         // Read subIds and subscriptions from database
74         subIds, register, err := mainCtrl.c.ReadAllSubscriptionsFromSdl()
75         if err != nil {
76                 mc.TestError(t, "%v", err)
77         } else {
78                 mainCtrl.c.registry.register = nil
79                 mainCtrl.c.registry.subIds = subIds
80                 mainCtrl.c.registry.register = register
81
82                 mc.TestLog(t, "register:")
83                 for subId, subs := range register {
84                         mc.TestLog(t, "  subId=%v", subId)
85                         mc.TestLog(t, "  subs.SubRespRcvd=%v", subs.SubRespRcvd)
86                         mc.TestLog(t, "  subs=%v\n", subs)
87                 }
88
89                 mc.TestLog(t, "mainCtrl.c.registry.register:")
90                 for subId, subs := range mainCtrl.c.registry.register {
91                         mc.TestLog(t, "  subId=%v", subId)
92                         mc.TestLog(t, "  subs.SubRespRcvd=%v", subs.SubRespRcvd)
93                         mc.TestLog(t, "  subs=%v\n", subs)
94                 }
95         }
96         go mainCtrl.c.HandleUncompletedSubscriptions(mainCtrl.c.registry.register)
97 }
98
99 func (mc *testingSubmgrControl) MakeTransactionNil(t *testing.T, subId uint32) {
100
101         mc.TestLog(t, "Makin transaction nil for SubId=%v", subId)
102         subs := mainCtrl.c.registry.GetSubscription(subId)
103         subs.TheTrans = nil
104 }
105
106 func (mc *testingSubmgrControl) SetResetTestFlag(t *testing.T, status bool) {
107         mc.TestLog(t, "ResetTestFlag set to %v", status)
108         mainCtrl.c.ResetTestFlag = status
109 }
110
111 func (mc *testingSubmgrControl) removeExistingSubscriptions(t *testing.T) {
112
113         mc.TestLog(t, "Removing existing subscriptions")
114         mainCtrl.c.RemoveAllSubscriptionsFromSdl()
115         mainCtrl.c.registry.subIds = nil
116         // Initialize subIds slice and subscription map
117         mainCtrl.c.registry.Initialize()
118 }
119
120 func PringSubscriptionQueryResult(resp models.SubscriptionList) {
121         for _, item := range resp {
122                 fmt.Printf("item.SubscriptionID=%v\n", item.SubscriptionID)
123                 fmt.Printf("item.Meid=%v\n", item.Meid)
124                 fmt.Printf("item.ClientEndpoint=%v\n", item.ClientEndpoint)
125         }
126 }
127
128 func (mc *testingSubmgrControl) wait_registry_empty(t *testing.T, secs int) bool {
129         cnt := int(0)
130         i := 1
131         for ; i <= secs*10; i++ {
132                 cnt = len(mc.c.registry.register)
133                 if cnt == 0 {
134                         return true
135                 }
136                 time.Sleep(100 * time.Millisecond)
137         }
138         mc.TestError(t, "(submgr) no registry empty within %d secs: %d", secs, cnt)
139         return false
140 }
141
142 func (mc *testingSubmgrControl) get_registry_next_subid(t *testing.T) uint32 {
143         mc.c.registry.mutex.Lock()
144         defer mc.c.registry.mutex.Unlock()
145         return mc.c.registry.subIds[0]
146 }
147
148 func (mc *testingSubmgrControl) wait_registry_next_subid_change(t *testing.T, origSubId uint32, secs int) (uint32, bool) {
149         i := 1
150         for ; i <= secs*10; i++ {
151                 mc.c.registry.mutex.Lock()
152                 currSubId := mc.c.registry.subIds[0]
153                 mc.c.registry.mutex.Unlock()
154                 if currSubId != origSubId {
155                         return currSubId, true
156                 }
157                 time.Sleep(100 * time.Millisecond)
158         }
159         mc.TestError(t, "(submgr) no subId change within %d secs", secs)
160         return 0, false
161 }
162
163 func (mc *testingSubmgrControl) wait_subs_clean(t *testing.T, e2SubsId uint32, secs int) bool {
164         var subs *Subscription
165         i := 1
166         for ; i <= secs*10; i++ {
167                 subs = mc.c.registry.GetSubscription(e2SubsId)
168                 if subs == nil {
169                         return true
170                 }
171                 time.Sleep(100 * time.Millisecond)
172         }
173         if subs != nil {
174                 mc.TestError(t, "(submgr) no clean within %d secs: %s", secs, subs.String())
175         } else {
176                 mc.TestError(t, "(submgr) no clean within %d secs: subs(N/A)", secs)
177         }
178         return false
179 }
180
181 func (mc *testingSubmgrControl) wait_multi_subs_clean(t *testing.T, e2SubsIds []uint32, secs int) bool {
182
183         purgedSubscriptions := 0
184
185         for i := 1; i <= secs*10; i++ {
186                 purgedSubscriptions = 0
187                 for k := 0; k <= len(e2SubsIds); i++ {
188                         subs := mc.c.registry.GetSubscription(e2SubsIds[k])
189                         if subs == nil {
190                                 mc.TestLog(t, "(submgr) subscriber purged for esSubsId %v", e2SubsIds[k])
191                                 purgedSubscriptions += 1
192                                 if purgedSubscriptions == len(e2SubsIds) {
193                                         return true
194                                 }
195                         }
196                 }
197                 mc.TestLog(t, "(submgr) subscriptions pending purging %v/%v after %d msecs", purgedSubscriptions, len(e2SubsIds), i+500)
198                 time.Sleep(100 * time.Millisecond)
199         }
200
201         mc.TestError(t, "(submgr) no clean within %d secs: subs(N/A) - %v/%v subscriptions found still", secs, purgedSubscriptions, len(e2SubsIds))
202
203         return false
204 }
205
206 func (mc *testingSubmgrControl) wait_subs_trans_clean(t *testing.T, e2SubsId uint32, secs int) bool {
207         var trans TransactionIf
208         i := 1
209         for ; i <= secs*10; i++ {
210                 subs := mc.c.registry.GetSubscription(e2SubsId)
211                 if subs == nil {
212                         return true
213                 }
214                 trans = subs.GetTransaction()
215                 if trans == nil {
216                         return true
217                 }
218                 time.Sleep(100 * time.Millisecond)
219         }
220         if trans != nil {
221                 mc.TestError(t, "(submgr) no clean within %d secs: %s", secs, trans.String())
222         } else {
223                 mc.TestError(t, "(submgr) no clean within %d secs: trans(N/A)", secs)
224         }
225         return false
226 }
227
228 func (mc *testingSubmgrControl) get_subs_entrypoint_cnt(t *testing.T, origSubId uint32) int {
229         subs := mc.c.registry.GetSubscription(origSubId)
230         if subs == nil {
231                 mc.TestError(t, "(submgr) no subs %d exists during entrypoint cnt get", origSubId)
232                 return -1
233         }
234         return subs.EpList.Size()
235 }
236
237 func (mc *testingSubmgrControl) wait_subs_entrypoint_cnt_change(t *testing.T, origSubId uint32, orig int, secs int) (int, bool) {
238
239         subs := mc.c.registry.GetSubscription(origSubId)
240         if subs == nil {
241                 mc.TestError(t, "(submgr) no subs %d exists during entrypoint cnt wait", origSubId)
242                 return -1, true
243         }
244
245         i := 1
246         for ; i <= secs*10; i++ {
247                 curr := subs.EpList.Size()
248                 if curr != orig {
249                         return curr, true
250                 }
251                 time.Sleep(100 * time.Millisecond)
252         }
253         mc.TestError(t, "(submgr) no subs %d entrypoint cnt change within %d secs", origSubId, secs)
254         return 0, false
255 }
256
257 //
258 // Counter check for received message. Note might not be yet handled
259 //
260 func (mc *testingSubmgrControl) get_msgcounter(t *testing.T) uint64 {
261         return mc.c.CntRecvMsg
262 }
263
264 func (mc *testingSubmgrControl) wait_msgcounter_change(t *testing.T, orig uint64, secs int) (uint64, bool) {
265         i := 1
266         for ; i <= secs*10; i++ {
267                 curr := mc.c.CntRecvMsg
268                 if curr != orig {
269                         return curr, true
270                 }
271                 time.Sleep(100 * time.Millisecond)
272         }
273         mc.TestError(t, "(submgr) no msg counter change within %d secs", secs)
274         return 0, false
275 }
276
277 func (mc *testingSubmgrControl) GetMetrics(t *testing.T) (string, error) {
278         req, err := http.NewRequest("GET", "http://localhost:8080/ric/v1/metrics", nil)
279         if err != nil {
280                 return "", fmt.Errorf("Error reading request. %v", err)
281         }
282         client := &http.Client{Timeout: time.Second * 10}
283         resp, err := client.Do(req)
284         if err != nil {
285                 return "", fmt.Errorf("Error reading response. %v", err)
286         }
287         defer resp.Body.Close()
288
289         respBody, err := ioutil.ReadAll(resp.Body)
290         if err != nil {
291                 return "", fmt.Errorf("Error reading body. %v", err)
292         }
293         return string(respBody[:]), nil
294 }
295
296 func (mc *testingSubmgrControl) CounterValuesToBeVeriefied(t *testing.T, countersToBeAdded CountersToBeAdded) {
297
298         if len(toBeAddedCountersMap) == 0 {
299                 toBeAddedCountersMap = make(map[string]Counter)
300         }
301         for _, counter := range countersToBeAdded {
302                 toBeAddedCountersMap[counter.Name] = counter
303         }
304         mc.GetCounterValuesBefore(t)
305 }
306
307 func (mc *testingSubmgrControl) GetCounterValuesBefore(t *testing.T) {
308         countersBeforeMap = make(map[string]Counter)
309         countersBeforeMap = mc.GetCurrentCounterValues(t, toBeAddedCountersMap)
310 }
311
312 func (mc *testingSubmgrControl) VerifyCounterValues(t *testing.T) {
313         currentCountersMap := mc.GetCurrentCounterValues(t, toBeAddedCountersMap)
314         for _, toBeAddedCounter := range toBeAddedCountersMap {
315                 if currentCounter, ok := currentCountersMap[toBeAddedCounter.Name]; ok == true {
316                         if beforeCounter, ok := countersBeforeMap[toBeAddedCounter.Name]; ok == true {
317                                 if currentCounter.Value != beforeCounter.Value+toBeAddedCounter.Value {
318                                         mc.TestError(t, "Error in expected counter value: counterName %v, current value %v, expected value %v",
319                                                 currentCounter.Name, currentCounter.Value, beforeCounter.Value+toBeAddedCounter.Value)
320
321                                         //fmt.Printf("beforeCounter.Value=%v, toBeAddedCounter.Value=%v, \n",beforeCounter.Value, toBeAddedCounter.Value)
322                                 }
323                         } else {
324                                 mc.TestError(t, "Counter %v not in countersBeforeMap", toBeAddedCounter.Name)
325                         }
326                 } else {
327                         mc.TestError(t, "Counter %v not in currentCountersMap", toBeAddedCounter.Name)
328                 }
329         }
330
331         // Make map empty
332         //fmt.Printf("toBeAddedCountersMap=%v\n",toBeAddedCountersMap)
333         toBeAddedCountersMap = make(map[string]Counter)
334 }
335
336 func (mc *testingSubmgrControl) GetCurrentCounterValues(t *testing.T, chekedCountersMap map[string]Counter) map[string]Counter {
337         countersString, err := mc.GetMetrics(t)
338         if err != nil {
339                 mc.TestError(t, "Error GetMetrics() failed %v", err)
340                 return nil
341         }
342
343         retCounterMap := make(map[string]Counter)
344         stringsTable := strings.Split(countersString, "\n")
345         for _, counter := range chekedCountersMap {
346                 for _, counterString := range stringsTable {
347                         if !strings.Contains(counterString, "#") && strings.Contains(counterString, counter.Name) {
348                                 counterString := strings.Split(counterString, " ")
349                                 if strings.Contains(counterString[0], counter.Name) {
350                                         val, err := strconv.ParseUint(counterString[1], 10, 64)
351                                         if err != nil {
352                                                 mc.TestError(t, "Error: strconv.ParseUint failed %v", err)
353                                         }
354                                         counter.Value = val
355                                         //fmt.Printf("counter=%v\n", counter)
356                                         retCounterMap[counter.Name] = counter
357                                 }
358                         }
359                 }
360         }
361
362         if len(retCounterMap) != len(chekedCountersMap) {
363                 mc.TestError(t, "Error: len(retCounterMap) != len(chekedCountersMap)")
364
365         }
366         return retCounterMap
367 }
368
369 func (mc *testingSubmgrControl) sendGetRequest(t *testing.T, addr string, path string) {
370
371         mc.TestLog(t, "GET http://"+addr+"%v", path)
372         req, err := http.NewRequest("GET", "http://"+addr+path, nil)
373         if err != nil {
374                 mc.TestError(t, "Error reading request. %v", err)
375                 return
376         }
377         req.Header.Set("Cache-Control", "no-cache")
378         client := &http.Client{Timeout: time.Second * 2}
379         resp, err := client.Do(req)
380         if err != nil {
381                 mc.TestError(t, "Error reading response. %v", err)
382                 return
383         }
384         defer resp.Body.Close()
385
386         mc.TestLog(t, "Response status: %v", resp.Status)
387         mc.TestLog(t, "Response Headers: %v", resp.Header)
388         if !strings.Contains(resp.Status, "200 OK") {
389                 mc.TestError(t, "Wrong response status")
390                 return
391         }
392
393         respBody, err := ioutil.ReadAll(resp.Body)
394         if err != nil {
395                 mc.TestError(t, "Error reading body. %v", err)
396                 return
397         }
398         mc.TestLog(t, "%s", respBody)
399         return
400 }
401
402 func (mc *testingSubmgrControl) sendPostRequest(t *testing.T, addr string, path string) {
403
404         mc.TestLog(t, "POST http://"+addr+"%v", path)
405         req, err := http.NewRequest("POST", "http://"+addr+path, nil)
406         if err != nil {
407                 mc.TestError(t, "Error reading request. %v", err)
408                 return
409         }
410         client := &http.Client{Timeout: time.Second * 2}
411         resp, err := client.Do(req)
412         if err != nil {
413                 mc.TestError(t, "Error reading response. %v", err)
414                 return
415         }
416         defer resp.Body.Close()
417
418         mc.TestLog(t, "Response status: %v", resp.Status)
419         mc.TestLog(t, "Response Headers: %v", resp.Header)
420         if !strings.Contains(resp.Status, "200 OK") {
421                 mc.TestError(t, "Wrong response status")
422                 return
423         }
424
425         respBody, err := ioutil.ReadAll(resp.Body)
426         if err != nil {
427                 mc.TestError(t, "Error reading body. %v", err)
428                 return
429         }
430         mc.TestLog(t, "%s", respBody)
431         return
432 }