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