LN0739_FM_FR8: relaxing the active alarm and alarm history restrictions
[ric-plt/alarm-go.git] / manager / cmd / manager_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         "github.com/gorilla/mux"
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 alarmManager *AlarmManager
43 var alarmer *alarm.RICAlarm
44 var eventChan chan string
45
46 // Test cases
47 func TestMain(M *testing.M) {
48         os.Setenv("ALARM_IF_RMR", "true")
49         alarmManager = NewAlarmManager("localhost:9093", 500)
50         go alarmManager.Run(false)
51         time.Sleep(time.Duration(2) * time.Second)
52
53         // Wait until RMR is up-and-running
54         for !xapp.Rmr.IsReady() {
55                 time.Sleep(time.Duration(1) * time.Second)
56         }
57
58         alarmer, _ = alarm.InitAlarm("my-pod", "my-app")
59         alarmManager.alarmClient = alarmer
60         time.Sleep(time.Duration(5) * time.Second)
61         eventChan = make(chan string)
62
63         os.Exit(M.Run())
64 }
65
66 func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
67         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
68         defer ts.Close()
69
70         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
71         assert.Nil(t, alarmer.Raise(a), "raise failed")
72
73         VerifyAlarm(t, a, 1)
74 }
75
76 func TestAlarmClearedSucess(t *testing.T) {
77         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
78         defer ts.Close()
79
80         // Raise the alarm
81         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
82         assert.Nil(t, alarmer.Raise(a), "raise failed")
83
84         VerifyAlarm(t, a, 1)
85
86         // Now Clear the alarm and check alarm is removed
87         a = alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
88         assert.Nil(t, alarmer.Clear(a), "clear failed")
89
90         time.Sleep(time.Duration(2) * time.Second)
91         assert.Equal(t, len(alarmManager.activeAlarms), 0)
92 }
93
94 func TestMultipleAlarmsRaisedSucess(t *testing.T) {
95         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
96         defer ts.Close()
97
98         // Raise two alarms
99         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
100         assert.Nil(t, alarmer.Raise(a), "raise failed")
101
102         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
103         assert.Nil(t, alarmer.Raise(b), "raise failed")
104
105         VerifyAlarm(t, a, 2)
106         VerifyAlarm(t, b, 2)
107 }
108
109 func TestMultipleAlarmsClearedSucess(t *testing.T) {
110         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
111         defer ts.Close()
112
113         // Raise two alarms
114         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
115         assert.Nil(t, alarmer.Clear(a), "clear failed")
116
117         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
118         assert.Nil(t, alarmer.Clear(b), "clear failed")
119
120         time.Sleep(time.Duration(2) * time.Second)
121         assert.Equal(t, len(alarmManager.activeAlarms), 0)
122 }
123
124 func TestAlarmsSuppresedSucess(t *testing.T) {
125         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
126         defer ts.Close()
127
128         // Raise two similar/matching alarms ... the second one suppresed
129         a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
130         assert.Nil(t, alarmer.Raise(a), "raise failed")
131         assert.Nil(t, alarmer.Raise(a), "raise failed")
132
133         VerifyAlarm(t, a, 1)
134         assert.Nil(t, alarmer.Clear(a), "clear failed")
135 }
136
137
138 func TestInvalidAlarms(t *testing.T) {
139         a := alarmer.NewAlarm(1111, alarm.SeverityMajor, "Some App data", "eth 0 1")
140         assert.Nil(t, alarmer.Raise(a), "raise failed")
141         time.Sleep(time.Duration(2) * time.Second)
142 }
143
144 func TestAlarmHandlingErrorCases(t *testing.T) {
145         ok, err := alarmManager.HandleAlarms(&xapp.RMRParams{})
146         assert.Equal(t, err.Error(), "unexpected end of JSON input")
147         assert.Nil(t, ok, "raise failed")
148 }
149
150 func TestConsumeUnknownMessage(t *testing.T) {
151         err := alarmManager.Consume(&xapp.RMRParams{})
152         assert.Nil(t, err, "raise failed")
153 }
154
155 func TestStatusCallback(t *testing.T) {
156         assert.Equal(t, true, alarmManager.StatusCB())
157 }
158
159 func TestActiveAlarmMaxThresholds(t *testing.T) {
160         xapp.Logger.Info("TestActiveAlarmMaxThresholds")
161         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
162         alarmManager.maxActiveAlarms = 0
163         alarmManager.maxAlarmHistory = 10
164
165         a := alarmer.NewAlarm(alarm.E2_CONNECTIVITY_LOST_TO_GNODEB, alarm.SeverityCritical, "Some Application data", "eth 0 2")
166         assert.Nil(t, alarmer.Raise(a), "raise failed")
167
168         var alarmConfigParams alarm.AlarmConfigParams
169         req, _ := http.NewRequest("GET", "/ric/v1/alarms/config", nil)
170         req = mux.SetURLVars(req, nil)
171         handleFunc := http.HandlerFunc(alarmManager.GetAlarmConfig)
172         response := executeRequest(req, handleFunc)
173
174         // Check HTTP Status Code
175         checkResponseCode(t, http.StatusOK, response.Code)
176
177         // Decode the json output from handler
178         json.NewDecoder(response.Body).Decode(&alarmConfigParams)
179         if alarmConfigParams.MaxActiveAlarms != 0 || alarmConfigParams.MaxAlarmHistory != 10 {
180                 t.Errorf("Incorrect alarm thresholds")
181         }
182
183         time.Sleep(time.Duration(1) * time.Second)
184         alarmManager.maxActiveAlarms = 5000
185         alarmManager.maxAlarmHistory = 20000
186         VerifyAlarm(t, a, 2)
187         VerifyAlarm(t, a, 2)
188         ts.Close()
189 }
190
191 func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
192         receivedAlert := waitForEvent()
193
194         assert.Equal(t, len(alarmManager.activeAlarms), expectedCount)
195         _, ok := alarmManager.IsMatchFound(a)
196         assert.True(t, ok)
197
198         return receivedAlert
199 }
200
201 func VerifyAlert(t *testing.T, receivedAlert, expectedAlert string) {
202         receivedAlert = strings.Replace(fmt.Sprintf("%v", receivedAlert), "\r\n", " ", -1)
203         //assert.Equal(t, receivedAlert, e)
204 }
205
206 func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
207         l, err := net.Listen("tcp", "localhost:9093")
208         if err != nil {
209                 t.Error("Failed to create listener: " + err.Error())
210         }
211         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
212                 assert.Equal(t, r.Method, method)
213                 assert.Equal(t, r.URL.String(), url)
214
215                 fireEvent(t, r.Body)
216
217                 w.Header().Add("Content-Type", "application/json")
218                 w.WriteHeader(status)
219                 b, _ := json.Marshal(respData)
220                 w.Write(b)
221         }))
222         ts.Listener.Close()
223         ts.Listener = l
224
225         ts.Start()
226
227         return ts
228 }
229
230 func waitForEvent() string {
231         receivedAlert := <-eventChan
232         return receivedAlert
233 }
234
235 func fireEvent(t *testing.T, body io.ReadCloser) {
236         reqBody, err := ioutil.ReadAll(body)
237         assert.Nil(t, err, "ioutil.ReadAll failed")
238         assert.NotNil(t, reqBody, "ioutil.ReadAll failed")
239
240         eventChan <- fmt.Sprintf("%s", reqBody)
241 }
242
243 func executeRequest(req *http.Request, handleR http.HandlerFunc) *httptest.ResponseRecorder {
244         rr := httptest.NewRecorder()
245
246         handleR.ServeHTTP(rr, req)
247
248         return rr
249 }
250
251 func checkResponseCode(t *testing.T, expected, actual int) bool {
252         if expected != actual {
253                 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
254                 return false
255         }
256         return true
257 }
258