Fetch RIC active alarms via O1
[ric-plt/o1.git] / agent / pkg / nbi / nbi_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 nbi
21
22 import (
23         "encoding/json"
24         "github.com/stretchr/testify/assert"
25         "net"
26         "net/http"
27         "net/http/httptest"
28         "os"
29         "testing"
30         "time"
31         "github.com/go-openapi/strfmt"
32         "fmt"
33
34         "github.com/prometheus/alertmanager/api/v2/models"
35         apimodel "gerrit.oran-osc.org/r/ric-plt/o1mediator/pkg/appmgrmodel"
36         "gerrit.oran-osc.org/r/ric-plt/o1mediator/pkg/sbi"
37 )
38
39 var XappConfig = `{
40         "o-ran-sc-ric-ueec-config-v1:ric": {
41           "config": {
42                 "name": "ueec",
43                 "namespace": "ricxapp",
44                 "control": {
45                   "active": true,
46                   "interfaceId": {
47                         "globalENBId": {
48                           "plmnId": "1234",
49                           "eNBId": "55"
50                         }
51                   }
52                 }
53           }
54         }
55   }`
56
57 var XappDescriptor = `{
58         "o-ran-sc-ric-xapp-desc-v1:ric": {
59           "xapps": {
60                 "xapp": [
61                   {
62                         "name": "ueec",
63                         "release-name": "ueec-xapp",
64                         "version": "0.0.1",
65                         "namespace": "ricxapp"
66                   }
67                 ]
68           }
69         }
70   }`
71
72 var kpodOutput = `
73 NAME                               READY   STATUS    RESTARTS   AGE
74 ricxapp-ueec-7bfdd587db-2jl9j      1/1     Running   53         29d
75 ricxapp-anr-6748846478-8hmtz       1-1     Running   1          29d
76 ricxapp-dualco-7f76f65c99-5p6c6    0/1     Running   1          29d
77 `
78
79 var n *Nbi
80
81 // Test cases
82 func TestMain(M *testing.M) {
83         n = NewNbi(sbi.NewSBIClient("localhost:8080", "localhost:9093", 5))
84         go n.Start()
85         time.Sleep(time.Duration(1) * time.Second)
86
87         os.Exit(M.Run())
88 }
89
90 func TestModifyConfigmap(t *testing.T) {
91         ts := CreateHTTPServer(t, "PUT", "/ric/v1/config", 8080, http.StatusOK, apimodel.ConfigValidationErrors{})
92         defer ts.Close()
93
94         var f interface{}
95         err := json.Unmarshal([]byte(XappConfig), &f)
96         assert.Equal(t, true, err == nil)
97
98         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", XappConfig, 1)
99         assert.Equal(t, true, err == nil)
100 }
101
102 func TestDeployXApp(t *testing.T) {
103         ts := CreateHTTPServer(t, "POST", "/ric/v1/xapps", 8080, http.StatusCreated, apimodel.Xapp{})
104         defer ts.Close()
105
106         var f interface{}
107         err := json.Unmarshal([]byte(XappDescriptor), &f)
108         assert.Equal(t, true, err == nil)
109
110         err = n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", XappDescriptor, 0)
111         assert.Equal(t, true, err == nil)
112 }
113
114 func TestUnDeployXApp(t *testing.T) {
115         ts := CreateHTTPServer(t, "DELETE", "/ric/v1/xapps/ueec-xapp", 8080, http.StatusNoContent, apimodel.Xapp{})
116         defer ts.Close()
117
118         var f interface{}
119         err := json.Unmarshal([]byte(XappDescriptor), &f)
120         assert.Equal(t, true, err == nil)
121
122         err = n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", XappDescriptor, 2)
123         assert.Equal(t, true, err == nil)
124 }
125
126 func TestGetDeployedXapps(t *testing.T) {
127         ts := CreateHTTPServer(t, "GET", "/ric/v1/xapps", 8080, http.StatusOK, apimodel.AllDeployedXapps{})
128         defer ts.Close()
129
130         err := sbiClient.GetDeployedXapps()
131         assert.Equal(t, true, err == nil)
132 }
133
134 func TestGetAlerts(t *testing.T) {
135         tim := strfmt.DateTime(time.Now())
136         fingerprint := "34c8f717936f063f"
137
138         alerts := []models.GettableAlert{
139                 models.GettableAlert{
140                         Alert: models.Alert{
141                                 Labels: models.LabelSet{
142                                         "status":      "active",
143                                         "alertname":   "E2 CONNECTIVITY LOST TO G-NODEB",
144                                         "severity":    "MAJOR",
145                                         "service":     "RIC:UEEC",
146                                         "system_name": "RIC",
147                                 },
148                         },
149                         Annotations: models.LabelSet{
150                                 "alarm_id": "8006",
151                                 "additional_info": "ethernet",
152                                 "description": "eth12",
153                                 "instructions": "Not defined",
154                                 "summary": "Communication error",
155                         },
156                         EndsAt: &tim,
157                         StartsAt: &tim,
158                         UpdatedAt: &tim,
159                         Fingerprint: &fingerprint,
160                 },
161         }
162
163         url := "/api/v2/alerts?active=true&inhibited=true&silenced=true&unprocessed=true"
164         ts := CreateHTTPServer(t, "GET", url, 9093, http.StatusOK, alerts)
165         defer ts.Close()
166
167         resp, err := sbiClient.GetAlerts()
168
169         assert.Equal(t, true, err == nil)
170         assert.Equal(t, true, resp != nil)
171
172         for _, alert := range resp.Payload {
173                 assert.Equal(t, alert.Annotations, alerts[0].Annotations)
174                 assert.Equal(t, alert.Alert, alerts[0].Alert)
175                 assert.Equal(t, alert.Fingerprint, alerts[0].Fingerprint)
176         }
177 }
178
179 func TestGetAllPodStatus(t *testing.T) {
180         sbi.CommandExec = func(args string) (out string, err error) {
181                 assert.Equal(t, "/usr/local/bin/kubectl get pod -n ricxapp", args)
182                 return kpodOutput, nil
183         }
184
185         expectedPodList := []sbi.PodStatus{
186                 sbi.PodStatus{
187                         Name:   "ueec",
188                         Health: "healthy",
189                         Status: "Running",
190                 },
191                 sbi.PodStatus{
192                         Name:   "anr",
193                         Health: "unavailable",
194                         Status: "Running",
195                 },
196                 sbi.PodStatus{
197                         Name:   "dualco",
198                         Health: "unhealthy",
199                         Status: "Running",
200                 },
201         }
202
203         podList, err := sbiClient.GetAllPodStatus("ricxapp")
204         assert.Equal(t, true, err == nil)
205         assert.Equal(t, podList, expectedPodList)
206 }
207
208 func TestErrorCases(t *testing.T) {
209         // Invalid config
210         err := n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", "", 2)
211         assert.Equal(t, true, err == nil)
212
213         // Invalid module
214         err = n.ManageXapps("", "{}", 2)
215         assert.Equal(t, true, err == nil)
216
217         // Unexpected module
218         err = n.ManageXapps("o-ran-sc-ric-ueec-config-v1", "{}", 2)
219         assert.Equal(t, true, err == nil)
220
221         // Invalid operation
222         err = n.ManageXapps("o-ran-sc-ric-ueec-config-v1", XappDescriptor, 1)
223         assert.Equal(t, true, err == nil)
224
225         // Invalid config
226         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", "", 1)
227         assert.Equal(t, true, err == nil)
228
229         // Invalid operation
230         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", "{}", 0)
231         assert.Equal(t, true, err != nil)
232 }
233
234 func TestConnStatus2Str(t *testing.T) {
235         assert.Equal(t, n.ConnStatus2Str(0), "not-specified")
236         assert.Equal(t, n.ConnStatus2Str(1), "connected")
237         assert.Equal(t, n.ConnStatus2Str(2), "disconnected")
238         assert.Equal(t, n.ConnStatus2Str(3), "setup-failed")
239         assert.Equal(t, n.ConnStatus2Str(4), "connecting")
240         assert.Equal(t, n.ConnStatus2Str(5), "shutting-down")
241         assert.Equal(t, n.ConnStatus2Str(6), "shutdown")
242         assert.Equal(t, n.ConnStatus2Str(1234), "not-specified")
243 }
244
245 func TestE2APProt2Str(t *testing.T) {
246         assert.Equal(t, n.E2APProt2Str(0), "not-specified")
247         assert.Equal(t, n.E2APProt2Str(1), "x2-setup-request")
248         assert.Equal(t, n.E2APProt2Str(2), "endc-x2-setup-request")
249         assert.Equal(t, n.E2APProt2Str(1111), "not-specified")
250 }
251
252 func TestNodeType2Str(t *testing.T) {
253         assert.Equal(t, n.NodeType2Str(0), "not-specified")
254         assert.Equal(t, n.NodeType2Str(1), "enb")
255         assert.Equal(t, n.NodeType2Str(2), "gnb")
256         assert.Equal(t, n.NodeType2Str(1111), "not-specified")
257 }
258
259 func TestTeardown(t *testing.T) {
260         n.Stop()
261 }
262
263 func CreateHTTPServer(t *testing.T, method, url string, port, status int, respData interface{}) *httptest.Server {
264         l, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
265         if err != nil {
266                 t.Error("Failed to create listener: " + err.Error())
267         }
268         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
269                 assert.Equal(t, r.Method, method)
270                 assert.Equal(t, r.URL.String(), url)
271                 w.Header().Add("Content-Type", "application/json")
272                 w.WriteHeader(status)
273                 b, _ := json.Marshal(respData)
274                 w.Write(b)
275         }))
276         ts.Listener.Close()
277         ts.Listener = l
278
279         ts.Start()
280
281         return ts
282 }
283
284 func DescMatcher(result, expected *apimodel.XappDescriptor) bool {
285         if *result.XappName == *expected.XappName && result.HelmVersion == expected.HelmVersion &&
286                 result.Namespace == expected.Namespace && result.ReleaseName == expected.ReleaseName {
287                 return true
288         }
289         return false
290 }
291
292 func ConfigMatcher(result, expected *apimodel.XAppConfig) bool {
293         if *result.Metadata.XappName == *expected.Metadata.XappName &&
294                 *result.Metadata.Namespace == *expected.Metadata.Namespace {
295                 return true
296         }
297         return false
298 }