chronograf/server/mux.go

265 lines
9.8 KiB
Go
Raw Normal View History

2016-10-25 15:20:06 +00:00
package server
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/NYTimes/gziphandler"
2016-10-25 15:20:06 +00:00
"github.com/bouk/httprouter"
2016-11-19 17:41:06 +00:00
"github.com/influxdata/chronograf" // When julienschmidt/httprouter v2 w/ context is out, switch
"github.com/influxdata/chronograf/oauth2"
2016-10-25 15:20:06 +00:00
)
const (
// JSONType the mimetype for a json request
JSONType = "application/json"
)
// MuxOpts are the options for the router. Mostly related to auth.
2016-10-25 15:20:06 +00:00
type MuxOpts struct {
Logger chronograf.Logger
Develop bool // Develop loads assets from filesystem instead of bindata
Basepath string // URL path prefix under which all chronograf routes will be mounted
UseAuth bool // UseAuth turns on Github OAuth and JWT
Auth oauth2.Authenticator // Auth is used to authenticate and authorize
ProviderFuncs []func(func(oauth2.Provider, oauth2.Mux))
2016-10-25 15:20:06 +00:00
}
// NewMux attaches all the route handlers; handler returned servers chronograf.
func NewMux(opts MuxOpts, service Service) http.Handler {
2016-10-25 15:20:06 +00:00
router := httprouter.New()
/* React Application */
assets := Assets(AssetsOpts{
Develop: opts.Develop,
Logger: opts.Logger,
})
// Prefix any URLs found in the React assets with any configured basepath
prefixedAssets := NewDefaultURLPrefixer(basepath, assets, opts.Logger)
// Compress the assets with gzip if an accepted encoding
compressed := gziphandler.GzipHandler(prefixedAssets)
2016-10-25 15:20:06 +00:00
// The react application handles all the routing if the server does not
// know about the route. This means that we never have unknown
// routes on the server.
router.NotFound = compressed
2016-10-25 15:20:06 +00:00
/* Documentation */
router.GET("/swagger.json", Spec())
router.GET("/docs", Redoc("/swagger.json"))
2016-10-25 15:20:06 +00:00
/* API */
// Sources
router.GET("/chronograf/v1/sources", service.Sources)
router.POST("/chronograf/v1/sources", service.NewSource)
2016-10-25 15:20:06 +00:00
router.GET("/chronograf/v1/sources/:id", service.SourcesID)
router.PATCH("/chronograf/v1/sources/:id", service.UpdateSource)
router.DELETE("/chronograf/v1/sources/:id", service.RemoveSource)
2016-10-25 15:20:06 +00:00
// Source Proxy to Influx; Has gzip compression around the handler
influx := gziphandler.GzipHandler(http.HandlerFunc(service.Influx))
router.Handler("POST", "/chronograf/v1/sources/:id/proxy", influx)
2016-10-25 15:20:06 +00:00
// All possible permissions for users in this source
router.GET("/chronograf/v1/sources/:id/permissions", service.Permissions)
2017-02-18 02:47:23 +00:00
// Users associated with the data source
router.GET("/chronograf/v1/sources/:id/users", service.SourceUsers)
router.POST("/chronograf/v1/sources/:id/users", service.NewSourceUser)
router.GET("/chronograf/v1/sources/:id/users/:uid", service.SourceUserID)
router.DELETE("/chronograf/v1/sources/:id/users/:uid", service.RemoveSourceUser)
router.PATCH("/chronograf/v1/sources/:id/users/:uid", service.UpdateSourceUser)
// Roles associated with the data source
router.GET("/chronograf/v1/sources/:id/roles", service.Roles)
router.POST("/chronograf/v1/sources/:id/roles", service.NewRole)
router.GET("/chronograf/v1/sources/:id/roles/:rid", service.RoleID)
router.DELETE("/chronograf/v1/sources/:id/roles/:rid", service.RemoveRole)
router.PATCH("/chronograf/v1/sources/:id/roles/:rid", service.UpdateRole)
2016-10-25 15:20:06 +00:00
// Kapacitor
router.GET("/chronograf/v1/sources/:id/kapacitors", service.Kapacitors)
router.POST("/chronograf/v1/sources/:id/kapacitors", service.NewKapacitor)
2016-10-25 15:20:06 +00:00
router.GET("/chronograf/v1/sources/:id/kapacitors/:kid", service.KapacitorsID)
router.PATCH("/chronograf/v1/sources/:id/kapacitors/:kid", service.UpdateKapacitor)
router.DELETE("/chronograf/v1/sources/:id/kapacitors/:kid", service.RemoveKapacitor)
2016-10-25 15:20:06 +00:00
2016-11-04 06:53:54 +00:00
// Kapacitor rules
router.GET("/chronograf/v1/sources/:id/kapacitors/:kid/rules", service.KapacitorRulesGet)
router.POST("/chronograf/v1/sources/:id/kapacitors/:kid/rules", service.KapacitorRulesPost)
2016-11-04 06:53:54 +00:00
router.GET("/chronograf/v1/sources/:id/kapacitors/:kid/rules/:tid", service.KapacitorRulesID)
router.PUT("/chronograf/v1/sources/:id/kapacitors/:kid/rules/:tid", service.KapacitorRulesPut)
router.PATCH("/chronograf/v1/sources/:id/kapacitors/:kid/rules/:tid", service.KapacitorRulesStatus)
2016-11-04 06:53:54 +00:00
router.DELETE("/chronograf/v1/sources/:id/kapacitors/:kid/rules/:tid", service.KapacitorRulesDelete)
2016-10-25 15:20:06 +00:00
// Kapacitor Proxy
router.GET("/chronograf/v1/sources/:id/kapacitors/:kid/proxy", service.KapacitorProxyGet)
router.POST("/chronograf/v1/sources/:id/kapacitors/:kid/proxy", service.KapacitorProxyPost)
router.PATCH("/chronograf/v1/sources/:id/kapacitors/:kid/proxy", service.KapacitorProxyPatch)
router.DELETE("/chronograf/v1/sources/:id/kapacitors/:kid/proxy", service.KapacitorProxyDelete)
2016-10-25 15:20:06 +00:00
// Mappings
router.GET("/chronograf/v1/mappings", service.GetMappings)
2016-10-25 15:20:06 +00:00
// Layouts
router.GET("/chronograf/v1/layouts", service.Layouts)
router.POST("/chronograf/v1/layouts", service.NewLayout)
2016-10-25 15:20:06 +00:00
router.GET("/chronograf/v1/layouts/:id", service.LayoutsID)
router.PUT("/chronograf/v1/layouts/:id", service.UpdateLayout)
router.DELETE("/chronograf/v1/layouts/:id", service.RemoveLayout)
2016-10-25 15:20:06 +00:00
// Users
router.GET("/chronograf/v1/me", service.Me)
// Dashboards
router.GET("/chronograf/v1/dashboards", service.Dashboards)
router.POST("/chronograf/v1/dashboards", service.NewDashboard)
router.GET("/chronograf/v1/dashboards/:id", service.DashboardID)
2017-01-27 12:59:13 +00:00
router.DELETE("/chronograf/v1/dashboards/:id", service.RemoveDashboard)
router.PUT("/chronograf/v1/dashboards/:id", service.ReplaceDashboard)
router.PATCH("/chronograf/v1/dashboards/:id", service.UpdateDashboard)
Introduce ability to edit a dashboard cell * Correct documentation for dashboards * Exclude .git and use 'make run-dev' in 'make continuous' * Fix dashboard deletion bug where id serialization was wrong * Commence creation of overlay technology, add autoRefresh props to DashboardPage * Enhance overlay magnitude of overlay technology * Add confirm buttons to overlay technology * Refactor ResizeContainer to accommodate arbitrary containers * Refactor ResizeContainer to require explicit ResizeTop and ResizeBottom for clarity * Add markup and styles for OverlayControls * CellEditorOverlay needs a larger minimum bottom height to accommodate more things * Revert Visualization to not use ResizeTop or flex-box * Remove TODO and move to issue * Refactor CellEditorOverlay to allow selection of graph type * Style Overlay controls, move confirm buttons to own stylesheet * Fix toggle buttons in overlay so active is actually active * Block user-select on a few UI items * Update cell query shape to support Visualization and LayoutRenderer * Code cleanup * Repair fixture schema; update props for affected components * Wired up selectedGraphType and activeQueryID in CellEditorOverlay * Wire up chooseMeasurements in QueryBuilder Pass queryActions into QueryBuilder so that DataExplorer can provide actionCreators and CellEditorOverlay can provide functions that modify its component state * semicolon cleanup * Bind all queryModifier actions to component state with a stateReducer * Overlay Technologies™ can add and delete a query from a cell * Semicolon cleanup * Add conversion of InfluxQL to QueryConfig for dashboards * Update go deps to add influxdb at af72d9b0e4ebe95be30e89b160f43eabaf0529ed * Updated docs for dashboard query config * Update CHANGELOG to mention InfluxQL to QueryConfig * Make reducer’s name more specific for clarity * Remove 'table' as graphType * Make graph renaming prettier * Remove duplicate DashboardQuery in swagger.json * Fix swagger to include name and links for Cell * Refactor CellEditorOverlay to enable graph type selection * Add link.self to all Dashboard cells; add bolt migrations * Make dash graph names only hover on contents * Consolidate timeRange format patterns, clean up * Add cell endpoints to dashboards * Include Line + Stat in Visualization Type list * Add cell link to dashboards * Enable step plot and stacked graph in Visualization * Overlay Technologies are summonable and dismissable * OverlayTechnologies saves changes to a cell * Convert NameableGraph to createClass for state This was converted from a pure function to encapsulate the state of the buttons. An attempt was made previously to store this state in Redux, but it proved too convoluted with the current state of the reducers for cells and dashboards. Another effort must take place to separate a cell reducer to manage the state of an individual cell in Redux in order for this state to be sanely kept in Redux as well. For the time being, this state is being kept in the component for the sake of expeditiousness, since this is needed for Dashboards to be released. A refactor of this will occur later. * Cells should contain a links key in server response * Clean up console logs * Use live data instead of a cellQuery fixture * Update docs for dashboard creation * DB and RP are already present in the Command field * Fix LayoutRenderer’s understanding of query schema * Return a new object, rather that mutate in place * Visualization doesn’t use activeQueryID * Selected is an object, not a string * QueryBuilder refactored to use query index instead of query id * CellEditorOverlay refactored to use query index instead of query id * ConfirmButtons doesn’t need to act on an item * Rename functions to follow convention * Queries are no longer guaranteed to have ids * Omit WHERE and GROUP BY clauses when saving query * Select new query on add in OverlayTechnologies * Add click outside to dash graph menu, style menu also * Change context menu from ... to a caret More consistent with the rest of the UI, better affordance * Hide graph context menu in presentation mode Don’t want people editing a dashboard from presentation mode * Move graph refreshing spinner so it does not overlap with context menu * Wire up Cell Menu to Overlay Technologies * Correct empty dashboard type * Refactor dashboard spec fixtures * Test syncDashboardCell reducer * Remove Delete button from graph dropdown menu (for now) * Update changelog
2017-03-24 00:12:33 +00:00
// Dashboard Cells
router.GET("/chronograf/v1/dashboards/:id/cells", service.DashboardCells)
router.POST("/chronograf/v1/dashboards/:id/cells", service.NewDashboardCell)
router.GET("/chronograf/v1/dashboards/:id/cells/:cid", service.DashboardCellID)
router.DELETE("/chronograf/v1/dashboards/:id/cells/:cid", service.RemoveDashboardCell)
router.PUT("/chronograf/v1/dashboards/:id/cells/:cid", service.ReplaceDashboardCell)
2017-03-20 21:23:29 +00:00
// Databases
2017-03-22 20:27:36 +00:00
router.GET("/chronograf/v1/sources/:id/dbs", service.GetDatabases)
2017-03-23 05:21:25 +00:00
router.POST("/chronograf/v1/sources/:id/dbs", service.NewDatabase)
2017-03-23 08:04:35 +00:00
router.DELETE("/chronograf/v1/sources/:id/dbs/:dbid", service.DropDatabase)
2017-03-23 10:06:59 +00:00
// Retention Policies
router.GET("/chronograf/v1/sources/:id/dbs/:dbid/rps", service.RetentionPolicies)
2017-03-23 11:51:08 +00:00
router.POST("/chronograf/v1/sources/:id/dbs/:dbid/rps", service.NewRetentionPolicy)
router.PUT("/chronograf/v1/sources/:id/dbs/:dbid/rps/:rpid", service.UpdateRetentionPolicy)
2017-03-23 11:51:08 +00:00
router.DELETE("/chronograf/v1/sources/:id/dbs/:dbid/rps/:rpid", service.DropRetentionPolicy)
2017-03-20 21:23:29 +00:00
var authRoutes AuthRoutes
var out http.Handler
2016-10-25 15:20:06 +00:00
/* Authentication */
if opts.UseAuth {
// Encapsulate the router with OAuth2
var auth http.Handler
auth, authRoutes = AuthAPI(opts, router)
// Create middleware to redirect to the appropriate provider logout
targetURL := "/"
router.GET("/oauth/logout", Logout(targetURL, authRoutes))
out = Logger(opts.Logger, auth)
} else {
out = Logger(opts.Logger, router)
2016-10-25 15:20:06 +00:00
}
router.GET("/chronograf/v1/", AllRoutes(authRoutes, opts.Logger))
router.GET("/chronograf/v1", AllRoutes(authRoutes, opts.Logger))
return out
2016-10-25 15:20:06 +00:00
}
// AuthAPI adds the OAuth routes if auth is enabled.
func AuthAPI(opts MuxOpts, router *httprouter.Router) (http.Handler, AuthRoutes) {
routes := AuthRoutes{}
for _, pf := range opts.ProviderFuncs {
pf(func(p oauth2.Provider, m oauth2.Mux) {
loginPath := fmt.Sprintf("%s/oauth/%s/login", opts.Basepath, strings.ToLower(p.Name()))
logoutPath := fmt.Sprintf("%s/oauth/%s/logout", opts.Basepath, strings.ToLower(p.Name()))
callbackPath := fmt.Sprintf("%s/oauth/%s/callback", opts.Basepath, strings.ToLower(p.Name()))
router.Handler("GET", loginPath, m.Login())
router.Handler("GET", logoutPath, m.Logout())
router.Handler("GET", callbackPath, m.Callback())
routes = append(routes, AuthRoute{
Name: p.Name(),
Label: strings.Title(p.Name()),
Login: loginPath,
Logout: logoutPath,
Callback: callbackPath,
})
})
}
tokenMiddleware := AuthorizedToken(opts.Auth, opts.Logger, router)
2016-10-25 15:20:06 +00:00
// Wrap the API with token validation middleware.
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/chronograf/v1/") {
2016-10-25 15:20:06 +00:00
tokenMiddleware.ServeHTTP(w, r)
return
}
router.ServeHTTP(w, r)
}), routes
2016-10-25 15:20:06 +00:00
}
func encodeJSON(w http.ResponseWriter, status int, v interface{}, logger chronograf.Logger) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
2016-11-19 17:41:06 +00:00
unknownErrorWithMessage(w, err, logger)
2016-10-25 15:20:06 +00:00
}
}
// Error writes an JSON message
2016-11-19 17:41:06 +00:00
func Error(w http.ResponseWriter, code int, msg string, logger chronograf.Logger) {
e := ErrorMessage{
2016-10-25 15:20:06 +00:00
Code: code,
Message: msg,
}
b, err := json.Marshal(e)
if err != nil {
code = http.StatusInternalServerError
b = []byte(`{"code": 500, "message":"server_error"}`)
}
2016-11-19 17:41:06 +00:00
logger.
WithField("component", "server").
WithField("http_status ", code).
Error("Error message ", msg)
2016-10-25 15:20:06 +00:00
w.Header().Set("Content-Type", JSONType)
w.WriteHeader(code)
2016-12-20 20:59:56 +00:00
_, _ = w.Write(b)
2016-10-25 15:20:06 +00:00
}
2016-11-19 17:41:06 +00:00
func invalidData(w http.ResponseWriter, err error, logger chronograf.Logger) {
Error(w, http.StatusUnprocessableEntity, fmt.Sprintf("%v", err), logger)
2016-10-25 15:20:06 +00:00
}
2016-11-19 17:41:06 +00:00
func invalidJSON(w http.ResponseWriter, logger chronograf.Logger) {
Error(w, http.StatusBadRequest, "Unparsable JSON", logger)
2016-10-25 15:20:06 +00:00
}
2016-11-19 17:41:06 +00:00
func unknownErrorWithMessage(w http.ResponseWriter, err error, logger chronograf.Logger) {
Error(w, http.StatusInternalServerError, fmt.Sprintf("Unknown error: %v", err), logger)
2016-10-25 15:20:06 +00:00
}
2016-11-19 17:41:06 +00:00
func notFound(w http.ResponseWriter, id int, logger chronograf.Logger) {
Error(w, http.StatusNotFound, fmt.Sprintf("ID %d not found", id), logger)
2016-10-25 15:20:06 +00:00
}
func paramID(key string, r *http.Request) (int, error) {
ctx := r.Context()
param := httprouter.GetParamFromContext(ctx, key)
id, err := strconv.Atoi(param)
if err != nil {
return -1, fmt.Errorf("Error converting ID %s", param)
}
return id, nil
}