2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
29 "github.com/gorilla/mux"
30 log "github.com/sirupsen/logrus"
31 "oransc.org/nonrtric/dmaapmediatorproducer/internal/jobs"
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"
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"`
54 type ProducerCallbackHandler struct {
55 jobsManager jobs.JobsManager
58 func NewProducerCallbackHandler(jm jobs.JobsManager) *ProducerCallbackHandler {
59 return &ProducerCallbackHandler{
64 func NewRouter(jm jobs.JobsManager, hcf func(http.ResponseWriter, *http.Request)) *mux.Router {
65 callbackHandler := NewProducerCallbackHandler(jm)
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 = ¬FoundHandler{}
72 r.MethodNotAllowedHandler = &methodNotAllowedHandler{}
76 // @Summary Add info job
77 // @Description Callback for ICS to add an info job
78 // @Tags Data producer (callbacks)
80 // @Param user body jobs.JobInfo true "Info job data"
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)
88 returnError(fmt.Sprintf("Unable to read body due to: %v", readErr), w)
91 jobInfo := jobs.JobInfo{}
92 if unmarshalErr := json.Unmarshal(b, &jobInfo); unmarshalErr != nil {
93 returnError(fmt.Sprintf("Invalid json body. Cause: %v", unmarshalErr), w)
96 if err := h.jobsManager.AddJobFromRESTCall(jobInfo); err != nil {
97 returnError(fmt.Sprintf("Invalid job info. Cause: %v", err), w)
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"
107 // @Router /info_job/{infoJobId} [delete]
108 func (h *ProducerCallbackHandler) deleteInfoJobHandler(w http.ResponseWriter, r *http.Request) {
110 id, ok := vars[jobIdToken]
112 http.Error(w, "Must provide infoJobId.", http.StatusBadRequest)
116 h.jobsManager.DeleteJobFromRESTCall(id)
119 // @Summary Set log level
120 // @Description Set the log level of the producer.
122 // @Param level query string false "string enums" Enums(Error, Warn, Info, Debug)
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)
133 returnError(fmt.Sprintf("Invalid log level: %v. Log level will not be changed!", logLevelStr), w)
138 type notFoundHandler struct{}
140 func (h *notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
141 http.Error(w, "404 not found.", http.StatusNotFound)
144 type methodNotAllowedHandler struct{}
146 func (h *methodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
147 http.Error(w, "Method is not supported.", http.StatusMethodNotAllowed)
150 func returnError(msg string, w http.ResponseWriter) {
151 errInfo := ErrorInfo{
152 Status: http.StatusBadRequest,
155 w.Header().Add("Content-Type", "application/problem+json")
156 w.WriteHeader(http.StatusBadRequest)
157 json.NewEncoder(w).Encode(errInfo)