1cb26b42cc0367fba80627c9f2dccac9f22f3233
[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                 rmrEndpoint: ALARM_MANAGER_RMR_URL,
53         }
54
55         //
56         // http service information (used in case of no rmr connectivity)
57         //
58         if os.Getenv("ALARM_MANAGER_URL") != "" {
59                 r.managerUrl = os.Getenv("ALARM_MANAGER_URL")
60         }
61
62         if os.Getenv("ALARM_MANAGER_SERVICE_NAME") != "" && os.Getenv("ALARM_MANAGER_SERVICE_PORT") != "" {
63                 r.rmrEndpoint = fmt.Sprintf("%s:%s", os.Getenv("ALARM_MANAGER_SERVICE_NAME"), os.Getenv("ALARM_MANAGER_SERVICE_PORT"))
64         }
65
66         if os.Getenv("ALARM_IF_RMR") == "" {
67                 if r.moId == "my-pod" {
68                         r.rmrEndpoint = "127.0.0.1:4560"
69                 } else if r.moId == "my-pod-lib" {
70                         r.rmrEndpoint = "127.0.0.1:4588"
71                 }
72         }
73
74         go InitRMR(r)
75
76         return r, nil
77 }
78
79 // Create a new Alarm instance
80 func (r *RICAlarm) NewAlarm(sp int, severity Severity, ainfo, iinfo string) Alarm {
81         return Alarm{
82                 ManagedObjectId:   r.moId,
83                 ApplicationId:     r.appId,
84                 SpecificProblem:   sp,
85                 PerceivedSeverity: severity,
86                 IdentifyingInfo:   iinfo,
87                 AdditionalInfo:    ainfo,
88         }
89 }
90
91 // Create a new AlarmMessage instance
92 func (r *RICAlarm) NewAlarmMessage(a Alarm, alarmAction AlarmAction) AlarmMessage {
93         alarmTime := time.Now().UnixNano()
94         return AlarmMessage{a, alarmAction, alarmTime}
95 }
96
97 func (r *RICAlarm) SetManagedObjectId(mo string) {
98         r.moId = mo
99 }
100
101 func (r *RICAlarm) SetApplicationId(app string) {
102         r.appId = app
103 }
104
105 // Raise a RIC alarm
106 func (r *RICAlarm) Raise(a Alarm) error {
107         r.mutex.Lock()
108         defer r.mutex.Unlock()
109
110         m := r.NewAlarmMessage(a, AlarmActionRaise)
111         return r.sendAlarmUpdateReq(m)
112 }
113
114 // Clear a RIC alarm
115 func (r *RICAlarm) Clear(a Alarm) error {
116         r.mutex.Lock()
117         defer r.mutex.Unlock()
118
119         m := r.NewAlarmMessage(a, AlarmActionClear)
120         return r.sendAlarmUpdateReq(m)
121 }
122
123 // Re-raise a RIC alarm
124 func (r *RICAlarm) Reraise(a Alarm) error {
125         r.mutex.Lock()
126         defer r.mutex.Unlock()
127
128         m := r.NewAlarmMessage(a, AlarmActionClear)
129         if err := r.sendAlarmUpdateReq(m); err != nil {
130                 return errors.New(fmt.Sprintf("Reraise failed: %v", err))
131         }
132
133         return r.sendAlarmUpdateReq(r.NewAlarmMessage(a, AlarmActionRaise))
134 }
135
136 // Clear all alarms raised by the application
137 func (r *RICAlarm) ClearAll() error {
138         r.mutex.Lock()
139         defer r.mutex.Unlock()
140
141         a := r.NewAlarm(0, SeverityDefault, "", "")
142         m := r.NewAlarmMessage(a, AlarmActionClearAll)
143
144         return r.sendAlarmUpdateReq(m)
145 }
146
147 func (r *RICAlarm) AlarmString(a AlarmMessage) string {
148         s := "MOId=%s AppId=%s SP=%d severity=%s IA=%s"
149         return fmt.Sprintf(s, a.ManagedObjectId, a.ApplicationId, a.SpecificProblem, a.PerceivedSeverity, a.IdentifyingInfo)
150 }
151
152 func (r *RICAlarm) sendAlarmUpdateReqWithHttp(payload []byte) error {
153         url := fmt.Sprintf("%s/%s", r.managerUrl, "ric/v1/alarms")
154         resp, err := http.Post(url, "application/json", bytes.NewReader(payload))
155         if err != nil || resp == nil {
156                 return fmt.Errorf("HttpError=Post failed with error: %v", err)
157         }
158         log.Printf("Alarm posted to %s [status=%d]", url, resp.StatusCode)
159         return nil
160 }
161
162 func (r *RICAlarm) sendAlarmUpdateReqWithRmr(payload []byte) error {
163         if r.rmrCtx == nil || !r.rmrReady {
164                 return fmt.Errorf("RmrError=rmr not ready")
165         }
166         datap := C.CBytes(payload)
167         defer C.free(datap)
168         meid := C.CString("ric")
169         defer C.free(unsafe.Pointer(meid))
170
171         if state := C.rmrSend(r.rmrCtx, RIC_ALARM_UPDATE, datap, C.int(len(payload)), meid); state != C.RMR_OK {
172                 return errors.New(fmt.Sprintf("RmrError=rmrSend failed with error: %d", state))
173         }
174         log.Printf("Alarm sent via rmr to %s", r.rmrEndpoint)
175         return nil
176 }
177
178 func (r *RICAlarm) sendAlarmUpdateReq(a AlarmMessage) error {
179
180         payload, err := json.Marshal(a)
181         if err != nil {
182                 log.Println("json.Marshal failed with error: ", err)
183                 return err
184         }
185         log.Println("Sending alarm: ", fmt.Sprintf("%s", payload))
186
187         // --
188         // Try rmr sending
189         // --
190         err = r.sendAlarmUpdateReqWithRmr(payload)
191
192         // --
193         // Try http posting if rmr is not done for some reason: rmrSend error, rmr not initialized yet etc.
194         // --
195         if err != nil {
196                 if httperr := r.sendAlarmUpdateReqWithHttp(payload); httperr != nil {
197                         err = fmt.Errorf("%s and  %s", err.Error(), httperr.Error())
198                 } else {
199                         err = nil
200                 }
201         }
202
203         if err != nil {
204                 log.Printf("Alarm sent error %s", err.Error())
205         }
206         return err
207 }
208
209 func (r *RICAlarm) ReceiveMessage(cb func(AlarmMessage)) error {
210         if rbuf := C.rmrRcv(r.rmrCtx); rbuf != nil {
211                 payload := C.GoBytes(unsafe.Pointer(rbuf.payload), C.int(rbuf.len))
212                 a := AlarmMessage{}
213                 if err := json.Unmarshal(payload, &a); err == nil {
214                         cb(a)
215                 }
216         }
217         return errors.New("rmrRcv failed!")
218 }
219
220 func InitRMR(r *RICAlarm) error {
221         // Setup static RT for alarm system
222         alarmRT := fmt.Sprintf("newrt|start\nrte|13111|%s\nnewrt|end\n", r.rmrEndpoint)
223         alarmRTFile := "/tmp/alarm.rt"
224
225         if err := ioutil.WriteFile(alarmRTFile, []byte(alarmRT), 0644); err != nil {
226                 log.Println("ioutil.WriteFile failed with error: ", err)
227                 return err
228         }
229
230         os.Setenv("RMR_SEED_RT", alarmRTFile)
231         os.Setenv("RMR_RTG_SVC", "-1")
232
233         if ctx := C.rmrInit(); ctx != nil {
234                 r.rmrCtx = ctx
235                 r.rmrReady = true
236                 return nil
237         }
238
239         return errors.New("rmrInit failed!")
240 }
241
242 func (r *RICAlarm) IsRMRReady() bool {
243         return r.rmrReady
244 }