This repository has been archived by the owner on Jan 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
300 lines (262 loc) · 8.97 KB
/
api.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
package api
import (
"flag"
"fmt"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/aws/aws-sdk-go/service/s3/s3manager/s3manageriface"
"github.com/gorilla/context"
gzip "github.com/lidashuang/goji-gzip"
"github.com/patrickmn/go-cache"
"github.com/twitchscience/aws_utils/logger"
"github.com/twitchscience/blueprint/auth"
"github.com/twitchscience/blueprint/bpdb"
"github.com/twitchscience/blueprint/core"
"github.com/twitchscience/blueprint/ingester"
"github.com/zenazn/goji"
"github.com/zenazn/goji/graceful"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
)
const (
allSchemasCache = "allSchemas"
allMetadataCache = "allMetadata"
)
type server struct {
docRoot string
bpdbBackend bpdb.Bpdb
bpSchemaBackend bpdb.BpSchemaBackend
bpKinesisConfigBackend bpdb.BpKinesisConfigBackend
ingesterController ingester.Controller
slackbotURL string
goCache *cache.Cache
cacheTimeout time.Duration
blacklistRe []*regexp.Regexp
readonly bool
s3Uploader s3manageriface.UploaderAPI
s3BpConfigsBucketName string
s3BpConfigsPrefix string
}
var (
loginURL = "/login"
logoutURL = "/logout"
authCallbackURL = "/github_oauth_cb"
slackbotDeletePath = "/request-table-delete"
enableAuth bool
cookieSecret string
clientID string
clientSecret string
githubServer string
requiredOrg string
adminTeam string
)
func init() {
flag.BoolVar(&enableAuth, "enableAuth", true, "enable authentication when not in readonly mode")
flag.StringVar(&cookieSecret, "cookieSecret", "", "32 character secret for signing cookies")
flag.StringVar(&clientID, "clientID", "", "Google API client id")
flag.StringVar(&clientSecret, "clientSecret", "", "Google API client secret")
flag.StringVar(&githubServer, "githubServer", "http://github.com", "Github server to use for auth")
flag.StringVar(&requiredOrg, "requiredOrg", "", "Org user need to belong to to use auth")
flag.StringVar(&adminTeam, "adminTeam", "", "Team with admin privileges")
}
// New returns an API process.
func New(
docRoot string,
bpdbBackend bpdb.Bpdb,
bpSchemaBackend bpdb.BpSchemaBackend,
bpKinesisConfigBackend bpdb.BpKinesisConfigBackend,
conf *Config,
ingCont ingester.Controller,
slackbotURL string,
readonly bool,
s3Uploader s3manageriface.UploaderAPI) core.Subprocess {
s := &server{
docRoot: docRoot,
bpdbBackend: bpdbBackend,
bpSchemaBackend: bpSchemaBackend,
bpKinesisConfigBackend: bpKinesisConfigBackend,
ingesterController: ingCont,
slackbotURL: slackbotURL,
goCache: cache.New(5*time.Minute, 10*time.Minute),
readonly: readonly,
s3Uploader: s3Uploader,
}
if err := s.loadConfig(conf); err != nil {
logger.WithError(err).Fatal("failed to load config")
}
return s
}
// NewS3Uploader returns a new S3 uploader
func NewS3Uploader() *s3manager.Uploader {
s := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
}))
return s3manager.NewUploader(s)
}
// MockS3UploaderAPI is a wrapper for the S3 manager UploaderAPI
type MockS3UploaderAPI struct {
uploadSuccessful bool
s3manageriface.UploaderAPI
}
// NewMockS3Uploader returns a new mock S3 uploader
func NewMockS3Uploader() *MockS3UploaderAPI {
return &MockS3UploaderAPI{}
}
// Upload is a mock of S3Manager's Upload function
func (s *MockS3UploaderAPI) Upload(input *s3manager.UploadInput, f ...func(*s3manager.Uploader)) (*s3manager.UploadOutput, error) {
k := *input.Key
if !strings.HasSuffix(k, schemaConfigS3Key) &&
!strings.HasSuffix(k, kinesisConfigS3Key) &&
!strings.HasSuffix(k, eventMetadataConfigS3Key) {
return nil, fmt.Errorf("Invalid S3 config key %s", k)
}
s.uploadSuccessful = true
return &s3manager.UploadOutput{}, nil
}
// UploadSucceeded returns whether a mock upload was successful
func (s *MockS3UploaderAPI) UploadSucceeded() bool {
return s.uploadSuccessful
}
// ResetUploadSuccess sets uploadSuccessful to false
func (s *MockS3UploaderAPI) ResetUploadSuccess() {
s.uploadSuccessful = false
}
// Create a simple health check API which needs no special setup.
func (s *server) setupHealthcheckAPI() {
healthcheckAPI := web.New()
healthcheckAPI.Get("/health", s.healthCheck)
goji.Get("/health", healthcheckAPI)
}
// Create the read-only API, available to all users.
func (s *server) setupReadonlyAPI() {
roAPI := web.New()
roAPI.Use(jsonResponse)
roAPI.Use(gzip.GzipHandler)
roAPI.Get("/schemas", s.allSchemas)
roAPI.Get("/schema/:id", s.schema)
roAPI.Get("/droppable/schema/:id", s.droppableSchema)
roAPI.Get("/maintenance", s.getMaintenanceMode)
roAPI.Get("/maintenance/:schema", s.getMaintenanceMode)
roAPI.Get("/migration/:schema", s.migration)
roAPI.Get("/types", s.types)
roAPI.Get("/suggestions", s.listSuggestions)
roAPI.Get("/suggestion/:id", s.suggestion)
roAPI.Get("/stats", s.stats)
roAPI.Get("/allmetadata", s.allEventMetadata)
roAPI.Get("/metadata/:event", s.eventMetadata)
goji.Get("/schemas", roAPI)
goji.Get("/schema/*", roAPI)
goji.Get("/droppable/schema/*", roAPI)
goji.Get("/maintenance", roAPI)
goji.Get("/maintenance/*", roAPI)
goji.Get("/migration/*", roAPI)
goji.Get("/types", roAPI)
goji.Get("/suggestions", roAPI)
goji.Get("/suggestion/*", roAPI)
goji.Get("/stats", roAPI)
goji.Get("/allmetadata", roAPI)
goji.Get("/metadata/*", roAPI)
roAPI.Get("/kinesisconfigs", s.allKinesisConfigs)
roAPI.Get("/kinesisconfig/:account/:type/:name", s.kinesisconfig)
goji.Get("/kinesisconfigs", roAPI)
goji.Get("/kinesisconfig/*", roAPI)
}
// Create the write API available only to authenticated users, which includes creating and
// adding rows to schemata, requesting deletion, and starting force loads. Because it
// involves changes to the Blueprint DB, all of it is locked down during maintenance mode.
func (s *server) authWriteAPI() *web.Mux {
authWriteAPI := web.New()
authWriteAPI.Use(context.ClearHandler)
authWriteAPI.Use(s.maintenanceHandler)
authWriteAPI.Post("/force_load", s.forceLoad)
authWriteAPI.Put("/schema", s.createSchema)
authWriteAPI.Post("/schema/:id", s.updateSchema)
authWriteAPI.Post("/drop/schema", s.dropSchema)
authWriteAPI.Post("/removesuggestion/:id", s.removeSuggestion)
authWriteAPI.Post("/metadata/:event", s.updateEventMetadata)
goji.Post("/force_load", authWriteAPI)
goji.Put("/schema", authWriteAPI)
goji.Post("/schema/*", authWriteAPI)
goji.Post("/drop/schema", authWriteAPI)
goji.Post("/removesuggestion/*", authWriteAPI)
goji.Post("/metadata/*", authWriteAPI)
return authWriteAPI
}
// Create the write API available only to admins. Currently limited to toggling maintenance
// modes and modifying Kinesis configs.
func (s *server) authAdminAPI() *web.Mux {
adminAPI := web.New()
adminAPI.Use(context.ClearHandler)
adminAPI.Post("/maintenance", s.setMaintenanceMode)
adminAPI.Post("/maintenance/:schema", s.setMaintenanceMode)
goji.Post("/maintenance", adminAPI)
goji.Post("/maintenance/*", adminAPI)
adminAPI.Put("/kinesisconfig", s.createKinesisConfig)
adminAPI.Post("/kinesisconfig/:account/:type/:name", s.updateKinesisConfig)
adminAPI.Post("/drop/kinesisconfig", s.dropKinesisConfig)
goji.Put("/kinesisconfig", adminAPI)
goji.Post("/kinesisconfig/*", adminAPI)
goji.Post("/drop/kinesisconfig", adminAPI)
return adminAPI
}
// Set up the authenticated portion of the API.
func (s *server) setupAuthAPI() {
authWriteAPI := s.authWriteAPI()
adminAPI := s.authAdminAPI()
files := web.New()
files.Use(context.ClearHandler)
if enableAuth {
a := auth.New(githubServer,
clientID,
clientSecret,
cookieSecret,
requiredOrg,
adminTeam,
loginURL)
authWriteAPI.Use(a.AuthorizeOrForbid)
adminAPI.Use(a.AuthorizeOrForbidAdmin)
goji.Handle(loginURL, a.LoginHandler)
goji.Handle(logoutURL, a.LogoutHandler)
goji.Handle(authCallbackURL, a.AuthCallbackHandler)
files.Use(a.ExpireDisplayName)
} else {
authWriteAPI.Use(auth.DummyAuth)
adminAPI.Use(auth.DummyAuth)
goji.Handle(loginURL, auth.DummyLoginHandler)
goji.Handle(logoutURL, auth.DummyLogoutHandler)
}
goji.Handle("/*", files)
files.Get("/*", s.fileHandler)
}
// Setup route handlers.
func (s *server) Setup() error {
s.setupHealthcheckAPI()
s.setupReadonlyAPI()
if !s.readonly {
s.setupAuthAPI()
}
goji.NotFound(fourOhFour)
// The default logger logs in colour which makes CloudWatch hard to read.
// Replace with a custom logger that does not use colour.
err := goji.DefaultMux.Abandon(middleware.Logger)
if err != nil {
logger.WithError(err).Warn("Couldn't abandon default logger; will continue as is")
} else {
goji.DefaultMux.Use(SimpleLogger)
}
// Stop() provides our shutdown semantics
graceful.ResetSignals()
return nil
}
// Start the API server.
func (s *server) Start() {
goji.Serve()
}
// Stop the API server.
func (s *server) Stop() {
graceful.Shutdown()
}