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