Initial version
[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         "net/http"
26 )
27
28 const (
29         ReadyURL = "/ric/v1/health/ready"
30         AliveURL = "/ric/v1/health/alive"
31 )
32
33 type StatusCb func() bool
34
35 type Router struct {
36         router *mux.Router
37         cbMap  []StatusCb
38 }
39
40 func NewRouter() *Router {
41         r := &Router{
42                 router: mux.NewRouter().StrictSlash(true),
43                 cbMap:  make([]StatusCb, 0),
44         }
45
46         // Inject default routes for health probes
47         r.InjectRoute(ReadyURL, readyHandler, "GET")
48         r.InjectRoute(AliveURL, aliveHandler, "GET")
49
50         return r
51 }
52
53 func (r *Router) serviceChecker(inner http.HandlerFunc) http.HandlerFunc {
54         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
55                 Logger.Info("restapi: method=%s url=%s", req.Method, req.URL.RequestURI())
56                 if req.URL.RequestURI() == AliveURL || (Rmr.IsReady() && r.CheckStatus()) {
57                         inner.ServeHTTP(w, req)
58                 } else {
59                         respondWithJSON(w, http.StatusServiceUnavailable, nil)
60                 }
61         })
62 }
63
64 func (r *Router) InjectRoute(url string, handler http.HandlerFunc, method string) *mux.Route {
65         return r.router.HandleFunc(url, r.serviceChecker(handler)).Methods(method)
66 }
67
68 func (r *Router) InjectQueryRoute(url string, h http.HandlerFunc, m string, q ...string) *mux.Route {
69         return r.router.HandleFunc(url, r.serviceChecker(h)).Methods(m).Queries(q...)
70 }
71
72 func (r *Router) InjectStatusCb(f StatusCb) {
73         r.cbMap = append(r.cbMap, f)
74 }
75
76 func (r *Router) CheckStatus() (status bool) {
77         if len(r.cbMap) == 0 {
78                 return true
79         }
80
81         for _, f := range r.cbMap {
82                 status = f()
83         }
84         return
85 }
86
87 func readyHandler(w http.ResponseWriter, r *http.Request) {
88         respondWithJSON(w, http.StatusOK, nil)
89 }
90
91 func aliveHandler(w http.ResponseWriter, r *http.Request) {
92         respondWithJSON(w, http.StatusOK, nil)
93 }
94
95 func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
96         w.Header().Set("Content-Type", "application/json")
97         w.WriteHeader(code)
98         if payload != nil {
99                 response, _ := json.Marshal(payload)
100                 w.Write(response)
101         }
102 }