0f7a8e8c0f1915fc73e047a95183e9cc32797242
[nonrtric/plt/sme.git] / capifcore / internal / eventservice / eventservice.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package eventservice
22
23 import (
24         "encoding/json"
25         "fmt"
26         "net/http"
27         "path"
28         "strconv"
29         "sync"
30
31         "github.com/labstack/echo/v4"
32         log "github.com/sirupsen/logrus"
33         "k8s.io/utils/strings/slices"
34         "oransc.org/nonrtric/capifcore/internal/common29122"
35         "oransc.org/nonrtric/capifcore/internal/eventsapi"
36         "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
37         "oransc.org/nonrtric/capifcore/internal/restclient"
38 )
39
40 type EventService struct {
41         notificationChannel chan eventsapi.EventNotification
42         client              restclient.HTTPClient
43         subscriptions       map[string]eventsapi.EventSubscription
44         idCounter           uint
45         lock                sync.Mutex
46 }
47
48 func NewEventService(c restclient.HTTPClient) *EventService {
49         es := EventService{
50                 notificationChannel: make(chan eventsapi.EventNotification),
51                 client:              c,
52                 subscriptions:       make(map[string]eventsapi.EventSubscription),
53         }
54         es.start()
55         return &es
56 }
57
58 func (es *EventService) start() {
59         go es.handleIncomingEvents()
60 }
61
62 func (es *EventService) handleIncomingEvents() {
63         for event := range es.notificationChannel {
64                 es.handleEvent(event)
65         }
66 }
67 func (es *EventService) GetNotificationChannel() chan<- eventsapi.EventNotification {
68         return es.notificationChannel
69 }
70
71 func (es *EventService) PostSubscriberIdSubscriptions(ctx echo.Context, subscriberId string) error {
72         newSubscription, err := getEventSubscriptionFromRequest(ctx)
73         errMsg := "Unable to register subscription due to %s."
74         if err != nil {
75                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
76         }
77         uri := ctx.Request().Host + ctx.Request().URL.String()
78         subId := es.getSubscriptionId(subscriberId)
79         es.addSubscription(subId, newSubscription)
80         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, subId))
81         err = ctx.JSON(http.StatusCreated, newSubscription)
82         if err != nil {
83                 // Something really bad happened, tell Echo that our handler failed
84                 return err
85         }
86
87         return nil
88 }
89
90 func (es *EventService) DeleteSubscriberIdSubscriptionsSubscriptionId(ctx echo.Context, subscriberId string, subscriptionId string) error {
91         es.lock.Lock()
92         defer es.lock.Unlock()
93
94         log.Debug(es.subscriptions)
95         if _, ok := es.subscriptions[subscriptionId]; ok {
96                 log.Debug("Deleting subscription", subscriptionId)
97                 delete(es.subscriptions, subscriptionId)
98         }
99
100         return ctx.NoContent(http.StatusNoContent)
101 }
102
103 func getEventSubscriptionFromRequest(ctx echo.Context) (eventsapi.EventSubscription, error) {
104         var subscription eventsapi.EventSubscription
105         err := ctx.Bind(&subscription)
106         if err != nil {
107                 return eventsapi.EventSubscription{}, fmt.Errorf("invalid format for subscription")
108         }
109         return subscription, nil
110 }
111
112 func (es *EventService) handleEvent(event eventsapi.EventNotification) {
113         subsIds := es.getMatchingSubs(event)
114         for _, subId := range subsIds {
115                 go es.sendEvent(event, subId)
116         }
117 }
118
119 func (es *EventService) sendEvent(event eventsapi.EventNotification, subscriptionId string) {
120         event.SubscriptionId = subscriptionId
121         e, _ := json.Marshal(event)
122         if error := restclient.Put(string(es.subscriptions[subscriptionId].NotificationDestination), []byte(e), es.client); error != nil {
123                 log.Error("Unable to send event")
124         }
125 }
126
127 func (es *EventService) getMatchingSubs(event eventsapi.EventNotification) []string {
128         es.lock.Lock()
129         defer es.lock.Unlock()
130         matchingTypeSubs := es.filterOnEventType(event)
131         matchingSubs := []string{}
132         for _, subId := range matchingTypeSubs {
133                 subscription := es.subscriptions[subId]
134                 if subscription.EventFilters == nil || event.EventDetail == nil {
135                         matchingSubs = append(matchingSubs, subId)
136                 } else if matchesFilters(event.EventDetail.ApiIds, *subscription.EventFilters, getApiIdsFromFilter) &&
137                         matchesFilters(event.EventDetail.ApiInvokerIds, *subscription.EventFilters, getInvokerIdsFromFilter) &&
138                         matchesFilters(getAefIdsFromEvent(event.EventDetail.ServiceAPIDescriptions), *subscription.EventFilters, getAefIdsFromFilter) {
139                         matchingSubs = append(matchingSubs, subId)
140                 }
141         }
142
143         return matchingSubs
144 }
145
146 func (es *EventService) filterOnEventType(event eventsapi.EventNotification) []string {
147         matchingSubs := []string{}
148         for subId, subInfo := range es.subscriptions {
149                 if slices.Contains(asStrings(subInfo.Events), string(event.Events)) {
150                         matchingSubs = append(matchingSubs, subId)
151                 }
152         }
153         return matchingSubs
154 }
155
156 func matchesFilters(eventIds *[]string, filters []eventsapi.CAPIFEventFilter, getIds func(eventsapi.CAPIFEventFilter) *[]string) bool {
157         if len(filters) == 0 || eventIds == nil {
158                 return true
159         }
160         for _, id := range *eventIds {
161                 filter := filters[0]
162                 filterIds := getIds(filter)
163                 if filterIds == nil || len(*filterIds) == 0 {
164                         return matchesFilters(eventIds, filters[1:], getIds)
165                 }
166                 return slices.Contains(*getIds(filter), id) && matchesFilters(eventIds, filters[1:], getIds)
167         }
168         return true
169 }
170
171 func getApiIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
172         return filter.ApiIds
173 }
174
175 func getInvokerIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
176         return filter.ApiInvokerIds
177 }
178
179 func getAefIdsFromEvent(serviceAPIDescriptions *[]publishserviceapi.ServiceAPIDescription) *[]string {
180         aefIds := []string{}
181         if serviceAPIDescriptions == nil {
182                 return &aefIds
183         }
184         for _, serviceDescription := range *serviceAPIDescriptions {
185                 if serviceDescription.AefProfiles == nil {
186                         return &aefIds
187                 }
188                 for _, profile := range *serviceDescription.AefProfiles {
189                         aefIds = append(aefIds, profile.AefId)
190                 }
191         }
192         return &aefIds
193 }
194
195 func getAefIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
196         return filter.AefIds
197 }
198
199 func asStrings(events []eventsapi.CAPIFEvent) []string {
200         asStrings := make([]string, len(events))
201         for i, event := range events {
202                 asStrings[i] = string(event)
203         }
204         return asStrings
205 }
206
207 func (es *EventService) getSubscriptionId(subscriberId string) string {
208         es.idCounter++
209         return subscriberId + strconv.FormatUint(uint64(es.idCounter), 10)
210 }
211
212 func (es *EventService) addSubscription(subId string, subscription eventsapi.EventSubscription) {
213         es.lock.Lock()
214         es.subscriptions[subId] = subscription
215         es.lock.Unlock()
216 }
217
218 func (es *EventService) getSubscription(subId string) *eventsapi.EventSubscription {
219         es.lock.Lock()
220         defer es.lock.Unlock()
221         if sub, ok := es.subscriptions[subId]; ok {
222                 return &sub
223         } else {
224                 return nil
225         }
226 }
227
228 // This function wraps sending of an error in the Error format, and
229 // handling the failure to marshal that.
230 func sendCoreError(ctx echo.Context, code int, message string) error {
231         pd := common29122.ProblemDetails{
232                 Cause:  &message,
233                 Status: &code,
234         }
235         err := ctx.JSON(code, pd)
236         return err
237 }