/
restapi.go
405 lines (343 loc) · 13.8 KB
/
restapi.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package channelparticipation
import (
"encoding/json"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"path"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"github.com/gorilla/mux"
cb "github.com/hyperledger/fabric-protos-go/common"
"github.com/jxu86/fabric-gm/common/configtx"
"github.com/jxu86/fabric-gm/common/flogging"
"github.com/jxu86/fabric-gm/orderer/common/localconfig"
"github.com/jxu86/fabric-gm/orderer/common/types"
"github.com/pkg/errors"
)
const (
URLBaseV1 = "/participation/v1/"
URLBaseV1Channels = URLBaseV1 + "channels"
FormDataConfigBlockKey = "config-block"
RemoveStorageQueryKey = "removeStorage"
channelIDKey = "channelID"
urlWithChannelIDKey = URLBaseV1Channels + "/{" + channelIDKey + "}"
)
//go:generate counterfeiter -o mocks/channel_management.go -fake-name ChannelManagement . ChannelManagement
type ChannelManagement interface {
// ChannelList returns a slice of ChannelInfoShort containing all application channels (excluding the system
// channel), and ChannelInfoShort of the system channel (nil if does not exist).
// The URL fields are empty, and are to be completed by the caller.
ChannelList() types.ChannelList
// ChannelInfo provides extended status information about a channel.
// The URL field is empty, and is to be completed by the caller.
ChannelInfo(channelID string) (types.ChannelInfo, error)
// JoinChannel instructs the orderer to create a channel and join it with the provided config block.
JoinChannel(channelID string, configBlock *cb.Block, isAppChannel bool) (types.ChannelInfo, error)
// RemoveChannel instructs the orderer to remove a channel.
// Depending on the removeStorage parameter, the storage resources are either removed or archived.
RemoveChannel(channelID string, removeStorage bool) error
}
// HTTPHandler handles all the HTTP requests to the channel participation API.
type HTTPHandler struct {
logger *flogging.FabricLogger
config localconfig.ChannelParticipation
registrar ChannelManagement
router *mux.Router
// TODO skeleton
}
func NewHTTPHandler(config localconfig.ChannelParticipation, registrar ChannelManagement) *HTTPHandler {
handler := &HTTPHandler{
logger: flogging.MustGetLogger("orderer.commmon.channelparticipation"),
config: config,
registrar: registrar,
router: mux.NewRouter(),
}
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveListOne).Methods(http.MethodGet)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveJoin).Methods(http.MethodPost).HeadersRegexp(
"Content-Type", "multipart/form-data*")
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveBadContentType).Methods(http.MethodPost)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveRemove).Methods(http.MethodDelete)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveNotAllowed)
handler.router.HandleFunc(URLBaseV1Channels, handler.serveListAll).Methods(http.MethodGet)
handler.router.HandleFunc(URLBaseV1Channels, handler.serveNotAllowed)
handler.router.HandleFunc(URLBaseV1, handler.redirectBaseV1).Methods(http.MethodGet)
return handler
}
func (h *HTTPHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if !h.config.Enabled {
err := errors.New("channel participation API is disabled")
h.sendResponseJsonError(resp, http.StatusServiceUnavailable, err)
return
}
h.router.ServeHTTP(resp, req)
}
// List all channels
func (h *HTTPHandler) serveListAll(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelList := h.registrar.ChannelList()
if channelList.SystemChannel != nil && channelList.SystemChannel.Name != "" {
channelList.SystemChannel.URL = path.Join(URLBaseV1Channels, channelList.SystemChannel.Name)
}
for i, info := range channelList.Channels {
channelList.Channels[i].URL = path.Join(URLBaseV1Channels, info.Name)
}
resp.Header().Set("Cache-Control", "no-store")
h.sendResponseOK(resp, channelList)
}
// List a single channel
func (h *HTTPHandler) serveListOne(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
infoFull, err := h.registrar.ChannelInfo(channelID)
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotFound, err)
return
}
resp.Header().Set("Cache-Control", "no-store")
h.sendResponseOK(resp, infoFull)
}
func (h *HTTPHandler) redirectBaseV1(resp http.ResponseWriter, req *http.Request) {
http.Redirect(resp, req, URLBaseV1Channels, http.StatusFound)
}
// Join a channel.
// Expect multipart/form-data.
func (h *HTTPHandler) serveJoin(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
_, params, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot parse Mime media type"))
return
}
block := h.multipartFormDataBodyToBlock(params, req, resp)
if block == nil {
return
}
isAppChannel, err := ValidateJoinBlock(channelID, block)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "invalid join block"))
return
}
info, err := h.registrar.JoinChannel(channelID, block, isAppChannel)
if err == nil {
info.URL = path.Join(URLBaseV1Channels, info.Name)
h.logger.Debugf("Successfully joined channel: %s", info)
h.sendResponseCreated(resp, info.URL, info)
return
}
h.sendJoinError(err, resp)
}
// Expect a multipart/form-data with a single part, of type file, with key FormDataConfigBlockKey.
func (h *HTTPHandler) multipartFormDataBodyToBlock(params map[string]string, req *http.Request, resp http.ResponseWriter) *cb.Block {
boundary := params["boundary"]
reader := multipart.NewReader(req.Body, boundary)
form, err := reader.ReadForm(100 * 1024 * 1024)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot read form from request body"))
return nil
}
if _, exist := form.File[FormDataConfigBlockKey]; !exist {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Errorf("form does not contains part key: %s", FormDataConfigBlockKey))
return nil
}
if len(form.File) != 1 || len(form.Value) != 0 {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.New("form contains too many parts"))
return nil
}
fileHeader := form.File[FormDataConfigBlockKey][0]
file, err := fileHeader.Open()
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot open file part %s from request body", FormDataConfigBlockKey))
return nil
}
blockBytes, err := ioutil.ReadAll(file)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot read file part %s from request body", FormDataConfigBlockKey))
return nil
}
block := &cb.Block{}
err = proto.Unmarshal(blockBytes, block)
if err != nil {
h.logger.Debugf("Failed to unmarshal blockBytes: %s", err)
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot unmarshal file part %s into a block", FormDataConfigBlockKey))
return nil
}
return block
}
func (h *HTTPHandler) extractChannelID(req *http.Request, resp http.ResponseWriter) (string, error) {
channelID, ok := mux.Vars(req)[channelIDKey]
if !ok {
err := errors.New("missing channel ID")
h.sendResponseJsonError(resp, http.StatusInternalServerError, err)
return "", err
}
if err := configtx.ValidateChannelID(channelID); err != nil {
err = errors.Wrap(err, "invalid channel ID")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return "", err
}
return channelID, nil
}
func (h *HTTPHandler) sendJoinError(err error, resp http.ResponseWriter) {
h.logger.Debugf("Failed to JoinChannel: %s", err)
switch err {
case types.ErrSystemChannelExists:
// The client is trying to join an app-channel, but the system channel exists: only GET is allowed on app channels.
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot join"), http.MethodGet)
case types.ErrChannelAlreadyExists:
// The client is trying to join an app-channel that exists, but the system channel does not;
// The client is trying to join the system-channel, and it exists. GET & DELETE are allowed on the channel.
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot join"), http.MethodGet, http.MethodDelete)
case types.ErrAppChannelsAlreadyExists:
// The client is trying to join the system-channel that does not exist, but app channels exist.
h.sendResponseJsonError(resp, http.StatusForbidden, errors.Wrap(err, "cannot join"))
default:
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot join"))
}
}
// Remove a channel
// Expecting an optional query: "removeStorage=true" or "removeStorage=false".
func (h *HTTPHandler) serveRemove(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
removeStorage, err := h.extractRemoveStorageQuery(req, resp)
if err != nil {
return
}
err = h.registrar.RemoveChannel(channelID, removeStorage)
if err == nil {
h.logger.Debugf("Successfully removed channel: %s", channelID)
resp.WriteHeader(http.StatusNoContent)
return
}
h.logger.Debugf("Failed to remove channel: %s, err: %s", channelID, err)
switch err {
case types.ErrSystemChannelExists:
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot remove"), http.MethodGet)
case types.ErrChannelNotExist:
h.sendResponseJsonError(resp, http.StatusNotFound, errors.Wrap(err, "cannot remove"))
default:
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot remove"))
}
}
func (h *HTTPHandler) extractRemoveStorageQuery(req *http.Request, resp http.ResponseWriter) (bool, error) {
removeStorage := h.config.RemoveStorage
queryVal := req.URL.Query()
if len(queryVal) > 1 {
err := errors.New("cannot remove: too many query keys")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
if values, ok := queryVal[RemoveStorageQueryKey]; ok {
var err error
if len(values) != 1 {
err = errors.New("cannot remove: too many query parameters")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
removeStorage, err = strconv.ParseBool(values[0])
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot remove: invalid query parameter"))
return false, err
}
} else if len(queryVal) > 0 {
err := errors.New("cannot remove: invalid query key")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
return removeStorage, nil
}
func (h *HTTPHandler) serveBadContentType(resp http.ResponseWriter, req *http.Request) {
err := errors.Errorf("unsupported Content-Type: %s", req.Header.Values("Content-Type"))
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
}
func (h *HTTPHandler) serveNotAllowed(resp http.ResponseWriter, req *http.Request) {
err := errors.Errorf("invalid request method: %s", req.Method)
if _, ok := mux.Vars(req)[channelIDKey]; ok {
h.sendResponseNotAllowed(resp, err, http.MethodGet, http.MethodPost, http.MethodDelete)
return
}
h.sendResponseNotAllowed(resp, err, http.MethodGet)
}
func negotiateContentType(req *http.Request) (string, error) {
acceptReq := req.Header.Get("Accept")
if len(acceptReq) == 0 {
return "application/json", nil
}
options := strings.Split(acceptReq, ",")
for _, opt := range options {
if strings.Contains(opt, "application/json") ||
strings.Contains(opt, "application/*") ||
strings.Contains(opt, "*/*") {
return "application/json", nil
}
}
return "", errors.New("response Content-Type is application/json only")
}
func (h *HTTPHandler) sendResponseJsonError(resp http.ResponseWriter, code int, err error) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(code)
if err := encoder.Encode(&types.ErrorResponse{Error: err.Error()}); err != nil {
h.logger.Errorf("failed to encode error, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseOK(resp http.ResponseWriter, content interface{}) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusOK)
if err := encoder.Encode(content); err != nil {
h.logger.Errorf("failed to encode content, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseCreated(resp http.ResponseWriter, location string, content interface{}) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Location", location)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusCreated)
if err := encoder.Encode(content); err != nil {
h.logger.Errorf("failed to encode content, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseNotAllowed(resp http.ResponseWriter, err error, allow ...string) {
encoder := json.NewEncoder(resp)
allowVal := strings.Join(allow, ", ")
resp.Header().Set("Allow", allowVal)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusMethodNotAllowed)
if err := encoder.Encode(&types.ErrorResponse{Error: err.Error()}); err != nil {
h.logger.Errorf("failed to encode error, err: %s", err)
}
}