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).
26 "github.com/stretchr/testify/assert"
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"
42 var alarmManager *AlarmManager
43 var alarmer *alarm.RICAlarm
44 var eventChan chan string
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)
53 // Wait until RMR is up-and-running
54 for !xapp.Rmr.IsReady() {
55 time.Sleep(time.Duration(1) * time.Second)
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)
66 func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
67 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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")
76 func TestAlarmClearedSucess(t *testing.T) {
77 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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")
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")
90 time.Sleep(time.Duration(2) * time.Second)
91 assert.Equal(t, len(alarmManager.activeAlarms), 0)
94 func TestMultipleAlarmsRaisedSucess(t *testing.T) {
95 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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")
102 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
103 assert.Nil(t, alarmer.Raise(b), "raise failed")
109 func TestMultipleAlarmsClearedSucess(t *testing.T) {
110 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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")
117 b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
118 assert.Nil(t, alarmer.Clear(b), "clear failed")
120 time.Sleep(time.Duration(2) * time.Second)
121 assert.Equal(t, len(alarmManager.activeAlarms), 0)
124 func TestAlarmsSuppresedSucess(t *testing.T) {
125 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
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")
134 assert.Nil(t, alarmer.Clear(a), "clear failed")
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)
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")
150 func TestConsumeUnknownMessage(t *testing.T) {
151 err := alarmManager.Consume(&xapp.RMRParams{})
152 assert.Nil(t, err, "raise failed")
155 func TestStatusCallback(t *testing.T) {
156 assert.Equal(t, true, alarmManager.StatusCB())
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
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")
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)
174 // Check HTTP Status Code
175 checkResponseCode(t, http.StatusOK, response.Code)
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")
183 time.Sleep(time.Duration(1) * time.Second)
184 alarmManager.maxActiveAlarms = 5000
185 alarmManager.maxAlarmHistory = 20000
191 func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
192 receivedAlert := waitForEvent()
194 assert.Equal(t, len(alarmManager.activeAlarms), expectedCount)
195 _, ok := alarmManager.IsMatchFound(a)
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)
206 func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
207 l, err := net.Listen("tcp", "localhost:9093")
209 t.Error("Failed to create listener: " + err.Error())
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)
217 w.Header().Add("Content-Type", "application/json")
218 w.WriteHeader(status)
219 b, _ := json.Marshal(respData)
230 func waitForEvent() string {
231 receivedAlert := <-eventChan
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")
240 eventChan <- fmt.Sprintf("%s", reqBody)
243 func executeRequest(req *http.Request, handleR http.HandlerFunc) *httptest.ResponseRecorder {
244 rr := httptest.NewRecorder()
246 handleR.ServeHTTP(rr, req)
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)