Update documentation for DMaaP Mediator Producer
[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 ProducerCallbackHandler struct {
42         jobsManager jobs.JobsManager
43 }
44
45 func NewProducerCallbackHandler(jm jobs.JobsManager) *ProducerCallbackHandler {
46         return &ProducerCallbackHandler{
47                 jobsManager: jm,
48         }
49 }
50
51 func NewRouter(jm jobs.JobsManager, hcf func(http.ResponseWriter, *http.Request)) *mux.Router {
52         callbackHandler := NewProducerCallbackHandler(jm)
53         r := mux.NewRouter()
54         r.HandleFunc(HealthCheckPath, hcf).Methods(http.MethodGet).Name("health_check")
55         r.HandleFunc(AddJobPath, callbackHandler.addInfoJobHandler).Methods(http.MethodPost).Name("add")
56         r.HandleFunc(deleteJobPath, callbackHandler.deleteInfoJobHandler).Methods(http.MethodDelete).Name("delete")
57         r.HandleFunc(logAdminPath, callbackHandler.setLogLevel).Methods(http.MethodPut).Name("setLogLevel")
58         r.NotFoundHandler = &notFoundHandler{}
59         r.MethodNotAllowedHandler = &methodNotAllowedHandler{}
60         return r
61 }
62
63 // @Summary      Add info job
64 // @Description  Callback for ICS to add an info job
65 // @Tags         Data producer (callbacks)
66 // @Accept       json
67 // @Param        user  body  jobs.JobInfo  true  "Info job data"
68 // @Success      200
69 // @Failure      400  {string}  Cause  of  error
70 // @Router       /info_job [post]
71 func (h *ProducerCallbackHandler) addInfoJobHandler(w http.ResponseWriter, r *http.Request) {
72         b, readErr := ioutil.ReadAll(r.Body)
73         if readErr != nil {
74                 http.Error(w, fmt.Sprintf("Unable to read body due to: %v", readErr), http.StatusBadRequest)
75                 return
76         }
77         jobInfo := jobs.JobInfo{}
78         if unmarshalErr := json.Unmarshal(b, &jobInfo); unmarshalErr != nil {
79                 http.Error(w, fmt.Sprintf("Invalid json body. Cause: %v", unmarshalErr), http.StatusBadRequest)
80                 return
81         }
82         if err := h.jobsManager.AddJobFromRESTCall(jobInfo); err != nil {
83                 http.Error(w, fmt.Sprintf("Invalid job info. Cause: %v", err), http.StatusBadRequest)
84         }
85 }
86
87 // @Summary      Delete info job
88 // @Description  Callback for ICS to delete an info job
89 // @Tags         Data producer (callbacks)
90 // @Param        infoJobId  path  string  true  "Info job ID"
91 // @Success      200
92 // @Router       /info_job/{infoJobId} [delete]
93 func (h *ProducerCallbackHandler) deleteInfoJobHandler(w http.ResponseWriter, r *http.Request) {
94         vars := mux.Vars(r)
95         id, ok := vars[jobIdToken]
96         if !ok {
97                 http.Error(w, "Must provide infoJobId.", http.StatusBadRequest)
98                 return
99         }
100
101         h.jobsManager.DeleteJobFromRESTCall(id)
102 }
103
104 // @Summary      Set log level
105 // @Description  Set the log level of the producer.
106 // @Tags         Admin
107 // @Param        level  query  string  false  "string enums"  Enums(Error, Warn, Info, Debug)
108 // @Success      200
109 // @Failure      400  {string}  Cause  of  error
110 // @Router       /admin/log [put]
111 func (h *ProducerCallbackHandler) setLogLevel(w http.ResponseWriter, r *http.Request) {
112         query := r.URL.Query()
113         logLevelStr := query.Get(logLevelToken)
114         if loglevel, err := log.ParseLevel(logLevelStr); err == nil {
115                 log.SetLevel(loglevel)
116         } else {
117                 http.Error(w, fmt.Sprintf("Invalid log level: %v. Log level will not be changed!", logLevelStr), http.StatusBadRequest)
118                 return
119         }
120 }
121
122 type notFoundHandler struct{}
123
124 func (h *notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
125         http.Error(w, "404 not found.", http.StatusNotFound)
126 }
127
128 type methodNotAllowedHandler struct{}
129
130 func (h *methodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
131         http.Error(w, "Method is not supported.", http.StatusMethodNotAllowed)
132 }