6562dc579e19191ac1dd8148546c583b2c9287d4
[ric-plt/xapp-frame.git] / pkg / xapp / restapi.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package xapp
21
22 import (
23         "encoding/json"
24         "github.com/gorilla/mux"
25         "io/ioutil"
26         "net/http"
27 )
28
29 const (
30         ReadyURL  = "/ric/v1/health/ready"
31         AliveURL  = "/ric/v1/health/alive"
32         ConfigURL = "/ric/v1/cm/{name}"
33 )
34
35 type StatusCb func() bool
36
37 type Router struct {
38         router *mux.Router
39         cbMap  []StatusCb
40 }
41
42 func NewRouter() *Router {
43         r := &Router{
44                 router: mux.NewRouter().StrictSlash(true),
45                 cbMap:  make([]StatusCb, 0),
46         }
47
48         // Inject default routes for health probes
49         r.InjectRoute(ReadyURL, readyHandler, "GET")
50         r.InjectRoute(AliveURL, aliveHandler, "GET")
51         r.InjectRoute(ConfigURL, configHandler, "POST")
52
53         return r
54 }
55
56 func (r *Router) serviceChecker(inner http.HandlerFunc) http.HandlerFunc {
57         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
58                 Logger.Info("restapi: method=%s url=%s", req.Method, req.URL.RequestURI())
59                 if req.URL.RequestURI() == AliveURL || r.CheckStatus() {
60                         inner.ServeHTTP(w, req)
61                 } else {
62                         respondWithJSON(w, http.StatusServiceUnavailable, nil)
63                 }
64         })
65 }
66
67 func (r *Router) InjectRoute(url string, handler http.HandlerFunc, method string) *mux.Route {
68         return r.router.Path(url).HandlerFunc(r.serviceChecker(handler)).Methods(method)
69 }
70
71 func (r *Router) InjectQueryRoute(url string, h http.HandlerFunc, m string, q ...string) *mux.Route {
72         return r.router.Path(url).HandlerFunc(r.serviceChecker(h)).Methods(m).Queries(q...)
73 }
74
75 func (r *Router) InjectRoutePrefix(prefix string, handler http.HandlerFunc) *mux.Route {
76         return r.router.PathPrefix(prefix).HandlerFunc(r.serviceChecker(handler))
77 }
78
79 func (r *Router) InjectStatusCb(f StatusCb) {
80         r.cbMap = append(r.cbMap, f)
81 }
82
83 func (r *Router) CheckStatus() (status bool) {
84         if len(r.cbMap) == 0 {
85                 return true
86         }
87
88         for _, f := range r.cbMap {
89                 status = f()
90         }
91         return
92 }
93
94 func readyHandler(w http.ResponseWriter, r *http.Request) {
95         respondWithJSON(w, http.StatusOK, nil)
96 }
97
98 func aliveHandler(w http.ResponseWriter, r *http.Request) {
99         respondWithJSON(w, http.StatusOK, nil)
100 }
101
102 func configHandler(w http.ResponseWriter, r *http.Request) {
103         xappName := mux.Vars(r)["name"]
104         if xappName == "" || r.Body == nil {
105                 respondWithJSON(w, http.StatusBadRequest, nil)
106                 return
107         }
108         defer r.Body.Close()
109
110         body, err := ioutil.ReadAll(r.Body)
111         if err != nil {
112                 Logger.Error("ioutil.ReadAll failed: %v", err)
113                 respondWithJSON(w, http.StatusInternalServerError, nil)
114                 return
115         }
116
117         if err := PublishConfigChange(xappName, string(body)); err != nil {
118                 respondWithJSON(w, http.StatusInternalServerError, nil)
119                 return
120         }
121
122         respondWithJSON(w, http.StatusOK, nil)
123 }
124
125 func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
126         w.Header().Set("Content-Type", "application/json")
127         w.WriteHeader(code)
128         if payload != nil {
129                 response, _ := json.Marshal(payload)
130                 w.Write(response)
131         }
132 }