46bc2a23315507ab6d934f0737be746c1ac1e74c
[nonrtric.git] / dmaap-mediator-producer / internal / server / server.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: 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 server
22
23 import (
24         "encoding/json"
25         "fmt"
26         "io/ioutil"
27         "net/http"
28
29         "github.com/gorilla/mux"
30         log "github.com/sirupsen/logrus"
31         "oransc.org/nonrtric/dmaapmediatorproducer/internal/jobs"
32 )
33
34 const HealthCheckPath = "/health_check"
35 const AddJobPath = "/info_job"
36 const jobIdToken = "infoJobId"
37 const deleteJobPath = AddJobPath + "/{" + jobIdToken + "}"
38 const logLevelToken = "level"
39 const logAdminPath = "/admin/log"
40
41 type ErrorInfo struct {
42         // A URI reference that identifies the problem type.
43         Type string `json:"type" swaggertype:"string"`
44         // A short, human-readable summary of the problem type.
45         Title string `json:"title" swaggertype:"string"`
46         // The HTTP status code generated by the origin server for this occurrence of the problem.
47         Status int `json:"status" swaggertype:"integer" example:"400"`
48         // A human-readable explanation specific to this occurrence of the problem.
49         Detail string `json:"detail" swaggertype:"string" example:"Info job type not found"`
50         // A URI reference that identifies the specific occurrence of the problem.
51         Instance string `json:"instance" swaggertype:"string"`
52 } // @name ErrorInfo
53
54 type ProducerCallbackHandler struct {
55         jobsManager jobs.JobsManager
56 }
57
58 func NewProducerCallbackHandler(jm jobs.JobsManager) *ProducerCallbackHandler {
59         return &ProducerCallbackHandler{
60                 jobsManager: jm,
61         }
62 }
63
64 func NewRouter(jm jobs.JobsManager, hcf func(http.ResponseWriter, *http.Request)) *mux.Router {
65         callbackHandler := NewProducerCallbackHandler(jm)
66         r := mux.NewRouter()
67         r.HandleFunc(HealthCheckPath, hcf).Methods(http.MethodGet).Name("health_check")
68         r.HandleFunc(AddJobPath, callbackHandler.addInfoJobHandler).Methods(http.MethodPost).Name("add")
69         r.HandleFunc(deleteJobPath, callbackHandler.deleteInfoJobHandler).Methods(http.MethodDelete).Name("delete")
70         r.HandleFunc(logAdminPath, callbackHandler.setLogLevel).Methods(http.MethodPut).Name("setLogLevel")
71         r.NotFoundHandler = &notFoundHandler{}
72         r.MethodNotAllowedHandler = &methodNotAllowedHandler{}
73         return r
74 }
75
76 // @Summary      Add info job
77 // @Description  Callback for ICS to add an info job
78 // @Tags         Data producer (callbacks)
79 // @Accept       json
80 // @Param        user  body  jobs.JobInfo  true  "Info job data"
81 // @Success      200
82 // @Failure      400  {object}  ErrorInfo     "Problem as defined in https://tools.ietf.org/html/rfc7807"
83 // @Header       400  {string}  Content-Type  "application/problem+json"
84 // @Router       /info_job [post]
85 func (h *ProducerCallbackHandler) addInfoJobHandler(w http.ResponseWriter, r *http.Request) {
86         b, readErr := ioutil.ReadAll(r.Body)
87         if readErr != nil {
88                 returnError(fmt.Sprintf("Unable to read body due to: %v", readErr), w)
89                 return
90         }
91         jobInfo := jobs.JobInfo{}
92         if unmarshalErr := json.Unmarshal(b, &jobInfo); unmarshalErr != nil {
93                 returnError(fmt.Sprintf("Invalid json body. Cause: %v", unmarshalErr), w)
94                 return
95         }
96         if err := h.jobsManager.AddJobFromRESTCall(jobInfo); err != nil {
97                 returnError(fmt.Sprintf("Invalid job info. Cause: %v", err), w)
98                 return
99         }
100 }
101
102 // @Summary      Delete info job
103 // @Description  Callback for ICS to delete an info job
104 // @Tags         Data producer (callbacks)
105 // @Param        infoJobId  path  string  true  "Info job ID"
106 // @Success      200
107 // @Router       /info_job/{infoJobId} [delete]
108 func (h *ProducerCallbackHandler) deleteInfoJobHandler(w http.ResponseWriter, r *http.Request) {
109         vars := mux.Vars(r)
110         id, ok := vars[jobIdToken]
111         if !ok {
112                 http.Error(w, "Must provide infoJobId.", http.StatusBadRequest)
113                 return
114         }
115
116         h.jobsManager.DeleteJobFromRESTCall(id)
117 }
118
119 // @Summary      Set log level
120 // @Description  Set the log level of the producer.
121 // @Tags         Admin
122 // @Param        level  query  string  false  "string enums"  Enums(Error, Warn, Info, Debug)
123 // @Success      200
124 // @Failure      400  {object}  ErrorInfo     "Problem as defined in https://tools.ietf.org/html/rfc7807"
125 // @Header       400  {string}  Content-Type  "application/problem+json"
126 // @Router       /admin/log [put]
127 func (h *ProducerCallbackHandler) setLogLevel(w http.ResponseWriter, r *http.Request) {
128         query := r.URL.Query()
129         logLevelStr := query.Get(logLevelToken)
130         if loglevel, err := log.ParseLevel(logLevelStr); err == nil {
131                 log.SetLevel(loglevel)
132         } else {
133                 returnError(fmt.Sprintf("Invalid log level: %v. Log level will not be changed!", logLevelStr), w)
134                 return
135         }
136 }
137
138 type notFoundHandler struct{}
139
140 func (h *notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
141         http.Error(w, "404 not found.", http.StatusNotFound)
142 }
143
144 type methodNotAllowedHandler struct{}
145
146 func (h *methodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
147         http.Error(w, "Method is not supported.", http.StatusMethodNotAllowed)
148 }
149
150 func returnError(msg string, w http.ResponseWriter) {
151         errInfo := ErrorInfo{
152                 Status: http.StatusBadRequest,
153                 Detail: msg,
154         }
155         w.Header().Add("Content-Type", "application/problem+json")
156         w.WriteHeader(http.StatusBadRequest)
157         json.NewEncoder(w).Encode(errInfo)
158 }