2 * Copyright (c) 2020 AT&T Intellectual Property.
3 * Copyright (c) 2020 Nokia.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * This source code is part of the near-RT RIC (RAN Intelligent Controller)
18 * platform project (RICP).
27 "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"
31 "github.com/stretchr/testify/assert"
45 var alarmManager *AlarmManager
46 var alarmer *alarm.RICAlarm
47 var eventChan chan string
50 func TestMain(M *testing.M) {
51 alarmManager = NewAlarmManager("localhost:9093", 500, false)
52 alarmManager.alertInterval = 20000
53 go alarmManager.Run(false, 5)
54 time.Sleep(time.Duration(10) * time.Second)
56 // Wait until RMR is up-and-running
57 for !xapp.Rmr.IsReady() {
58 time.Sleep(time.Duration(1) * time.Second)
61 alarmer, _ = alarm.InitAlarm("my-pod", "my-app")
62 alarmManager.alarmClient = alarmer
63 time.Sleep(time.Duration(5) * time.Second)
64 eventChan = make(chan string)
69 func 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")
85 func 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"
92 alarm8004Definition.RaiseDelay = 0
93 alarm8004Definition.ClearDelay = 0
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"
100 alarm8005Definition.RaiseDelay = 0
101 alarm8005Definition.ClearDelay = 0
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"
108 alarm8006Definition.RaiseDelay = 0
109 alarm8006Definition.ClearDelay = 0
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"
116 alarm8007Definition.RaiseDelay = 0
117 alarm8007Definition.ClearDelay = 0
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"
123 alarm8008Definition.OperationInstructions = "Clear alarms or raise threshold"
124 alarm8008Definition.RaiseDelay = 0
125 alarm8008Definition.ClearDelay = 0
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"
131 alarm8009Definition.OperationInstructions = "Clear alarms or raise threshold"
132 alarm8009Definition.RaiseDelay = 0
133 alarm8009Definition.ClearDelay = 0
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)
145 func 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")
161 func TestDeleteAlarmDefinitions(t *testing.T) {
162 xapp.Logger.Info("TestDeleteAlarmDefinitions")
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)
176 req, _ = http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
177 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)
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)
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"
197 alarm8004Definition.RaiseDelay = 0
198 alarm8004Definition.ClearDelay = 0
199 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)
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)
215 func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
216 xapp.Logger.Info("TestNewAlarmStoredAndPostedSucess")
217 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
220 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
221 assert.Nil(t, alarmer.Raise(a), "raise failed")
226 func TestAlarmClearedSucess(t *testing.T) {
227 xapp.Logger.Info("TestAlarmClearedSucess")
228 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
232 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
233 assert.Nil(t, alarmer.Raise(a), "raise failed")
237 // Now Clear the alarm and check alarm is removed
238 a = alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityCritical, "Some App data", "eth 0 1")
239 assert.Nil(t, alarmer.Clear(a), "clear failed")
241 time.Sleep(time.Duration(2) * time.Second)
242 assert.Equal(t, len(alarmManager.activeAlarms), 0)
245 func TestMultipleAlarmsRaisedSucess(t *testing.T) {
246 xapp.Logger.Info("TestMultipleAlarmsRaisedSucess")
247 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
251 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
252 assert.Nil(t, alarmer.Raise(a), "raise failed")
254 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
255 assert.Nil(t, alarmer.Raise(b), "raise failed")
257 time.Sleep(time.Duration(2) * time.Second)
262 func TestMultipleAlarmsClearedSucess(t *testing.T) {
263 xapp.Logger.Info("TestMultipleAlarmsClearedSucess")
264 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
268 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
269 assert.Nil(t, alarmer.Clear(a), "clear failed")
271 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
272 assert.Nil(t, alarmer.Clear(b), "clear failed")
274 time.Sleep(time.Duration(2) * time.Second)
275 assert.Equal(t, len(alarmManager.activeAlarms), 0)
278 func TestAlarmsSuppresedSucess(t *testing.T) {
279 xapp.Logger.Info("TestAlarmsSuppresedSucess")
280 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
283 // Raise two similar/matching alarms ... the second one suppresed
284 a := alarmer.NewAlarm(alarm.RIC_RT_DISTRIBUTION_FAILED, alarm.SeverityMajor, "Some App data", "eth 0 1")
285 assert.Nil(t, alarmer.Raise(a), "raise failed")
286 assert.Nil(t, alarmer.Raise(a), "raise failed")
289 assert.Nil(t, alarmer.Clear(a), "clear failed")
292 func TestInvalidAlarms(t *testing.T) {
293 xapp.Logger.Info("TestInvalidAlarms")
294 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)
299 func TestAlarmHandlingErrorCases(t *testing.T) {
300 xapp.Logger.Info("TestAlarmHandlingErrorCases")
301 ok, err := alarmManager.HandleAlarms(&xapp.RMRParams{})
302 assert.Equal(t, err.Error(), "unexpected end of JSON input")
303 assert.Nil(t, ok, "raise failed")
306 func TestConsumeUnknownMessage(t *testing.T) {
307 xapp.Logger.Info("TestConsumeUnknownMessage")
308 err := alarmManager.Consume(&xapp.RMRParams{})
309 assert.Nil(t, err, "raise failed")
312 func TestStatusCallback(t *testing.T) {
313 xapp.Logger.Info("TestStatusCallback")
314 assert.Equal(t, true, alarmManager.StatusCB())
317 func 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
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")
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)
332 // Check HTTP Status Code
333 checkResponseCode(t, http.StatusOK, response.Code)
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")
341 time.Sleep(time.Duration(1) * time.Second)
342 alarmManager.maxActiveAlarms = 5000
343 alarmManager.maxAlarmHistory = 20000
349 func 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")
354 commandReady := make(chan bool, 1)
355 command := "cli/alarm-cli"
356 args := []string{"alerts", "--active", "true", "--inhibited", "true", "--silenced", "--unprocessed", "true", "true", "--host", "localhost", "--port", "9093", "flushall"}
357 ExecCLICommand(commandReady, command, args...)
363 func TestDelayedAlarmRaiseAndClear(t *testing.T) {
364 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear")
366 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
367 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
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)
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)
392 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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)
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")
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)
408 func TestDelayedAlarmRaiseAndClear2(t *testing.T) {
409 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear2")
411 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
412 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
414 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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)
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)
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")
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)
435 func TestDelayedAlarmRaiseAndClear3(t *testing.T) {
436 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear3")
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)
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)
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)
469 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
470 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
472 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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)
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)
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")
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)
493 func TestClearExpiredAlarms(t *testing.T) {
494 xapp.Logger.Info("TestClearExpiredAlarms")
496 a := alarm.AlarmMessage{
497 Alarm: alarmer.NewAlarm(8007, alarm.SeverityWarning, "threshold", ""),
498 AlarmAction: alarm.AlarmActionRaise,
499 AlarmTime: time.Now().UnixNano(),
501 d := alarm.RICAlarmDefinitions[8007]
502 n := AlarmNotification{a, *d}
503 alarmManager.activeAlarms = make([]AlarmNotification, 0)
504 alarmManager.UpdateActiveAlarmList(&n)
507 a.Alarm.SpecificProblem = 1234
508 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
512 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
515 a.Alarm.SpecificProblem = 8007
517 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
519 // TTL expired, alarm should be cleared
520 time.Sleep(time.Duration(3) * time.Second)
521 assert.Equal(t, len(alarmManager.activeAlarms), 1)
522 assert.True(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
523 assert.Equal(t, len(alarmManager.activeAlarms), 0)
526 func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
527 receivedAlert := waitForEvent()
529 assert.Equal(t, expectedCount, len(alarmManager.activeAlarms))
530 _, ok := alarmManager.IsMatchFound(a)
536 func VerifyAlert(t *testing.T, receivedAlert, expectedAlert string) {
537 receivedAlert = strings.Replace(fmt.Sprintf("%v", receivedAlert), "\r\n", " ", -1)
538 //assert.Equal(t, receivedAlert, e)
541 func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
542 l, err := net.Listen("tcp", "localhost:9093")
544 t.Error("Failed to create listener: " + err.Error())
546 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
547 assert.Equal(t, r.Method, method)
548 assert.Equal(t, r.URL.String(), url)
552 w.Header().Add("Content-Type", "application/json")
553 w.WriteHeader(status)
554 b, _ := json.Marshal(respData)
565 func CreatePromAlertSimulator2(t *testing.T, method, url string) *httptest.Server {
566 l, err := net.Listen("tcp", "localhost:9093")
568 t.Error("Failed to create listener: " + err.Error())
570 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
571 assert.Equal(t, r.Method, method)
572 assert.Equal(t, r.URL.String(), url)
574 w.Header().Add("Content-Type", "application/json")
576 // Read alerts from file
577 payload, err := readJSONFromFile("../testresources/prometheus-alerts.json")
579 t.Error("Failed to send response: ", err)
581 _, err = w.Write(payload)
583 t.Error("Failed to send response: " + err.Error())
592 func waitForEvent() string {
593 receivedAlert := <-eventChan
597 func fireEvent(t *testing.T, body io.ReadCloser) {
598 reqBody, err := ioutil.ReadAll(body)
599 assert.Nil(t, err, "ioutil.ReadAll failed")
600 assert.NotNil(t, reqBody, "ioutil.ReadAll failed")
602 eventChan <- fmt.Sprintf("%s", reqBody)
605 func executeRequest(req *http.Request, handleR http.HandlerFunc) *httptest.ResponseRecorder {
606 rr := httptest.NewRecorder()
608 handleR.ServeHTTP(rr, req)
613 func checkResponseCode(t *testing.T, expected, actual int) bool {
614 if expected != actual {
615 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
621 func ExecCLICommand(commandReady chan bool, command string, args ...string) {
623 xapp.Logger.Info("Giving CLI command")
624 cmd := exec.Command(command, args...)
626 output, err := cmd.CombinedOutput()
628 xapp.Logger.Info("CLI command failed out: %s", err)
630 xapp.Logger.Info("CLI command output: %s", output)
632 xapp.Logger.Info("CLI command completed")
636 func readJSONFromFile(filename string) ([]byte, error) {
637 file, err := ioutil.ReadFile(filename)
639 err := fmt.Errorf("readJSONFromFile() failed: Error: %v", err)