Improve documentation
[nonrtric/rapp/ransliceassurance.git] / icsversion / internal / odusliceassurance / app.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 sliceassurance
22
23 import (
24         "fmt"
25         "net/http"
26
27         "github.com/gorilla/mux"
28         log "github.com/sirupsen/logrus"
29         "oransc.org/usecase/oduclosedloop/icsversion/internal/config"
30         "oransc.org/usecase/oduclosedloop/icsversion/internal/restclient"
31         "oransc.org/usecase/oduclosedloop/icsversion/internal/structures"
32 )
33
34 var started bool
35 var icsAddr string
36 var consumerPort string
37 var jobId string
38
39 const (
40         THRESHOLD_TPUT          = 7000
41         DEFAULT_DEDICATED_RATIO = 15
42         NEW_DEDICATED_RATIO     = 25
43 )
44
45 var jobRegistrationInfo = struct {
46         InfoTypeID            string      `json:"info_type_id"`
47         JobResultURI          string      `json:"job_result_uri"`
48         JobOwner              string      `json:"job_owner"`
49         JobDefinition         interface{} `json:"job_definition"`
50         StatusNotificationURI string      `json:"status_notification_uri"`
51 }{
52         InfoTypeID:   "Performance_Measurement_Streaming",
53         JobResultURI: "",
54         JobOwner:     "O-DU Slice Assurance Use Case",
55 }
56
57 type App struct {
58         client *restclient.Client
59         data   *structures.SliceAssuranceMeas
60         sdnr   SdnrHandler
61         mh     MessageHandler
62 }
63
64 var sdnrConfig SdnrConfiguration
65
66 func (a *App) Initialize(config *config.Configuration) {
67         consumerPort = fmt.Sprint(config.ConsumerPort)
68         jobRegistrationInfo.JobResultURI = config.ConsumerHost + ":" + consumerPort
69         jobRegistrationInfo.StatusNotificationURI = config.ConsumerHost + ":" + consumerPort
70         var job_definition struct{}
71         jobRegistrationInfo.JobDefinition = job_definition
72
73         sdnrConfig = SdnrConfiguration{
74                 SDNRAddress:  config.SDNRAddress,
75                 SDNRUser:     config.SDNRUser,
76                 SDNRPassword: config.SDNPassword,
77                 NodeId:       config.NodeId,
78         }
79         icsAddr = config.InfoCoordinatorAddress
80         jobId = config.JobId
81
82         a.client = restclient.New(&http.Client{}, false)
83         a.data = structures.NewSliceAssuranceMeas()
84
85         a.sdnr = *NewSdnrHandler(sdnrConfig, a.client, a.data)
86         a.mh = *NewMessageHandler(a.data)
87 }
88
89 func (a *App) StartServer() {
90         fmt.Printf("Starting Server %v", consumerPort)
91         err := http.ListenAndServe(fmt.Sprintf(":%v", consumerPort), a.getRouter())
92
93         if err != nil {
94                 log.Errorf("Server stopped unintentionally due to: %v. Deleting job.", err)
95                 if deleteErr := a.deleteJob(); deleteErr != nil {
96                         log.Errorf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId)
97                 }
98         }
99 }
100
101 func (a *App) getRouter() *mux.Router {
102
103         r := mux.NewRouter()
104         r.HandleFunc("/", a.run).Methods(http.MethodPost).Name("messageHandler")
105         r.HandleFunc("/status", a.statusHandler).Methods(http.MethodGet).Name("status")
106         r.HandleFunc("/admin/start", a.startHandler).Methods(http.MethodPost).Name("start")
107         r.HandleFunc("/admin/stop", a.stopHandler).Methods(http.MethodPost).Name("stop")
108
109         return r
110 }
111
112 func (a *App) run(w http.ResponseWriter, r *http.Request) {
113         a.mh.ProcessMessage(r.Body)
114
115         for key := range a.data.Metrics {
116                 a.sdnr.getRRMInformation(key.Duid)
117         }
118         a.sdnr.updateDedicatedRatio()
119 }
120
121 func (a *App) statusHandler(w http.ResponseWriter, r *http.Request) {
122         log.Debug("statusHandler:")
123         runStatus := "started"
124         if !started {
125                 runStatus = "stopped"
126         }
127         fmt.Fprintf(w, `{"status": "%v"}`, runStatus)
128 }
129
130 func (a *App) startHandler(w http.ResponseWriter, r *http.Request) {
131         log.Debug("Register job in ICS.")
132
133         putErr := a.client.Put(icsAddr+"/data-consumer/v1/info-jobs/"+jobId, jobRegistrationInfo, nil)
134         if putErr != nil {
135                 http.Error(w, fmt.Sprintf("Unable to register consumer job due to: %v.", putErr), http.StatusBadRequest)
136                 return
137         }
138         log.Debug("Registered job.")
139         started = true
140 }
141
142 func (a *App) stopHandler(w http.ResponseWriter, r *http.Request) {
143         deleteErr := a.deleteJob()
144         if deleteErr != nil {
145                 http.Error(w, fmt.Sprintf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId), http.StatusBadRequest)
146                 return
147         }
148         log.Debug("Deleted job.")
149         started = false
150 }
151
152 func (a *App) deleteJob() error {
153         return a.client.Delete(icsAddr+"/data-consumer/v1/info-jobs/"+jobId, nil, nil)
154 }
155
156 func (a *App) Teardown() {
157         log.Info("Shutting down gracefully.")
158         deleteErr := a.deleteJob()
159         if deleteErr != nil {
160                 log.Errorf("Unable to delete job on shutdown due to: %v. Please remove job %v manually.", deleteErr, jobId)
161         }
162
163 }