LN0739_FM_FR7: support for setting and clearing alarm via RMR
[ric-plt/alarm-go.git] / alarm / alarm.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 alarm
22
23 import (
24         "bytes"
25         "encoding/json"
26         "errors"
27         "fmt"
28         "io/ioutil"
29         "log"
30         "net/http"
31         "os"
32         "time"
33         "unsafe"
34 )
35
36 /*
37 #cgo CFLAGS: -I../
38 #cgo LDFLAGS: -lrmr_si
39
40 #include "utils.h"
41 */
42 import "C"
43
44 // InitAlarm is the init routine which returns a new alarm instance.
45 // The MO and APP identities are given as a parameters.
46 // The identities are used when raising/clearing alarms, unless provided by the applications.
47 func InitAlarm(mo, id string) (*RICAlarm, error) {
48         r := &RICAlarm{
49                 moId:       mo,
50                 appId:      id,
51                 managerUrl: ALARM_MANAGER_HTTP_URL,
52         }
53
54         if os.Getenv("ALARM_MANAGER_URL") != "" {
55                 r.managerUrl = os.Getenv("ALARM_MANAGER_URL")
56         }
57
58         if os.Getenv("ALARM_IF_RMR") == "" {
59                 go InitRMR(r)
60         }
61         return r, nil
62 }
63
64 // Create a new Alarm instance
65 func (r *RICAlarm) NewAlarm(sp int, severity Severity, ainfo, iinfo string) Alarm {
66         return Alarm{
67                 ManagedObjectId:   r.moId,
68                 ApplicationId:     r.appId,
69                 SpecificProblem:   sp,
70                 PerceivedSeverity: severity,
71                 AdditionalInfo:    ainfo,
72                 IdentifyingInfo:   iinfo,
73         }
74 }
75
76 // Create a new AlarmMessage instance
77 func (r *RICAlarm) NewAlarmMessage(a Alarm, alarmAction AlarmAction) AlarmMessage {
78         alarmTime := time.Now().UnixNano()
79         return AlarmMessage{a, alarmAction, alarmTime}
80 }
81
82 func (r *RICAlarm) SetManagedObjectId(mo string) {
83         r.moId = mo
84 }
85
86 func (r *RICAlarm) SetApplicationId(app string) {
87         r.appId = app
88 }
89
90 // Raise a RIC alarm
91 func (r *RICAlarm) Raise(a Alarm) error {
92         r.mutex.Lock()
93         defer r.mutex.Unlock()
94
95         m := r.NewAlarmMessage(a, AlarmActionRaise)
96         return r.sendAlarmUpdateReq(m)
97 }
98
99 // Clear a RIC alarm
100 func (r *RICAlarm) Clear(a Alarm) error {
101         r.mutex.Lock()
102         defer r.mutex.Unlock()
103
104         m := r.NewAlarmMessage(a, AlarmActionClear)
105         return r.sendAlarmUpdateReq(m)
106 }
107
108 // Re-raise a RIC alarm
109 func (r *RICAlarm) Reraise(a Alarm) error {
110         r.mutex.Lock()
111         defer r.mutex.Unlock()
112
113         m := r.NewAlarmMessage(a, AlarmActionClear)
114         if err := r.sendAlarmUpdateReq(m); err != nil {
115                 return errors.New(fmt.Sprintf("Reraise failed: %v", err))
116         }
117
118         return r.sendAlarmUpdateReq(r.NewAlarmMessage(a, AlarmActionRaise))
119 }
120
121 // Clear all alarms raised by the application
122 func (r *RICAlarm) ClearAll() error {
123         r.mutex.Lock()
124         defer r.mutex.Unlock()
125
126         a := r.NewAlarm(0, SeverityDefault, "", "")
127         m := r.NewAlarmMessage(a, AlarmActionClearAll)
128
129         return r.sendAlarmUpdateReq(m)
130 }
131
132 func (r *RICAlarm) AlarmString(a AlarmMessage) string {
133         s := "MOId=%s AppId=%s SP=%d severity=%s IA=%s"
134         return fmt.Sprintf(s, a.ManagedObjectId, a.ApplicationId, a.SpecificProblem, a.PerceivedSeverity, a.IdentifyingInfo)
135 }
136
137 func (r *RICAlarm) sendAlarmUpdateReq(a AlarmMessage) error {
138
139         payload, err := json.Marshal(a)
140         if err != nil {
141                 log.Println("json.Marshal failed with error: ", err)
142                 return err
143         }
144         log.Println("Sending alarm: ", fmt.Sprintf("%s", payload))
145
146         if r.rmrCtx == nil || !r.rmrReady {
147                 url := fmt.Sprintf("%s/%s", r.managerUrl, "ric/v1/alarms")
148                 resp, err := http.Post(url, "application/json", bytes.NewReader(payload))
149                 if err != nil || resp == nil {
150                         return fmt.Errorf("Unable to send alarm: %v", err)
151                 }
152                 log.Printf("Alarm posted to %s [status=%d]", url, resp.StatusCode)
153                 return nil
154         }
155
156         datap := C.CBytes(payload)
157         defer C.free(datap)
158         meid := C.CString("ric")
159         defer C.free(unsafe.Pointer(meid))
160
161         if state := C.rmrSend(r.rmrCtx, RIC_ALARM_UPDATE, datap, C.int(len(payload)), meid); state != C.RMR_OK {
162                 log.Println("rmrSend failed with error: ", state)
163                 return errors.New(fmt.Sprintf("rmrSend failed with error: %d", state))
164         }
165
166         return nil
167 }
168
169 func (r *RICAlarm) ReceiveMessage(cb func(AlarmMessage)) error {
170         if rbuf := C.rmrRcv(r.rmrCtx); rbuf != nil {
171                 payload := C.GoBytes(unsafe.Pointer(rbuf.payload), C.int(rbuf.len))
172                 a := AlarmMessage{}
173                 if err := json.Unmarshal(payload, &a); err == nil {
174                         cb(a)
175                 }
176         }
177         return errors.New("rmrRcv failed!")
178 }
179
180 func InitRMR(r *RICAlarm) error {
181         // Setup static RT for alarm system
182         endpoint := ALARM_MANAGER_RMR_URL
183         if r.moId == "my-pod" {
184                 endpoint = "127.0.0.1:4560"
185         } else if r.moId == "my-pod-lib" {
186                 endpoint = "127.0.0.1:4588"
187         }
188
189         alarmRT := fmt.Sprintf("newrt|start\nrte|13111|%s\nnewrt|end\n", endpoint)
190         alarmRTFile := "/tmp/alarm.rt"
191
192         if err := ioutil.WriteFile(alarmRTFile, []byte(alarmRT), 0644); err != nil {
193                 log.Println("ioutil.WriteFile failed with error: ", err)
194                 return err
195         }
196
197         os.Setenv("RMR_SEED_RT", alarmRTFile)
198         os.Setenv("RMR_RTG_SVC", "-1")
199
200         if ctx := C.rmrInit(); ctx != nil {
201                 r.rmrCtx = ctx
202                 r.rmrReady = true
203                 return nil
204         }
205
206         return errors.New("rmrInit failed!")
207 }
208
209 func (r *RICAlarm) IsRMRReady() bool {
210         return r.rmrReady
211 }