-
-
Notifications
You must be signed in to change notification settings - Fork 402
/
server.go
262 lines (224 loc) · 7.03 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
* Copyright (C) 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy ofthe License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specificlanguage governing permissions and
* limitations under the License.
*
*/
package server
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
auth "github.com/abbot/go-http-auth"
etcd "github.com/coreos/etcd/client"
"github.com/skydive-project/skydive/common"
shttp "github.com/skydive-project/skydive/http"
"github.com/skydive-project/skydive/logging"
"github.com/skydive-project/skydive/rbac"
"github.com/skydive-project/skydive/validator"
"github.com/skydive-project/skydive/version"
)
// Server object are created once for each ServiceType (agent or analyzer)
type Server struct {
HTTPServer *shttp.Server
EtcdKeyAPI etcd.KeysAPI
handlers map[string]Handler
}
// Info for each host describes his API version and service (agent or analyzer)
type Info struct {
Host string
Version string
Service string
}
// HandlerFunc describes an http(s) router handler callback function
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
func writeError(w http.ResponseWriter, status int, err error) {
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
w.WriteHeader(status)
w.Write([]byte(err.Error()))
}
// RegisterAPIHandler registers a new handler for an API
func (a *Server) RegisterAPIHandler(handler Handler, authBackend shttp.AuthenticationBackend) error {
name := handler.Name()
title := strings.Title(name)
routes := []shttp.Route{
{
Name: title + "Index",
Method: "GET",
Path: "/api/" + name,
HandlerFunc: func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
if !rbac.Enforce(r.Username, name, "read") {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
resources := handler.Index()
for _, resource := range resources {
handler.Decorate(resource)
}
if err := json.NewEncoder(w).Encode(resources); err != nil {
logging.GetLogger().Criticalf("Failed to display %s: %s", name, err)
}
},
},
{
Name: title + "Show",
Method: "GET",
Path: shttp.PathPrefix(fmt.Sprintf("/api/%s/", name)),
HandlerFunc: func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
if !rbac.Enforce(r.Username, name, "read") {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
id := r.URL.Path[len(fmt.Sprintf("/api/%s/", name)):]
if id == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
resource, ok := handler.Get(id)
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
handler.Decorate(resource)
if err := json.NewEncoder(w).Encode(resource); err != nil {
logging.GetLogger().Criticalf("Failed to display %s: %s", name, err)
}
},
},
{
Name: title + "Insert",
Method: "POST",
Path: "/api/" + name,
HandlerFunc: func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
if !rbac.Enforce(r.Username, name, "write") {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
resource := handler.New()
var err error
if contentType := r.Header.Get("Content-Type"); contentType == "application/yaml" {
if content, e := ioutil.ReadAll(r.Body); e == nil {
err = yaml.Unmarshal(content, resource)
} else {
writeError(w, http.StatusBadRequest, err)
return
}
} else {
err = common.JSONDecode(r.Body, &resource)
}
if err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
if err := validator.Validate(resource); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
var createOpts CreateOptions
if ttlHeader := r.Header.Get("X-Resource-TTL"); ttlHeader != "" {
if createOpts.TTL, err = time.ParseDuration(ttlHeader); err != nil {
writeError(w, http.StatusBadRequest, fmt.Errorf("invalid ttl: %s", err))
return
}
}
if err := handler.Create(resource, &createOpts); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
data, err := json.Marshal(&resource)
if err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if _, err := w.Write(data); err != nil {
logging.GetLogger().Criticalf("Failed to create %s: %s", name, err)
}
},
},
{
Name: title + "Delete",
Method: "DELETE",
Path: shttp.PathPrefix(fmt.Sprintf("/api/%s/", name)),
HandlerFunc: func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
if !rbac.Enforce(r.Username, name, "write") {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
id := r.URL.Path[len(fmt.Sprintf("/api/%s/", name)):]
if id == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := handler.Delete(id); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
w.WriteHeader(http.StatusOK)
},
},
}
a.HTTPServer.RegisterRoutes(routes, authBackend)
if _, err := a.EtcdKeyAPI.Set(context.Background(), "/"+name, "", &etcd.SetOptions{Dir: true}); err != nil {
if _, err = a.EtcdKeyAPI.Get(context.Background(), "/"+name, nil); err != nil {
return err
}
}
a.handlers[handler.Name()] = handler
return nil
}
func (a *Server) addAPIRootRoute(service common.Service, authBackend shttp.AuthenticationBackend) {
info := Info{
Version: version.Version,
Service: string(service.Type),
Host: service.ID,
}
routes := []shttp.Route{
{
Name: "Skydive API",
Method: "GET",
Path: "/api",
HandlerFunc: func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(&info); err != nil {
logging.GetLogger().Criticalf("Failed to display /api: %s", err)
}
},
}}
a.HTTPServer.RegisterRoutes(routes, authBackend)
}
// GetHandler returns the hander named hname
func (a *Server) GetHandler(hname string) Handler {
return a.handlers[hname]
}
// NewAPI creates a new API server based on http
func NewAPI(server *shttp.Server, kapi etcd.KeysAPI, service common.Service, authBackend shttp.AuthenticationBackend) (*Server, error) {
apiServer := &Server{
HTTPServer: server,
EtcdKeyAPI: kapi,
handlers: make(map[string]Handler),
}
apiServer.addAPIRootRoute(service, authBackend)
return apiServer, nil
}