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).
29 clientruntime "github.com/go-openapi/runtime/client"
30 "github.com/go-openapi/strfmt"
31 "github.com/prometheus/alertmanager/api/v2/client"
32 "github.com/prometheus/alertmanager/api/v2/client/alert"
33 "github.com/prometheus/alertmanager/api/v2/models"
34 "github.com/spf13/viper"
36 "gerrit.o-ran-sc.org/r/ric-plt/alarm-go/alarm"
37 app "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
40 type AlertStatus string
43 AlertStatusActive = "active"
44 AlertStatusResolved = "resolved"
47 type AlarmAdapter struct {
52 activeAlarms []alarm.Alarm
63 NewAlarmAdapter("", 0).Run(true)
66 func NewAlarmAdapter(amHost string, alertInterval int) *AlarmAdapter {
67 if alertInterval == 0 {
68 alertInterval = viper.GetInt("promAlertManager.alertInterval")
72 amHost = viper.GetString("promAlertManager.address")
78 amBaseUrl: viper.GetString("promAlertManager.baseUrl"),
79 amSchemes: []string{viper.GetString("promAlertManager.schemes")},
80 alertInterval: alertInterval,
81 activeAlarms: make([]alarm.Alarm, 0),
85 func (a *AlarmAdapter) Run(sdlcheck bool) {
86 app.Logger.SetMdc("alarmAdapter", fmt.Sprintf("%s:%s", Version, Hash))
87 app.SetReadyCB(func(d interface{}) { a.rmrReady = true }, true)
88 app.Resource.InjectStatusCb(a.StatusCB)
90 app.Resource.InjectRoute("/ric/v1/alarms", a.GetActiveAlarms, "GET")
91 app.Resource.InjectRoute("/ric/v1/alarms", a.RaiseAlarm, "POST")
92 app.Resource.InjectRoute("/ric/v1/alarms", a.ClearAlarm, "DELETE")
94 // Start background timer for re-raising alerts
95 a.postClear = sdlcheck
96 go a.StartAlertTimer()
98 app.RunWithParams(a, sdlcheck)
101 func (a *AlarmAdapter) StartAlertTimer() {
102 tick := time.Tick(time.Duration(a.alertInterval) * time.Millisecond)
105 for _, m := range a.activeAlarms {
106 app.Logger.Info("Re-raising alarm: %v", m)
107 a.PostAlert(a.GenerateAlertLabels(m, AlertStatusActive))
113 func (a *AlarmAdapter) Consume(rp *app.RMRParams) (err error) {
114 app.Logger.Info("Message received!")
116 defer app.Rmr.Free(rp.Mbuf)
118 case alarm.RIC_ALARM_UPDATE:
121 app.Logger.Info("Unknown Message Type '%d', discarding", rp.Mtype)
127 func (a *AlarmAdapter) HandleAlarms(rp *app.RMRParams) (*alert.PostAlertsOK, error) {
128 var m alarm.AlarmMessage
129 app.Logger.Info("Received JSON: %s", rp.Payload)
130 if err := json.Unmarshal(rp.Payload, &m); err != nil {
131 app.Logger.Error("json.Unmarshal failed: %v", err)
134 app.Logger.Info("newAlarm: %v", m)
136 if _, ok := alarm.RICAlarmDefinitions[m.Alarm.SpecificProblem]; !ok {
137 app.Logger.Warn("Alarm (SP='%d') not recognized, ignoring ...", m.Alarm.SpecificProblem)
141 // Suppress duplicate alarms
142 idx, found := a.IsMatchFound(m.Alarm)
143 if found && m.AlarmAction != alarm.AlarmActionClear {
144 app.Logger.Info("Duplicate alarm ... suppressing!")
148 // Clear alarm if found from active alarm list
149 if m.AlarmAction == alarm.AlarmActionClear {
151 a.activeAlarms = a.RemoveAlarm(a.activeAlarms, idx)
152 app.Logger.Info("Active alarm cleared!")
155 return a.PostAlert(a.GenerateAlertLabels(m.Alarm, AlertStatusResolved))
158 app.Logger.Info("No matching alarm found, ignoring!")
162 // New alarm -> update active alarms and post to Alert Manager
163 if m.AlarmAction == alarm.AlarmActionRaise {
164 a.UpdateActiveAlarms(m.Alarm)
165 return a.PostAlert(a.GenerateAlertLabels(m.Alarm, AlertStatusActive))
171 func (a *AlarmAdapter) IsMatchFound(newAlarm alarm.Alarm) (int, bool) {
172 for i, m := range a.activeAlarms {
173 if m.ManagedObjectId == newAlarm.ManagedObjectId && m.ApplicationId == newAlarm.ApplicationId &&
174 m.SpecificProblem == newAlarm.SpecificProblem && m.IdentifyingInfo == newAlarm.IdentifyingInfo {
181 func (a *AlarmAdapter) RemoveAlarm(alarms []alarm.Alarm, i int) []alarm.Alarm {
183 defer a.mutex.Unlock()
185 copy(alarms[i:], alarms[i+1:])
186 return alarms[:len(alarms)-1]
189 func (a *AlarmAdapter) UpdateActiveAlarms(newAlarm alarm.Alarm) {
191 defer a.mutex.Unlock()
193 // For now just keep the active alarms in-memory. Use SDL later
194 a.activeAlarms = append(a.activeAlarms, newAlarm)
197 func (a *AlarmAdapter) GenerateAlertLabels(newAlarm alarm.Alarm, status AlertStatus) (models.LabelSet, models.LabelSet) {
198 alarmDef := alarm.RICAlarmDefinitions[newAlarm.SpecificProblem]
199 amLabels := models.LabelSet{
200 "status": string(status),
201 "alertname": alarmDef.AlarmText,
202 "severity": string(newAlarm.PerceivedSeverity),
203 "service": fmt.Sprintf("%s:%s", newAlarm.ManagedObjectId, newAlarm.ApplicationId),
204 "system_name": "RIC",
206 amAnnotations := models.LabelSet{
207 "alarm_id": string(alarmDef.AlarmId),
208 "description": newAlarm.IdentifyingInfo,
209 "additional_info": newAlarm.AdditionalInfo,
210 "summary": alarmDef.EventType,
211 "instructions": alarmDef.OperationInstructions,
214 return amLabels, amAnnotations
217 func (a *AlarmAdapter) NewAlertmanagerClient() *client.Alertmanager {
218 cr := clientruntime.New(a.amHost, a.amBaseUrl, a.amSchemes)
219 return client.New(cr, strfmt.Default)
222 func (a *AlarmAdapter) PostAlert(amLabels, amAnnotations models.LabelSet) (*alert.PostAlertsOK, error) {
223 pa := &models.PostableAlert{
225 GeneratorURL: strfmt.URI(""),
228 Annotations: amAnnotations,
230 alertParams := alert.NewPostAlertsParams().WithAlerts(models.PostableAlerts{pa})
232 app.Logger.Info("Posting alerts: labels: %v, annotations: %v", amLabels, amAnnotations)
233 ok, err := a.NewAlertmanagerClient().Alert.PostAlerts(alertParams)
235 app.Logger.Error("Posting alerts to '%s/%s' failed with error: %v", a.amHost, a.amBaseUrl, err)
240 func (a *AlarmAdapter) StatusCB() bool {
242 app.Logger.Info("RMR not ready yet!")