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