Release image version 1.1.2
[ric-app/hw-go.git] / hwApp.go
1 /*
2 ==================================================================================
3   Copyright (c) 2020 Samsung
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 ==================================================================================
18 */
19 package main
20
21 import (
22         "encoding/json"
23
24         "gerrit.o-ran-sc.org/r/ric-plt/alarm-go.git/alarm"
25         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/clientmodel"
26         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
27 )
28
29 type HWApp struct {
30         stats map[string]xapp.Counter
31 }
32
33 var (
34         A1_POLICY_QUERY      = 20013
35         POLICY_QUERY_PAYLOAD = "{\"policy_type_id\":20000}"
36         reqId                = int64(1)
37         seqId                = int64(1)
38         funId                = int64(1)
39         actionId             = int64(1)
40         actionType           = "report"
41         subsequestActioType  = "continue"
42         timeToWait           = "w10ms"
43         direction            = int64(0)
44         procedureCode        = int64(27)
45         xappEventInstanceID  = int64(1234)
46         typeOfMessage        = int64(1)
47         subscriptionId       = ""
48         hPort                = int64(8080)
49         rPort                = int64(4560)
50         clientEndpoint       = clientmodel.SubscriptionParamsClientEndpoint{Host: "service-ricxapp-hw-go-rmr.ricxapp", HTTPPort: &hPort, RMRPort: &rPort}
51 )
52
53 func (e *HWApp) sendPolicyQuery() {
54         xapp.Logger.Info("Invoked method to send  policy query message")
55
56         // prepare and send policy query message over RMR
57         rmrParams := new(xapp.RMRParams)
58         rmrParams.Mtype = A1_POLICY_QUERY // A1_POLICY_QUERY
59         rmrParams.Payload = []byte(POLICY_QUERY_PAYLOAD)
60
61         // send rmr message
62         flg := xapp.Rmr.SendMsg(rmrParams)
63
64         if flg {
65                 xapp.Logger.Info("Successfully sent policy query message over RMR")
66         } else {
67                 xapp.Logger.Info("Failed to send policy query message over RMR")
68         }
69 }
70
71 func (e *HWApp) ConfigChangeHandler(f string) {
72         xapp.Logger.Info("Config file changed")
73 }
74
75 func (e *HWApp) getEnbList() ([]*xapp.RNIBNbIdentity, error) {
76         enbs, err := xapp.Rnib.GetListEnbIds()
77
78         if err != nil {
79                 xapp.Logger.Error("err: %s", err)
80                 return nil, err
81         }
82
83         xapp.Logger.Info("List for connected eNBs :")
84         for index, enb := range enbs {
85                 xapp.Logger.Info("%d. enbid: %s", index+1, enb.InventoryName)
86         }
87         return enbs, nil
88 }
89
90 func (e *HWApp) getGnbList() ([]*xapp.RNIBNbIdentity, error) {
91         gnbs, err := xapp.Rnib.GetListGnbIds()
92
93         if err != nil {
94                 xapp.Logger.Error("err: %s", err)
95                 return nil, err
96         }
97
98         xapp.Logger.Info("List of connected gNBs :")
99         for index, gnb := range gnbs {
100                 xapp.Logger.Info("%d. gnbid : %s", index+1, gnb.InventoryName)
101         }
102         return gnbs, nil
103 }
104
105 func (e *HWApp) getnbList() []*xapp.RNIBNbIdentity {
106         nbs := []*xapp.RNIBNbIdentity{}
107
108         if enbs, err := e.getEnbList(); err == nil {
109                 nbs = append(nbs, enbs...)
110         }
111
112         if gnbs, err := e.getGnbList(); err == nil {
113                 nbs = append(nbs, gnbs...)
114         }
115         return nbs
116 }
117
118 func (e *HWApp) sendSubscription(meid string) {
119
120         xapp.Logger.Info("sending subscription request for meid : %s", meid)
121
122         subscriptionParams := clientmodel.SubscriptionParams{
123                 ClientEndpoint: &clientEndpoint,
124                 Meid:           &meid,
125                 RANFunctionID:  &funId,
126                 SubscriptionDetails: clientmodel.SubscriptionDetailsList([]*clientmodel.SubscriptionDetail{
127                         {
128                                 ActionToBeSetupList: clientmodel.ActionsToBeSetup{
129                                         &clientmodel.ActionToBeSetup{
130                                                 ActionDefinition: clientmodel.ActionDefinition([]int64{1, 2, 3, 4}),
131                                                 ActionID:         &actionId,
132                                                 ActionType:       &actionType,
133                                                 SubsequentAction: &clientmodel.SubsequentAction{
134                                                         SubsequentActionType: &subsequestActioType,
135                                                         TimeToWait:           &timeToWait,
136                                                 },
137                                         },
138                                 },
139                                 EventTriggers:       clientmodel.EventTriggerDefinition([]int64{1, 2, 3, 4}),
140                                 XappEventInstanceID: &xappEventInstanceID,
141                         },
142                 }),
143         }
144
145         b, err := json.MarshalIndent(subscriptionParams, "", "  ")
146
147         if err != nil {
148                 xapp.Logger.Error("Json marshaling failed : %s", err)
149                 return
150         }
151
152         xapp.Logger.Info("*****body: %s ", string(b))
153
154         resp, err := xapp.Subscription.Subscribe(&subscriptionParams)
155
156         if err != nil {
157                 xapp.Logger.Error("subscription failed (%s) with error: %s", meid, err)
158
159                 // subscription failed, raise alarm
160                 err := xapp.Alarm.Raise(8086, alarm.SeverityCritical, meid, "subscriptionFailed")
161                 if err != nil {
162                         xapp.Logger.Error("Raising alarm failed with error %v", err)
163                 }
164
165                 return
166         }
167         xapp.Logger.Info("Successfully subcription done (%s), subscription id : %s", meid, *resp.SubscriptionID)
168 }
169
170 func (e *HWApp) xAppStartCB(d interface{}) {
171         xapp.Logger.Info("xApp ready call back received")
172
173         // get the list of all NBs
174         nbList := e.getnbList()
175
176         // send subscription request to each of the NBs
177         for _, nb := range nbList {
178                 e.sendSubscription(nb.InventoryName)
179         }
180 }
181
182 func (e *HWApp) handleRICIndication(ranName string, r *xapp.RMRParams) {
183         // update metrics for indication message
184         e.stats["RICIndicationRx"].Inc()
185 }
186
187 func (e *HWApp) Consume(msg *xapp.RMRParams) (err error) {
188         id := xapp.Rmr.GetRicMessageName(msg.Mtype)
189
190         xapp.Logger.Info("Message received: name=%s meid=%s subId=%d txid=%s len=%d", id, msg.Meid.RanName, msg.SubId, msg.Xid, msg.PayloadLen)
191
192         switch id {
193         // policy request handler
194         case "A1_POLICY_REQUEST":
195                 xapp.Logger.Info("Recived policy instance list")
196
197         // health check request
198         case "RIC_HEALTH_CHECK_REQ":
199                 xapp.Logger.Info("Received health check request")
200
201         // RIC INDICATION message
202         case "RIC_INDICATION":
203                 xapp.Logger.Info("Received RIC Indication message")
204                 e.handleRICIndication(msg.Meid.RanName, msg)
205
206         default:
207                 xapp.Logger.Info("Unknown message type '%d', discarding", msg.Mtype)
208         }
209
210         defer func() {
211                 xapp.Rmr.Free(msg.Mbuf)
212                 msg.Mbuf = nil
213         }()
214         return
215 }
216
217 func (e *HWApp) Run() {
218
219         // set MDC
220         xapp.Logger.SetMdc("HWApp", "0.0.1")
221
222         // set config change listener
223         xapp.AddConfigChangeListener(e.ConfigChangeHandler)
224
225         // register callback after xapp ready
226         xapp.SetReadyCB(e.xAppStartCB, true)
227
228         // reading configuration from config file
229         waitForSdl := xapp.Config.GetBool("db.waitForSdl")
230
231         // start xapp
232         xapp.RunWithParams(e, waitForSdl)
233
234 }
235
236 func main() {
237         // Defind metrics counter that the xapp provides
238         metrics := []xapp.CounterOpts{
239                 {
240                         Name: "RICIndicationRx",
241                         Help: "Total number of RIC Indication message received",
242                 },
243         }
244
245         hw := HWApp{
246                 stats: xapp.Metric.RegisterCounterGroup(metrics, "hw_go"), // register counter
247         }
248         hw.Run()
249 }