Improve locking
[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
92         log.Debug(es.subscriptions)
93         if _, ok := es.subscriptions[subscriptionId]; ok {
94                 es.deleteSubscription(subscriptionId)
95         }
96
97         return ctx.NoContent(http.StatusNoContent)
98 }
99
100 func (es *EventService) deleteSubscription(subscriptionId string) {
101         log.Debug("Deleting subscription", subscriptionId)
102         es.lock.Lock()
103         defer es.lock.Unlock()
104         delete(es.subscriptions, subscriptionId)
105 }
106
107 func getEventSubscriptionFromRequest(ctx echo.Context) (eventsapi.EventSubscription, error) {
108         var subscription eventsapi.EventSubscription
109         err := ctx.Bind(&subscription)
110         if err != nil {
111                 return eventsapi.EventSubscription{}, fmt.Errorf("invalid format for subscription")
112         }
113         return subscription, nil
114 }
115
116 func (es *EventService) handleEvent(event eventsapi.EventNotification) {
117         subsIds := es.getMatchingSubs(event)
118         for _, subId := range subsIds {
119                 go es.sendEvent(event, subId)
120         }
121 }
122
123 func (es *EventService) sendEvent(event eventsapi.EventNotification, subscriptionId string) {
124         event.SubscriptionId = subscriptionId
125         e, _ := json.Marshal(event)
126         if error := restclient.Put(string(es.subscriptions[subscriptionId].NotificationDestination), []byte(e), es.client); error != nil {
127                 log.Error("Unable to send event")
128         }
129 }
130
131 func (es *EventService) getMatchingSubs(event eventsapi.EventNotification) []string {
132         es.lock.Lock()
133         defer es.lock.Unlock()
134         matchingTypeSubs := es.filterOnEventType(event)
135         matchingSubs := []string{}
136         for _, subId := range matchingTypeSubs {
137                 subscription := es.subscriptions[subId]
138                 if subscription.EventFilters == nil || event.EventDetail == nil {
139                         matchingSubs = append(matchingSubs, subId)
140                 } else if matchesFilters(event.EventDetail.ApiIds, *subscription.EventFilters, getApiIdsFromFilter) &&
141                         matchesFilters(event.EventDetail.ApiInvokerIds, *subscription.EventFilters, getInvokerIdsFromFilter) &&
142                         matchesFilters(getAefIdsFromEvent(event.EventDetail.ServiceAPIDescriptions), *subscription.EventFilters, getAefIdsFromFilter) {
143                         matchingSubs = append(matchingSubs, subId)
144                 }
145         }
146
147         return matchingSubs
148 }
149
150 func (es *EventService) filterOnEventType(event eventsapi.EventNotification) []string {
151         matchingSubs := []string{}
152         for subId, subInfo := range es.subscriptions {
153                 if slices.Contains(asStrings(subInfo.Events), string(event.Events)) {
154                         matchingSubs = append(matchingSubs, subId)
155                 }
156         }
157         return matchingSubs
158 }
159
160 func matchesFilters(eventIds *[]string, filters []eventsapi.CAPIFEventFilter, getIds func(eventsapi.CAPIFEventFilter) *[]string) bool {
161         if len(filters) == 0 || eventIds == nil {
162                 return true
163         }
164         for _, id := range *eventIds {
165                 filter := filters[0]
166                 filterIds := getIds(filter)
167                 if filterIds == nil || len(*filterIds) == 0 {
168                         return matchesFilters(eventIds, filters[1:], getIds)
169                 }
170                 return slices.Contains(*getIds(filter), id) && matchesFilters(eventIds, filters[1:], getIds)
171         }
172         return true
173 }
174
175 func getApiIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
176         return filter.ApiIds
177 }
178
179 func getInvokerIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
180         return filter.ApiInvokerIds
181 }
182
183 func getAefIdsFromEvent(serviceAPIDescriptions *[]publishserviceapi.ServiceAPIDescription) *[]string {
184         aefIds := []string{}
185         if serviceAPIDescriptions == nil {
186                 return &aefIds
187         }
188         for _, serviceDescription := range *serviceAPIDescriptions {
189                 if serviceDescription.AefProfiles == nil {
190                         return &aefIds
191                 }
192                 for _, profile := range *serviceDescription.AefProfiles {
193                         aefIds = append(aefIds, profile.AefId)
194                 }
195         }
196         return &aefIds
197 }
198
199 func getAefIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
200         return filter.AefIds
201 }
202
203 func asStrings(events []eventsapi.CAPIFEvent) []string {
204         asStrings := make([]string, len(events))
205         for i, event := range events {
206                 asStrings[i] = string(event)
207         }
208         return asStrings
209 }
210
211 func (es *EventService) getSubscriptionId(subscriberId string) string {
212         es.idCounter++
213         return subscriberId + strconv.FormatUint(uint64(es.idCounter), 10)
214 }
215
216 func (es *EventService) addSubscription(subId string, subscription eventsapi.EventSubscription) {
217         es.lock.Lock()
218         defer es.lock.Unlock()
219         es.subscriptions[subId] = subscription
220 }
221
222 func (es *EventService) getSubscription(subId string) *eventsapi.EventSubscription {
223         es.lock.Lock()
224         defer es.lock.Unlock()
225         if sub, ok := es.subscriptions[subId]; ok {
226                 return &sub
227         } else {
228                 return nil
229         }
230 }
231
232 // This function wraps sending of an error in the Error format, and
233 // handling the failure to marshal that.
234 func sendCoreError(ctx echo.Context, code int, message string) error {
235         pd := common29122.ProblemDetails{
236                 Cause:  &message,
237                 Status: &code,
238         }
239         err := ctx.JSON(code, pd)
240         return err
241 }