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