151619d3ed9cf1242912c4c7a9d4382fdd19627b
[ric-plt/submgr.git] / pkg / control / ut_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         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
25         "io/ioutil"
26         "os"
27         "strings"
28         "sync"
29         "testing"
30         "time"
31 )
32
33 //-----------------------------------------------------------------------------
34 //
35 //-----------------------------------------------------------------------------
36 type testingRmrControl struct {
37         desc     string
38         mutex    sync.Mutex
39         syncChan chan struct{}
40 }
41
42 func (tc *testingRmrControl) Lock() {
43         tc.mutex.Lock()
44 }
45
46 func (tc *testingRmrControl) Unlock() {
47         tc.mutex.Unlock()
48 }
49
50 func (tc *testingRmrControl) GetDesc() string {
51         return tc.desc
52 }
53
54 func (tc *testingRmrControl) ReadyCB(data interface{}) {
55         xapp.Logger.Info("testingRmrControl(%s) ReadyCB", tc.GetDesc())
56         tc.syncChan <- struct{}{}
57         return
58 }
59
60 func (tc *testingRmrControl) WaitCB() {
61         <-tc.syncChan
62 }
63
64 func (tc *testingRmrControl) init(desc string, rtfile string, port string) {
65         os.Setenv("RMR_SEED_RT", rtfile)
66         os.Setenv("RMR_SRC_ID", "localhost:"+port)
67         xapp.Logger.Info("Using rt file %s", os.Getenv("RMR_SEED_RT"))
68         xapp.Logger.Info("Using src id  %s", os.Getenv("RMR_SRC_ID"))
69         tc.desc = strings.ToUpper(desc)
70         tc.syncChan = make(chan struct{})
71 }
72
73 //-----------------------------------------------------------------------------
74 //
75 //-----------------------------------------------------------------------------
76 type testingRmrStubControl struct {
77         testingRmrControl
78         rmrConChan    chan *RMRParams
79         rmrClientTest *xapp.RMRClient
80         active        bool
81         msgCnt        uint64
82 }
83
84 func (tc *testingRmrStubControl) GetMsgCnt() uint64 {
85         return tc.msgCnt
86 }
87
88 func (tc *testingRmrStubControl) IncMsgCnt() {
89         tc.msgCnt++
90 }
91
92 func (tc *testingRmrStubControl) DecMsgCnt() {
93         if tc.msgCnt > 0 {
94                 tc.msgCnt--
95         }
96 }
97
98 func (tc *testingRmrStubControl) TestMsgCnt(t *testing.T) {
99         if tc.GetMsgCnt() > 0 {
100                 testError(t, "(%s) message count expected 0 but is %d", tc.GetDesc(), tc.GetMsgCnt())
101         }
102 }
103
104 func (tc *testingRmrStubControl) RmrSend(params *RMRParams) (err error) {
105         //
106         //NOTE: Do this way until xapp-frame sending is improved
107         //
108         xapp.Logger.Info("(%s) RmrSend %s", tc.GetDesc(), params.String())
109         status := false
110         i := 1
111         for ; i <= 10 && status == false; i++ {
112                 status = tc.rmrClientTest.SendMsg(params.RMRParams)
113                 if status == false {
114                         xapp.Logger.Info("(%s) RmrSend failed. Retry count %v, %s", tc.GetDesc(), i, params.String())
115                         time.Sleep(500 * time.Millisecond)
116                 }
117         }
118         if status == false {
119                 err = fmt.Errorf("(%s) RmrSend failed. Retry count %v, %s", tc.GetDesc(), i, params.String())
120                 xapp.Rmr.Free(params.Mbuf)
121         }
122         return
123 }
124
125 func (tc *testingRmrStubControl) init(desc string, rtfile string, port string, stat string, consumer xapp.MessageConsumer) {
126         tc.active = false
127         tc.testingRmrControl.init(desc, rtfile, port)
128         tc.rmrConChan = make(chan *RMRParams)
129         tc.rmrClientTest = xapp.NewRMRClientWithParams("tcp:"+port, 4096, 1, stat)
130         tc.rmrClientTest.SetReadyCB(tc.ReadyCB, nil)
131         go tc.rmrClientTest.Start(consumer)
132         tc.WaitCB()
133         allRmrStubs = append(allRmrStubs, tc)
134 }
135
136 var allRmrStubs []*testingRmrStubControl
137
138 //-----------------------------------------------------------------------------
139 //
140 //-----------------------------------------------------------------------------
141
142 func testError(t *testing.T, pattern string, args ...interface{}) {
143         xapp.Logger.Error(fmt.Sprintf(pattern, args...))
144         t.Errorf(fmt.Sprintf(pattern, args...))
145 }
146
147 func testLog(t *testing.T, pattern string, args ...interface{}) {
148         xapp.Logger.Info(fmt.Sprintf(pattern, args...))
149         t.Logf(fmt.Sprintf(pattern, args...))
150 }
151
152 func testCreateTmpFile(str string) (string, error) {
153         file, err := ioutil.TempFile("/tmp", "*.rt")
154         if err != nil {
155                 return "", err
156         }
157         _, err = file.WriteString(str)
158         if err != nil {
159                 file.Close()
160                 return "", err
161         }
162         return file.Name(), nil
163 }
164
165 //-----------------------------------------------------------------------------
166 //
167 //-----------------------------------------------------------------------------
168
169 var xappConn1 *testingXappStub
170 var xappConn2 *testingXappStub
171 var e2termConn *testingE2termStub
172 var rtmgrHttp *testingHttpRtmgrStub
173 var mainCtrl *testingSubmgrControl
174
175 func ut_test_init() {
176         xapp.Logger.Info("ut_test_init")
177
178         //---------------------------------
179         //
180         //---------------------------------
181         rtmgrHttp = createNewHttpRtmgrStub("RTMGRSTUB", "8989")
182         go rtmgrHttp.run()
183
184         //---------------------------------
185         //
186         //---------------------------------
187
188         //
189         //Cfg creation won't work like this as xapp-frame reads it during init.
190         //
191         /*
192             cfgstr:=`{
193               "local": {
194                   "host": ":8080"
195               },
196               "logger": {
197                   "level": 4
198               },
199               "rmr": {
200                  "protPort": "tcp:14560",
201                  "maxSize": 4096,
202                  "numWorkers": 1,
203                  "txMessages": ["RIC_SUB_REQ", "RIC_SUB_DEL_REQ"],
204                  "rxMessages": ["RIC_SUB_RESP", "RIC_SUB_FAILURE", "RIC_SUB_DEL_RESP", "RIC_SUB_DEL_FAILURE", "RIC_INDICATION"]
205               },
206               "db": {
207                   "host": "localhost",
208                   "port": 6379,
209                   "namespaces": ["sdl", "rnib"]
210               },
211                  "rtmgr" : {
212                    "HostAddr" : "localhost",
213                    "port" : "8989",
214                    "baseUrl" : "/"
215                  }
216            `
217
218            cfgfilename,_ := testCreateTmpFile(cfgstr)
219            defer os.Remove(cfgfilename)
220            os.Setenv("CFG_FILE", cfgfilename)
221         */
222         xapp.Logger.Info("Using cfg file %s", os.Getenv("CFG_FILE"))
223
224         //---------------------------------
225         // Static routetable for rmr
226         //
227         // NOTE: Routing table is configured so, that responses
228         //       are duplicated to xapp1 and xapp2 instances.
229         //       If XID is not matching xapp stub will just
230         //       drop message. (Messages 12011, 12012, 12021, 12022)
231         //
232         // NOTE2: 55555 message type is for stub rmr connectivity probing
233         //
234         // NOTE3: Ports per entity:
235         //
236         // Port    Entity
237         // -------------------
238         // 14560   submgr
239         // 15560   e2term stub
240         // 13560   xapp1 stub
241         // 13660   xapp2 stub
242         //
243         //---------------------------------
244
245         allrt := `newrt|start
246 mse|12010|-1|localhost:14560
247 mse|12010,localhost:14560|-1|localhost:15560
248 mse|12011,localhost:15560|-1|localhost:14560
249 mse|12012,localhost:15560|-1|localhost:14560
250 mse|12011,localhost:14560|-1|localhost:13660;localhost:13560
251 mse|12012,localhost:14560|-1|localhost:13660;localhost:13560
252 mse|12020|-1|localhost:14560
253 mse|12020,localhost:14560|-1|localhost:15560
254 mse|12021,localhost:15560|-1|localhost:14560
255 mse|12022,localhost:15560|-1|localhost:14560
256 mse|12021,localhost:14560|-1|localhost:13660;localhost:13560
257 mse|12022,localhost:14560|-1|localhost:13660;localhost:13560
258 mse|55555|-1|localhost:13660;localhost:13560,localhost:15560
259 newrt|end
260 `
261
262         //---------------------------------
263         //
264         //---------------------------------
265         xapp.Logger.Info("### submgr ctrl run ###")
266         subsrt := allrt
267         subrtfilename, _ := testCreateTmpFile(subsrt)
268         defer os.Remove(subrtfilename)
269         mainCtrl = createSubmgrControl("main", subrtfilename, "14560")
270
271         //---------------------------------
272         //
273         //---------------------------------
274         xapp.Logger.Info("### xapp1 stub run ###")
275         xapprt1 := allrt
276         xapprtfilename1, _ := testCreateTmpFile(xapprt1)
277         defer os.Remove(xapprtfilename1)
278         xappConn1 = createNewXappStub("xappstub1", xapprtfilename1, "13560", "RMRXAPP1STUB")
279
280         //---------------------------------
281         //
282         //---------------------------------
283         xapp.Logger.Info("### xapp2 stub run ###")
284         xapprt2 := allrt
285         xapprtfilename2, _ := testCreateTmpFile(xapprt2)
286         defer os.Remove(xapprtfilename2)
287         xappConn2 = createNewXappStub("xappstub2", xapprtfilename2, "13660", "RMRXAPP2STUB")
288
289         //---------------------------------
290         //
291         //---------------------------------
292         xapp.Logger.Info("### e2term stub run ###")
293         e2termrt := allrt
294         e2termrtfilename, _ := testCreateTmpFile(e2termrt)
295         defer os.Remove(e2termrtfilename)
296         e2termConn = createNewE2termStub("e2termstub", e2termrtfilename, "15560", "RMRE2TERMSTUB")
297
298         //---------------------------------
299         // Testing message sending
300         //---------------------------------
301         var dummyBuf []byte = make([]byte, 100)
302
303         params := &RMRParams{&xapp.RMRParams{}}
304         params.Mtype = 55555
305         params.SubId = -1
306         params.Payload = dummyBuf
307         params.PayloadLen = 100
308         params.Meid = &xapp.RMRMeid{RanName: "NONEXISTINGRAN"}
309         params.Xid = "THISISTESTFORSTUBS"
310         params.Mbuf = nil
311
312         status := false
313         i := 1
314         for ; i <= 10 && status == false; i++ {
315                 xapp.Rmr.Send(params.RMRParams, false)
316
317                 status = true
318                 for _, val := range allRmrStubs {
319                         if val.active == false {
320                                 status = false
321                                 break
322                         }
323                 }
324                 if status == true {
325                         break
326                 }
327                 xapp.Logger.Info("Sleep 0.5 secs and try routes again")
328                 time.Sleep(500 * time.Millisecond)
329         }
330
331         if status == false {
332                 xapp.Logger.Error("Could not initialize routes")
333                 os.Exit(1)
334         }
335 }
336
337 //-----------------------------------------------------------------------------
338 //
339 //-----------------------------------------------------------------------------
340 func TestMain(m *testing.M) {
341         xapp.Logger.Info("TestMain start")
342         ut_test_init()
343         code := m.Run()
344         os.Exit(code)
345 }