blob: b75cae549a05374227e7909f96392a32b698a341 [file] [log] [blame]
Mohamed Abukar4e7e7122020-03-04 10:01:45 +02001/*
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
21package main
22
23import (
vipin4cedd502020-09-25 05:58:31 +000024 "bytes"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020025 "encoding/json"
26 "fmt"
vipin4cedd502020-09-25 05:58:31 +000027 "gerrit.o-ran-sc.org/r/ric-plt/alarm-go/alarm"
28 "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
29 "github.com/gorilla/mux"
30 "github.com/prometheus/alertmanager/api/v2/models"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020031 "github.com/stretchr/testify/assert"
32 "io"
33 "io/ioutil"
34 "net"
35 "net/http"
36 "net/http/httptest"
37 "os"
Anssi Mannila00894a42020-10-19 11:36:26 +030038 "os/exec"
vipin4cedd502020-09-25 05:58:31 +000039 "strconv"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020040 "strings"
41 "testing"
42 "time"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020043)
44
Abukar Mohamed121e8b62020-09-18 11:41:33 +000045var alarmManager *AlarmManager
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020046var alarmer *alarm.RICAlarm
47var eventChan chan string
48
49// Test cases
50func TestMain(M *testing.M) {
Mohamed Abukar105030f2020-10-22 18:08:34 +030051 alarmManager = NewAlarmManager("localhost:9093", 500, false)
vipin6f73fa32020-10-06 06:51:53 +000052 alarmManager.alertInterval = 20000
Abukar Mohamed121e8b62020-09-18 11:41:33 +000053 go alarmManager.Run(false)
vipin14323a92020-09-25 10:03:43 +000054 time.Sleep(time.Duration(10) * time.Second)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020055
56 // Wait until RMR is up-and-running
57 for !xapp.Rmr.IsReady() {
58 time.Sleep(time.Duration(1) * time.Second)
59 }
60
61 alarmer, _ = alarm.InitAlarm("my-pod", "my-app")
vipin541eb502020-09-22 12:04:59 +000062 alarmManager.alarmClient = alarmer
Mohamed Abukareac44512020-03-31 09:46:04 +030063 time.Sleep(time.Duration(5) * time.Second)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020064 eventChan = make(chan string)
65
66 os.Exit(M.Run())
67}
68
vipin14323a92020-09-25 10:03:43 +000069func TestGetPreDefinedAlarmDefinitions(t *testing.T) {
70 xapp.Logger.Info("TestGetPreDefinedAlarmDefinitions")
71 var alarmDefinition alarm.AlarmDefinition
72 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
73 vars := map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
74 req = mux.SetURLVars(req, vars)
75 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
76 response := executeRequest(req, handleFunc)
77 checkResponseCode(t, http.StatusOK, response.Code)
78 json.NewDecoder(response.Body).Decode(&alarmDefinition)
79 xapp.Logger.Info("alarm definition = %v", alarmDefinition)
80 if alarmDefinition.AlarmId != alarm.RIC_RT_DISTRIBUTION_FAILED || alarmDefinition.AlarmText != "RIC ROUTING TABLE DISTRIBUTION FAILED" {
81 t.Errorf("Incorrect alarm definition")
82 }
83}
84
vipin54a3a4f2020-09-23 12:19:58 +000085func TestSetAlarmDefinitions(t *testing.T) {
86 xapp.Logger.Info("TestSetAlarmDefinitions")
87 var alarm8004Definition alarm.AlarmDefinition
88 alarm8004Definition.AlarmId = alarm.RIC_RT_DISTRIBUTION_FAILED
89 alarm8004Definition.AlarmText = "RIC ROUTING TABLE DISTRIBUTION FAILED"
90 alarm8004Definition.EventType = "Processing error"
91 alarm8004Definition.OperationInstructions = "Not defined"
Anssi Mannila18fd03c2020-10-29 10:01:00 +020092 alarm8004Definition.RaiseDelay = 0
93 alarm8004Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +000094
95 var alarm8005Definition alarm.AlarmDefinition
96 alarm8005Definition.AlarmId = alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS
97 alarm8005Definition.AlarmText = "TCP CONNECTIVITY LOST TO DBAAS"
98 alarm8005Definition.EventType = "Communication error"
99 alarm8005Definition.OperationInstructions = "Not defined"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200100 alarm8005Definition.RaiseDelay = 0
101 alarm8005Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000102
103 var alarm8006Definition alarm.AlarmDefinition
104 alarm8006Definition.AlarmId = alarm.E2_CONNECTIVITY_LOST_TO_GNODEB
105 alarm8006Definition.AlarmText = "E2 CONNECTIVITY LOST TO G-NODEB"
106 alarm8006Definition.EventType = "Communication error"
107 alarm8006Definition.OperationInstructions = "Not defined"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200108 alarm8006Definition.RaiseDelay = 0
109 alarm8006Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000110
111 var alarm8007Definition alarm.AlarmDefinition
112 alarm8007Definition.AlarmId = alarm.E2_CONNECTIVITY_LOST_TO_ENODEB
113 alarm8007Definition.AlarmText = "E2 CONNECTIVITY LOST TO E-NODEB"
114 alarm8007Definition.EventType = "Communication error"
115 alarm8007Definition.OperationInstructions = "Not defined"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200116 alarm8007Definition.RaiseDelay = 0
117 alarm8007Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000118
119 var alarm8008Definition alarm.AlarmDefinition
120 alarm8008Definition.AlarmId = alarm.ACTIVE_ALARM_EXCEED_MAX_THRESHOLD
121 alarm8008Definition.AlarmText = "ACTIVE ALARM EXCEED MAX THRESHOLD"
122 alarm8008Definition.EventType = "storage warning"
vipin14323a92020-09-25 10:03:43 +0000123 alarm8008Definition.OperationInstructions = "Clear alarms or raise threshold"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200124 alarm8008Definition.RaiseDelay = 0
125 alarm8008Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000126
127 var alarm8009Definition alarm.AlarmDefinition
128 alarm8009Definition.AlarmId = alarm.ALARM_HISTORY_EXCEED_MAX_THRESHOLD
129 alarm8009Definition.AlarmText = "ALARM HISTORY EXCEED MAX THRESHOLD"
130 alarm8009Definition.EventType = "storage warning"
vipin14323a92020-09-25 10:03:43 +0000131 alarm8009Definition.OperationInstructions = "Clear alarms or raise threshold"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200132 alarm8009Definition.RaiseDelay = 0
133 alarm8009Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000134
135 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm8004Definition, &alarm8005Definition, &alarm8006Definition, &alarm8007Definition, &alarm8008Definition, &alarm8009Definition}}
136 pbodyEn, _ := json.Marshal(pbodyParams)
137 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
138 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
139 response := executeRequest(req, handleFunc)
140 status := checkResponseCode(t, http.StatusOK, response.Code)
141 xapp.Logger.Info("status = %v", status)
142
143}
144
145func TestGetAlarmDefinitions(t *testing.T) {
146 xapp.Logger.Info("TestGetAlarmDefinitions")
147 var alarmDefinition alarm.AlarmDefinition
148 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
149 vars := map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
150 req = mux.SetURLVars(req, vars)
151 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
152 response := executeRequest(req, handleFunc)
153 checkResponseCode(t, http.StatusOK, response.Code)
154 json.NewDecoder(response.Body).Decode(&alarmDefinition)
155 xapp.Logger.Info("alarm definition = %v", alarmDefinition)
156 if alarmDefinition.AlarmId != alarm.RIC_RT_DISTRIBUTION_FAILED || alarmDefinition.AlarmText != "RIC ROUTING TABLE DISTRIBUTION FAILED" {
157 t.Errorf("Incorrect alarm definition")
158 }
159}
160
161func TestDeleteAlarmDefinitions(t *testing.T) {
162 xapp.Logger.Info("TestDeleteAlarmDefinitions")
163 //Get all
164 var ricAlarmDefinitions RicAlarmDefinitions
165 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
166 req = mux.SetURLVars(req, nil)
167 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
168 response := executeRequest(req, handleFunc)
169 checkResponseCode(t, http.StatusOK, response.Code)
170 json.NewDecoder(response.Body).Decode(&ricAlarmDefinitions)
171 for _, alarmDefinition := range ricAlarmDefinitions.AlarmDefinitions {
172 xapp.Logger.Info("alarm definition = %v", *alarmDefinition)
173 }
174
175 //Delete 8004
176 req, _ = http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
vipin4cedd502020-09-25 05:58:31 +0000177 vars := map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
178 req = mux.SetURLVars(req, vars)
179 handleFunc = http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
180 response = executeRequest(req, handleFunc)
181 checkResponseCode(t, http.StatusOK, response.Code)
vipin54a3a4f2020-09-23 12:19:58 +0000182
183 //Get 8004 fail
184 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
185 vars = map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
186 req = mux.SetURLVars(req, vars)
187 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
188 response = executeRequest(req, handleFunc)
189 checkResponseCode(t, http.StatusBadRequest, response.Code)
190
191 //Set 8004 success
192 var alarm8004Definition alarm.AlarmDefinition
193 alarm8004Definition.AlarmId = alarm.RIC_RT_DISTRIBUTION_FAILED
194 alarm8004Definition.AlarmText = "RIC ROUTING TABLE DISTRIBUTION FAILED"
195 alarm8004Definition.EventType = "Processing error"
196 alarm8004Definition.OperationInstructions = "Not defined"
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200197 alarm8004Definition.RaiseDelay = 0
198 alarm8004Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000199 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm8004Definition}}
200 pbodyEn, _ := json.Marshal(pbodyParams)
201 req, _ = http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
202 handleFunc = http.HandlerFunc(alarmManager.SetAlarmDefinition)
203 response = executeRequest(req, handleFunc)
204 checkResponseCode(t, http.StatusOK, response.Code)
205
206 //Get 8004 success
207 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
208 vars = map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
209 req = mux.SetURLVars(req, vars)
210 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
211 response = executeRequest(req, handleFunc)
212 checkResponseCode(t, http.StatusOK, response.Code)
213}
214
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200215func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000216 xapp.Logger.Info("TestNewAlarmStoredAndPostedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200217 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
218 defer ts.Close()
219
Mohamed Abukar540ceee2020-09-09 08:07:40 +0300220 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200221 assert.Nil(t, alarmer.Raise(a), "raise failed")
222
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200223 VerifyAlarm(t, a, 1)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200224}
225
226func TestAlarmClearedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000227 xapp.Logger.Info("TestAlarmClearedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200228 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
229 defer ts.Close()
230
231 // Raise the alarm
Mohamed Abukar540ceee2020-09-09 08:07:40 +0300232 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200233 assert.Nil(t, alarmer.Raise(a), "raise failed")
234
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200235 VerifyAlarm(t, a, 1)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200236
237 // Now Clear the alarm and check alarm is removed
Mohamed Abukar540ceee2020-09-09 08:07:40 +0300238 a = alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200239 assert.Nil(t, alarmer.Clear(a), "clear failed")
240
241 time.Sleep(time.Duration(2) * time.Second)
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000242 assert.Equal(t, len(alarmManager.activeAlarms), 0)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200243}
244
245func TestMultipleAlarmsRaisedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000246 xapp.Logger.Info("TestMultipleAlarmsRaisedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200247 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
248 defer ts.Close()
249
250 // Raise two alarms
Mohamed Abukaraf0c5702020-03-11 10:29:40 +0200251 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200252 assert.Nil(t, alarmer.Raise(a), "raise failed")
253
Mohamed Abukaraf0c5702020-03-11 10:29:40 +0200254 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200255 assert.Nil(t, alarmer.Raise(b), "raise failed")
256
vipin6f73fa32020-10-06 06:51:53 +0000257 time.Sleep(time.Duration(2) * time.Second)
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200258 VerifyAlarm(t, a, 2)
259 VerifyAlarm(t, b, 2)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200260}
261
262func TestMultipleAlarmsClearedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000263 xapp.Logger.Info("TestMultipleAlarmsClearedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200264 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
265 defer ts.Close()
266
267 // Raise two alarms
Mohamed Abukaraf0c5702020-03-11 10:29:40 +0200268 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200269 assert.Nil(t, alarmer.Clear(a), "clear failed")
270
Mohamed Abukaraf0c5702020-03-11 10:29:40 +0200271 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200272 assert.Nil(t, alarmer.Clear(b), "clear failed")
273
274 time.Sleep(time.Duration(2) * time.Second)
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000275 assert.Equal(t, len(alarmManager.activeAlarms), 0)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200276}
277
278func TestAlarmsSuppresedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000279 xapp.Logger.Info("TestAlarmsSuppresedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200280 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
281 defer ts.Close()
282
283 // Raise two similar/matching alarms ... the second one suppresed
Mohamed Abukaraf0c5702020-03-11 10:29:40 +0200284 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200285 assert.Nil(t, alarmer.Raise(a), "raise failed")
286 assert.Nil(t, alarmer.Raise(a), "raise failed")
287
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200288 VerifyAlarm(t, a, 1)
vipin541eb502020-09-22 12:04:59 +0000289 assert.Nil(t, alarmer.Clear(a), "clear failed")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200290}
291
292func TestInvalidAlarms(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000293 xapp.Logger.Info("TestInvalidAlarms")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200294 a := alarmer.NewAlarm(1111, alarm.SeverityMajor, "Some App data", "eth 0 1")
295 assert.Nil(t, alarmer.Raise(a), "raise failed")
296 time.Sleep(time.Duration(2) * time.Second)
297}
298
299func TestAlarmHandlingErrorCases(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000300 xapp.Logger.Info("TestAlarmHandlingErrorCases")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000301 ok, err := alarmManager.HandleAlarms(&xapp.RMRParams{})
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200302 assert.Equal(t, err.Error(), "unexpected end of JSON input")
303 assert.Nil(t, ok, "raise failed")
304}
305
306func TestConsumeUnknownMessage(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000307 xapp.Logger.Info("TestConsumeUnknownMessage")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000308 err := alarmManager.Consume(&xapp.RMRParams{})
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200309 assert.Nil(t, err, "raise failed")
310}
311
312func TestStatusCallback(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000313 xapp.Logger.Info("TestStatusCallback")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000314 assert.Equal(t, true, alarmManager.StatusCB())
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200315}
316
vipin541eb502020-09-22 12:04:59 +0000317func TestActiveAlarmMaxThresholds(t *testing.T) {
318 xapp.Logger.Info("TestActiveAlarmMaxThresholds")
319 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
320 alarmManager.maxActiveAlarms = 0
321 alarmManager.maxAlarmHistory = 10
322
323 a := alarmer.NewAlarm(alarm.E2_CONNECTIVITY_LOST_TO_GNODEB, alarm.SeverityCritical, "Some Application data", "eth 0 2")
324 assert.Nil(t, alarmer.Raise(a), "raise failed")
325
326 var alarmConfigParams alarm.AlarmConfigParams
327 req, _ := http.NewRequest("GET", "/ric/v1/alarms/config", nil)
328 req = mux.SetURLVars(req, nil)
329 handleFunc := http.HandlerFunc(alarmManager.GetAlarmConfig)
330 response := executeRequest(req, handleFunc)
331
332 // Check HTTP Status Code
333 checkResponseCode(t, http.StatusOK, response.Code)
334
335 // Decode the json output from handler
336 json.NewDecoder(response.Body).Decode(&alarmConfigParams)
337 if alarmConfigParams.MaxActiveAlarms != 0 || alarmConfigParams.MaxAlarmHistory != 10 {
338 t.Errorf("Incorrect alarm thresholds")
339 }
340
341 time.Sleep(time.Duration(1) * time.Second)
342 alarmManager.maxActiveAlarms = 5000
343 alarmManager.maxAlarmHistory = 20000
344 VerifyAlarm(t, a, 2)
345 VerifyAlarm(t, a, 2)
346 ts.Close()
347}
348
Anssi Mannila00894a42020-10-19 11:36:26 +0300349func TestGetPrometheusAlerts(t *testing.T) {
350 time.Sleep(1 * time.Second)
351 xapp.Logger.Info("TestGetPrometheusAlerts")
352 ts := CreatePromAlertSimulator2(t, "GET", "/alerts?active=true&inhibited=true&silenced=true&unprocessed=true")
353
354 commandReady := make(chan bool, 1)
355 command := "cli/alarm-cli"
Mohamed Abukarf5a8e712020-10-19 16:58:17 +0300356 args := []string{"gapam", "--active", "true", "--inhibited", "true", "--silenced", "--unprocessed", "true", "true", "--host", "localhost", "--port", "9093", "flushall"}
Anssi Mannila00894a42020-10-19 11:36:26 +0300357 ExecCLICommand(commandReady, command, args...)
358 <-commandReady
359
360 ts.Close()
361}
362
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200363func TestDelayedAlarmRaiseAndClear(t *testing.T) {
364 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear")
365
366 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
367 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
368
369 // Add new alarm definition
370 var alarm9999Definition alarm.AlarmDefinition
371 alarm9999Definition.AlarmId = 9999
372 alarm9999Definition.AlarmText = "DELAYED TEST ALARM"
373 alarm9999Definition.EventType = "Test type"
374 alarm9999Definition.OperationInstructions = "Not defined"
375 alarm9999Definition.RaiseDelay = 1
376 alarm9999Definition.ClearDelay = 1
377 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm9999Definition}}
378 pbodyEn, _ := json.Marshal(pbodyParams)
379 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
380 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
381 response := executeRequest(req, handleFunc)
382 checkResponseCode(t, http.StatusOK, response.Code)
383
384 // Verify 9999 alarm definition
385 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
386 vars := map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
387 req = mux.SetURLVars(req, vars)
388 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
389 response = executeRequest(req, handleFunc)
390 checkResponseCode(t, http.StatusOK, response.Code)
391
392 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
393 defer ts.Close()
394
395 // Raise alarm. Posting alert and updating alarm history should be delayed
396 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
397 assert.Nil(t, alarmer.Raise(a), "raise failed")
398 VerifyAlarm(t, a, activeAlarmsBeforeTest + 1)
399
400 // Clear the alarm and check the alarm is removed. Posting alert clear and updating alarm history should be delayed
401 assert.Nil(t, alarmer.Clear(a), "clear failed")
402
403 time.Sleep(time.Duration(2) * time.Second)
404 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
405 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest + 2)
406}
407
408func TestDelayedAlarmRaiseAndClear2(t *testing.T) {
409 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear2")
410
411 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
412 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
413
414 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
415 defer ts.Close()
416
417 // Raise two alarms. The first should be delayed
418 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
419 assert.Nil(t, alarmer.Raise(a), "raise failed")
420 VerifyAlarm(t, a, activeAlarmsBeforeTest + 1)
421
422 b := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
423 assert.Nil(t, alarmer.Raise(b), "raise failed")
424 VerifyAlarm(t, b, activeAlarmsBeforeTest + 2)
425
426 // Clear two alarms. The first should be delayed. Check the alarms are removed
427 assert.Nil(t, alarmer.Clear(a), "clear failed")
428 assert.Nil(t, alarmer.Clear(b), "clear failed")
429
430 time.Sleep(time.Duration(2) * time.Second)
431 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
432 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest + 4)
433}
434
435func TestDelayedAlarmRaiseAndClear3(t *testing.T) {
436 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear3")
437
438 // Delete exisitng 9999 alarm definition
439 req, _ := http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
440 vars := map[string]string{"alarmId": strconv.FormatUint(9999, 10)}
441 req = mux.SetURLVars(req, vars)
442 handleFunc := http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
443 response := executeRequest(req, handleFunc)
444 checkResponseCode(t, http.StatusOK, response.Code)
445
446 // Add updated 9999 alarm definition
447 var alarm9999Definition alarm.AlarmDefinition
448 alarm9999Definition.AlarmId = 9999
449 alarm9999Definition.AlarmText = "DELAYED TEST ALARM"
450 alarm9999Definition.EventType = "Test type"
451 alarm9999Definition.OperationInstructions = "Not defined"
452 alarm9999Definition.RaiseDelay = 1
453 alarm9999Definition.ClearDelay = 0
454 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm9999Definition}}
455 pbodyEn, _ := json.Marshal(pbodyParams)
456 req, _ = http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
457 handleFunc = http.HandlerFunc(alarmManager.SetAlarmDefinition)
458 response = executeRequest(req, handleFunc)
459 checkResponseCode(t, http.StatusOK, response.Code)
460
461 // Verify 9999 alarm definition
462 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
463 vars = map[string]string{"alarmId": strconv.FormatUint(8004, 10)}
464 req = mux.SetURLVars(req, vars)
465 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
466 response = executeRequest(req, handleFunc)
467 checkResponseCode(t, http.StatusOK, response.Code)
468
469 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
470 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
471
472 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
473 defer ts.Close()
474
475 // Raise two alarms. The first should be delayed
476 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
477 assert.Nil(t, alarmer.Raise(a), "raise failed")
478 VerifyAlarm(t, a, activeAlarmsBeforeTest + 1)
479
480 b := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
481 assert.Nil(t, alarmer.Raise(b), "raise failed")
482 VerifyAlarm(t, b, activeAlarmsBeforeTest + 2)
483
484 // Clear two alarms. The first should be delayed. Check the alarms are removed
485 assert.Nil(t, alarmer.Clear(a), "clear failed")
486 assert.Nil(t, alarmer.Clear(b), "clear failed")
487
488 time.Sleep(time.Duration(2) * time.Second)
489 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
490 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest + 4)
491}
492
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200493func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200494 receivedAlert := waitForEvent()
495
vipin6f73fa32020-10-06 06:51:53 +0000496 assert.Equal(t, expectedCount, len(alarmManager.activeAlarms))
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000497 _, ok := alarmManager.IsMatchFound(a)
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200498 assert.True(t, ok)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200499
500 return receivedAlert
501}
502
503func VerifyAlert(t *testing.T, receivedAlert, expectedAlert string) {
504 receivedAlert = strings.Replace(fmt.Sprintf("%v", receivedAlert), "\r\n", " ", -1)
505 //assert.Equal(t, receivedAlert, e)
506}
507
508func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
509 l, err := net.Listen("tcp", "localhost:9093")
510 if err != nil {
511 t.Error("Failed to create listener: " + err.Error())
512 }
513 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
514 assert.Equal(t, r.Method, method)
515 assert.Equal(t, r.URL.String(), url)
516
517 fireEvent(t, r.Body)
518
519 w.Header().Add("Content-Type", "application/json")
520 w.WriteHeader(status)
521 b, _ := json.Marshal(respData)
522 w.Write(b)
523 }))
524 ts.Listener.Close()
525 ts.Listener = l
526
527 ts.Start()
528
529 return ts
530}
531
Anssi Mannila00894a42020-10-19 11:36:26 +0300532func CreatePromAlertSimulator2(t *testing.T, method, url string) *httptest.Server {
533 l, err := net.Listen("tcp", "localhost:9093")
534 if err != nil {
535 t.Error("Failed to create listener: " + err.Error())
536 }
537 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
538 assert.Equal(t, r.Method, method)
539 assert.Equal(t, r.URL.String(), url)
540
541 w.Header().Add("Content-Type", "application/json")
542 w.WriteHeader(200)
543 // Read alerts from file
544 payload, err := readJSONFromFile("../testresources/prometheus-alerts.json")
Mohamed Abukarf5a8e712020-10-19 16:58:17 +0300545 if err != nil {
546 t.Error("Failed to send response: ", err)
Anssi Mannila00894a42020-10-19 11:36:26 +0300547 }
548 _, err = w.Write(payload)
549 if err != nil {
550 t.Error("Failed to send response: " + err.Error())
551 }
552 }))
553 ts.Listener.Close()
554 ts.Listener = l
555 ts.Start()
556 return ts
557}
558
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200559func waitForEvent() string {
560 receivedAlert := <-eventChan
561 return receivedAlert
562}
563
564func fireEvent(t *testing.T, body io.ReadCloser) {
565 reqBody, err := ioutil.ReadAll(body)
566 assert.Nil(t, err, "ioutil.ReadAll failed")
567 assert.NotNil(t, reqBody, "ioutil.ReadAll failed")
568
569 eventChan <- fmt.Sprintf("%s", reqBody)
570}
vipin541eb502020-09-22 12:04:59 +0000571
572func executeRequest(req *http.Request, handleR http.HandlerFunc) *httptest.ResponseRecorder {
573 rr := httptest.NewRecorder()
574
575 handleR.ServeHTTP(rr, req)
576
577 return rr
578}
579
580func checkResponseCode(t *testing.T, expected, actual int) bool {
581 if expected != actual {
582 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
583 return false
584 }
585 return true
586}
Anssi Mannila00894a42020-10-19 11:36:26 +0300587
588func ExecCLICommand(commandReady chan bool, command string, args ...string) {
589 go func() {
590 xapp.Logger.Info("Giving CLI command")
591 cmd := exec.Command(command, args...)
592 cmd.Dir = "../"
593 output, err := cmd.CombinedOutput()
594 if err != nil {
595 xapp.Logger.Info("CLI command failed out: %s", err)
596 }
597 xapp.Logger.Info("CLI command output: %s", output)
598 commandReady <- true
599 xapp.Logger.Info("CLI command completed")
600 }()
601}
602
603func readJSONFromFile(filename string) ([]byte, error) {
604 file, err := ioutil.ReadFile(filename)
605 if err != nil {
606 err := fmt.Errorf("readJSONFromFile() failed: Error: %v", err)
607 return nil, err
608 }
609 return file, nil
610}