c50084b732995f01efdc1c1af5936662c2266112
[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         "bytes"
25         "encoding/json"
26         "fmt"
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"
32         "io"
33         "io/ioutil"
34         "net"
35         "net/http"
36         "net/http/httptest"
37         "os"
38         "os/exec"
39         "strconv"
40         "strings"
41         "testing"
42         "time"
43 )
44
45 var alarmManager *AlarmManager
46 var alarmer *alarm.RICAlarm
47 var eventChan chan string
48
49 // Test cases
50 func TestMain(M *testing.M) {
51         alarmManager = NewAlarmManager("localhost:9093", 500, false)
52         alarmManager.alertInterval = 20000
53         go alarmManager.Run(false)
54         time.Sleep(time.Duration(10) * time.Second)
55
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")
62         alarmManager.alarmClient = alarmer
63         time.Sleep(time.Duration(5) * time.Second)
64         eventChan = make(chan string)
65
66         os.Exit(M.Run())
67 }
68
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")
82         }
83 }
84
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
94
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
102
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
110
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
118
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
126
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
134
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
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")
158         }
159 }
160
161 func 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)
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)
182
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"
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)
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
215 func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
216         xapp.Logger.Info("TestNewAlarmStoredAndPostedSucess")
217         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
218         defer ts.Close()
219
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")
222
223         VerifyAlarm(t, a, 1)
224 }
225
226 func TestAlarmClearedSucess(t *testing.T) {
227         xapp.Logger.Info("TestAlarmClearedSucess")
228         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
229         defer ts.Close()
230
231         // Raise the alarm
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")
234
235         VerifyAlarm(t, a, 1)
236
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")
240
241         time.Sleep(time.Duration(2) * time.Second)
242         assert.Equal(t, len(alarmManager.activeAlarms), 0)
243 }
244
245 func TestMultipleAlarmsRaisedSucess(t *testing.T) {
246         xapp.Logger.Info("TestMultipleAlarmsRaisedSucess")
247         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
248         defer ts.Close()
249
250         // Raise two alarms
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")
253
254         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
255         assert.Nil(t, alarmer.Raise(b), "raise failed")
256
257         time.Sleep(time.Duration(2) * time.Second)
258         VerifyAlarm(t, a, 2)
259         VerifyAlarm(t, b, 2)
260 }
261
262 func TestMultipleAlarmsClearedSucess(t *testing.T) {
263         xapp.Logger.Info("TestMultipleAlarmsClearedSucess")
264         ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
265         defer ts.Close()
266
267         // Raise two alarms
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")
270
271         b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
272         assert.Nil(t, alarmer.Clear(b), "clear failed")
273
274         time.Sleep(time.Duration(2) * time.Second)
275         assert.Equal(t, len(alarmManager.activeAlarms), 0)
276 }
277
278 func TestAlarmsSuppresedSucess(t *testing.T) {
279         xapp.Logger.Info("TestAlarmsSuppresedSucess")
280         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
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")
287
288         VerifyAlarm(t, a, 1)
289         assert.Nil(t, alarmer.Clear(a), "clear failed")
290 }
291
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)
297 }
298
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")
304 }
305
306 func TestConsumeUnknownMessage(t *testing.T) {
307         xapp.Logger.Info("TestConsumeUnknownMessage")
308         err := alarmManager.Consume(&xapp.RMRParams{})
309         assert.Nil(t, err, "raise failed")
310 }
311
312 func TestStatusCallback(t *testing.T) {
313         xapp.Logger.Info("TestStatusCallback")
314         assert.Equal(t, true, alarmManager.StatusCB())
315 }
316
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
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
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")
353
354         commandReady := make(chan bool, 1)
355         command := "cli/alarm-cli"
356         args := []string{"gapam", "--active", "true", "--inhibited", "true", "--silenced", "--unprocessed", "true", "true", "--host", "localhost", "--port", "9093", "flushall"}
357         ExecCLICommand(commandReady, command, args...)
358         <-commandReady
359
360         ts.Close()
361 }
362
363 func 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
408 func 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
435 func 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
493 func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
494         receivedAlert := waitForEvent()
495
496         assert.Equal(t, expectedCount, len(alarmManager.activeAlarms))
497         _, ok := alarmManager.IsMatchFound(a)
498         assert.True(t, ok)
499
500         return receivedAlert
501 }
502
503 func 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
508 func 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
532 func 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")
545                 if err != nil {
546                         t.Error("Failed to send response: ", err)
547                 }
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
559 func waitForEvent() string {
560         receivedAlert := <-eventChan
561         return receivedAlert
562 }
563
564 func 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 }
571
572 func 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
580 func 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 }
587
588 func 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
603 func 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 }