Non-blocking RMR init ...
[ric-plt/alarm-go.git] / adapter / cmd / adapter_test.go
1 /*
2  *  Copyright (c) 2020 AT&T Intellectual Property.
3  *  Copyright (c) 2020 Nokia.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  * This source code is part of the near-RT RIC (RAN Intelligent Controller)
18  * platform project (RICP).
19  */
20
21 package main
22
23 import (
24         "encoding/json"
25         "fmt"
26         "github.com/stretchr/testify/assert"
27         "io"
28         "io/ioutil"
29         "net"
30         "net/http"
31         "net/http/httptest"
32         "os"
33         "strings"
34         "testing"
35         "time"
36
37         "gerrit.o-ran-sc.org/r/ric-plt/alarm-go/alarm"
38         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
39         "github.com/prometheus/alertmanager/api/v2/models"
40 )
41
42 var alarmAdapter *AlarmAdapter
43 var alarmer *alarm.RICAlarm
44 var eventChan chan string
45
46 // Test cases
47 func TestMain(M *testing.M) {
48         alarmAdapter = NewAlarmAdapter("localhost:9093", 500)
49         go alarmAdapter.Run(false)
50         time.Sleep(time.Duration(2) * time.Second)
51
52         // Wait until RMR is up-and-running
53         for !xapp.Rmr.IsReady() {
54                 time.Sleep(time.Duration(1) * time.Second)
55         }
56
57         alarmer, _ = alarm.InitAlarm("my-pod", "my-app")
58         time.Sleep(time.Duration(5) * time.Second)
59         eventChan = make(chan string)
60
61         os.Exit(M.Run())
62 }
63
64 func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
65         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
66         defer ts.Close()
67
68         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
69         assert.Nil(t, alarmer.Raise(a), "raise failed")
70
71         VerifyAlarm(t, a, 1)
72 }
73
74 func TestAlarmClearedSucess(t *testing.T) {
75         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
76         defer ts.Close()
77
78         // Raise the alarm
79         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
80         assert.Nil(t, alarmer.Raise(a), "raise failed")
81
82         VerifyAlarm(t, a, 1)
83
84         // Now Clear the alarm and check alarm is removed
85         a = alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCleared, "Some App data", "eth 0 1")
86         assert.Nil(t, alarmer.Clear(a), "clear failed")
87
88         time.Sleep(time.Duration(2) * time.Second)
89         assert.Equal(t, len(alarmAdapter.activeAlarms), 0)
90 }
91
92 func TestMultipleAlarmsRaisedSucess(t *testing.T) {
93         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
94         defer ts.Close()
95
96         // Raise two alarms
97         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
98         assert.Nil(t, alarmer.Raise(a), "raise failed")
99
100         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
101         assert.Nil(t, alarmer.Raise(b), "raise failed")
102
103         VerifyAlarm(t, a, 2)
104         VerifyAlarm(t, b, 2)
105 }
106
107 func TestMultipleAlarmsClearedSucess(t *testing.T) {
108         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
109         defer ts.Close()
110
111         // Raise two alarms
112         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
113         assert.Nil(t, alarmer.Clear(a), "clear failed")
114
115         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
116         assert.Nil(t, alarmer.Clear(b), "clear failed")
117
118         time.Sleep(time.Duration(2) * time.Second)
119         assert.Equal(t, len(alarmAdapter.activeAlarms), 0)
120 }
121
122 func TestAlarmsSuppresedSucess(t *testing.T) {
123         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
124         defer ts.Close()
125
126         // Raise two similar/matching alarms ... the second one suppresed
127         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
128         assert.Nil(t, alarmer.Raise(a), "raise failed")
129         assert.Nil(t, alarmer.Raise(a), "raise failed")
130
131         VerifyAlarm(t, a, 1)
132 }
133
134 func TestInvalidAlarms(t *testing.T) {
135         a := alarmer.NewAlarm(1111, alarm.SeverityMajor, "Some App data", "eth 0 1")
136         assert.Nil(t, alarmer.Raise(a), "raise failed")
137         time.Sleep(time.Duration(2) * time.Second)
138 }
139
140 func TestAlarmHandlingErrorCases(t *testing.T) {
141         ok, err := alarmAdapter.HandleAlarms(&xapp.RMRParams{})
142         assert.Equal(t, err.Error(), "unexpected end of JSON input")
143         assert.Nil(t, ok, "raise failed")
144 }
145
146 func TestConsumeUnknownMessage(t *testing.T) {
147         err := alarmAdapter.Consume(&xapp.RMRParams{})
148         assert.Nil(t, err, "raise failed")
149 }
150
151 func TestStatusCallback(t *testing.T) {
152         assert.Equal(t, true, alarmAdapter.StatusCB())
153 }
154
155 func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
156         receivedAlert := waitForEvent()
157
158         assert.Equal(t, len(alarmAdapter.activeAlarms), expectedCount)
159         _, ok := alarmAdapter.IsMatchFound(a)
160         assert.True(t, ok)
161
162         return receivedAlert
163 }
164
165 func VerifyAlert(t *testing.T, receivedAlert, expectedAlert string) {
166         receivedAlert = strings.Replace(fmt.Sprintf("%v", receivedAlert), "\r\n", " ", -1)
167         //assert.Equal(t, receivedAlert, e)
168 }
169
170 func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
171         l, err := net.Listen("tcp", "localhost:9093")
172         if err != nil {
173                 t.Error("Failed to create listener: " + err.Error())
174         }
175         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
176                 assert.Equal(t, r.Method, method)
177                 assert.Equal(t, r.URL.String(), url)
178
179                 fireEvent(t, r.Body)
180
181                 w.Header().Add("Content-Type", "application/json")
182                 w.WriteHeader(status)
183                 b, _ := json.Marshal(respData)
184                 w.Write(b)
185         }))
186         ts.Listener.Close()
187         ts.Listener = l
188
189         ts.Start()
190
191         return ts
192 }
193
194 func waitForEvent() string {
195         receivedAlert := <-eventChan
196         return receivedAlert
197 }
198
199 func fireEvent(t *testing.T, body io.ReadCloser) {
200         reqBody, err := ioutil.ReadAll(body)
201         assert.Nil(t, err, "ioutil.ReadAll failed")
202         assert.NotNil(t, reqBody, "ioutil.ReadAll failed")
203
204         eventChan <- fmt.Sprintf("%s", reqBody)
205 }