Exemple #1
0
func setupHandlers(metricSink *metricsink.MetricSink, podLister *cache.StoreToPodLister) http.Handler {

	runningInKubernetes := true

	// Make API handler.
	wsContainer := restful.NewContainer()
	wsContainer.EnableContentEncoding(true)
	wsContainer.Router(restful.CurlyRouter{})
	a := v1.NewApi(runningInKubernetes, metricSink)
	a.Register(wsContainer)
	// Metrics API
	m := metricsApi.NewApi(metricSink, podLister)
	m.Register(wsContainer)

	handlePprofEndpoint := func(req *restful.Request, resp *restful.Response) {
		name := strings.TrimPrefix(req.Request.URL.Path, pprofBasePath)
		switch name {
		case "profile":
			pprof.Profile(resp, req.Request)
		case "symbol":
			pprof.Symbol(resp, req.Request)
		case "cmdline":
			pprof.Cmdline(resp, req.Request)
		default:
			pprof.Index(resp, req.Request)
		}
	}

	// Setup pporf handlers.
	ws := new(restful.WebService).Path(pprofBasePath)
	ws.Route(ws.GET("/{subpath:*}").To(metrics.InstrumentRouteFunc("pprof", handlePprofEndpoint))).Doc("pprof endpoint")
	wsContainer.Add(ws)

	return wsContainer
}
Exemple #2
0
// initAPIVersionRoute initializes the osapi endpoint to behave similar to the upstream api endpoint
func initAPIVersionRoute(root *restful.WebService, prefix string, versions ...string) {
	versionHandler := apiserver.APIVersionHandler(versions...)
	root.Route(root.GET(prefix).To(versionHandler).
		Doc("list supported server API versions").
		Produces(restful.MIME_JSON).
		Consumes(restful.MIME_JSON))
}
Exemple #3
0
// initHealthCheckRoute initalizes an HTTP endpoint for health checking.
// OpenShift is deemed healthy if the API server can respond with an OK messages
func initMetricsRoute(root *restful.WebService, path string) {
	h := prometheus.Handler()
	root.Route(root.GET(path).To(func(req *restful.Request, resp *restful.Response) {
		h.ServeHTTP(resp.ResponseWriter, req.Request)
	}).Doc("return metrics for this process").
		Returns(http.StatusOK, "if metrics are available", nil).
		Produces("text/plain"))
}
Exemple #4
0
// initHealthCheckRoute initalizes an HTTP endpoint for health checking.
// OpenShift is deemed healthy if the API server can respond with an OK messages
func initHealthCheckRoute(root *restful.WebService, path string) {
	root.Route(root.GET(path).To(func(req *restful.Request, resp *restful.Response) {
		resp.ResponseWriter.WriteHeader(http.StatusOK)
		resp.ResponseWriter.Write([]byte("ok"))
	}).Doc("return the health state of the master").
		Returns(http.StatusOK, "if master is healthy", nil).
		Produces(restful.MIME_JSON))
}
Exemple #5
0
// initOAuthAuthorizationServerMetadataRoute initializes an HTTP endpoint for OAuth 2.0 Authorization Server Metadata discovery
// https://tools.ietf.org/id/draft-ietf-oauth-discovery-04.html#rfc.section.2
// masterPublicURL should be internally and externally routable to allow all users to discover this information
func initOAuthAuthorizationServerMetadataRoute(apiContainer *genericmux.APIContainer, path, masterPublicURL string) {
	// Build OAuth metadata once
	metadata, err := json.MarshalIndent(discovery.Get(masterPublicURL, OpenShiftOAuthAuthorizeURL(masterPublicURL), OpenShiftOAuthTokenURL(masterPublicURL)), "", "  ")
	if err != nil {
		glog.Errorf("Unable to initialize OAuth authorization server metadata route: %v", err)
		return
	}

	secretContainer := restful.Container{
		ServeMux: apiContainer.SecretRoutes.(*http.ServeMux), // we know it's a *http.ServeMux. In kube 1.6, the type will actually be correct.
	}

	// Set up a service to return the OAuth metadata.
	ws := new(restful.WebService)
	ws.Path(path)
	ws.Doc("OAuth 2.0 Authorization Server Metadata")
	ws.Route(
		ws.GET("/").To(func(_ *restful.Request, resp *restful.Response) {
			writeJSON(resp, metadata)
		}).
			Doc("get the server's OAuth 2.0 Authorization Server Metadata").
			Operation("getOAuthAuthorizationServerMetadata").
			Produces(restful.MIME_JSON))

	secretContainer.Add(ws)
}
Exemple #6
0
// initAPIVersionRoute initializes the osapi endpoint to behave similar to the upstream api endpoint
func initAPIVersionRoute(root *restful.WebService, prefix string, versions ...string) {
	versionHandler := apiserver.APIVersionHandler(kapi.Codecs, func(req *restful.Request) *unversioned.APIVersions {
		apiVersionsForDiscovery := unversioned.APIVersions{
			// TODO: ServerAddressByClientCIDRs: s.getServerAddressByClientCIDRs(req.Request),
			Versions: versions,
		}
		return &apiVersionsForDiscovery
	})
	root.Route(root.GET(prefix).To(versionHandler).
		Doc("list supported server API versions").
		Produces(restful.MIME_JSON).
		Consumes(restful.MIME_JSON))
}
Exemple #7
0
// initMetricsRoute initializes an HTTP endpoint for metrics.
func initMetricsRoute(apiContainer *genericmux.APIContainer, path string) {
	ws := new(restful.WebService).
		Path(path).
		Doc("return metrics for this process")
	h := prometheus.Handler()
	ws.Route(ws.GET("/").To(func(req *restful.Request, resp *restful.Response) {
		h.ServeHTTP(resp.ResponseWriter, req.Request)
	}).Doc("return metrics for this process").
		Returns(http.StatusOK, "if metrics are available", nil).
		Produces("text/plain"))

	apiContainer.Add(ws)
}
// NewService creates and returns a new Service, initalized with a new
// restful.WebService configured with a route that dispatches to the supplied
// handler. The new Service must be registered before accepting traffic by
// calling Register.
func NewService(handler restful.RouteFunction) *Service {
	restful.EnableTracing(true)
	webService := new(restful.WebService)
	webService.Consumes(restful.MIME_JSON, restful.MIME_XML)
	webService.Produces(restful.MIME_JSON, restful.MIME_XML)
	webService.Route(webService.POST("/expand").To(handler).
		Doc("Expand a template.").
		Reads(&expander.Template{}))
	return &Service{webService}
}
Exemple #9
0
// initReadinessCheckRoute initializes an HTTP endpoint for readiness checking
func initReadinessCheckRoute(root *restful.WebService, path string, readyFunc func() bool) {
	root.Route(root.GET(path).To(func(req *restful.Request, resp *restful.Response) {
		if readyFunc() {
			resp.ResponseWriter.WriteHeader(http.StatusOK)
			resp.ResponseWriter.Write([]byte("ok"))

		} else {
			resp.ResponseWriter.WriteHeader(http.StatusServiceUnavailable)
		}
	}).Doc("return the readiness state of the master").
		Returns(http.StatusOK, "if the master is ready", nil).
		Returns(http.StatusServiceUnavailable, "if the master is not ready", nil).
		Produces(restful.MIME_JSON))
}
Exemple #10
0
// initReadinessCheckRoute initializes an HTTP endpoint for readiness checking
func initVersionRoute(container *restful.Container, path string) {
	// Set up a service to return the git code version.
	versionWS := new(restful.WebService)
	versionWS.Path(path)
	versionWS.Doc("git code version from which this is built")
	versionWS.Route(
		versionWS.GET("/").To(handleVersion).
			Doc("get the code version").
			Operation("getCodeVersion").
			Produces(restful.MIME_JSON).
			Consumes(restful.MIME_JSON))

	container.Add(versionWS)
}
Exemple #11
0
// Creates a new HTTP handler that handles all requests to the API of the backend.
func CreateApiHandler(client *client.Client) http.Handler {
	wsContainer := restful.NewContainer()

	// TODO(bryk): This is for tests only. Replace with real implementation once ready.
	ws := new(restful.WebService)
	ws.Path("/api/deploy").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	ws.Route(ws.POST("").To(func(request *restful.Request, response *restful.Response) {
		cfg := new(DeployAppConfig)
		if err := request.ReadEntity(cfg); err != nil {
			HandleInternalError(response, err)
			return
		}
		if err := DeployApp(cfg, client); err != nil {
			HandleInternalError(response, err)
			return
		}

		response.WriteHeaderAndEntity(http.StatusCreated, cfg)
	}).Reads(DeployAppConfig{}).Writes(DeployAppConfig{}))

	wsContainer.Add(ws)

	return wsContainer
}
Exemple #12
0
// initAPIVersionRoute initializes the osapi endpoint to behave similar to the upstream api endpoint
func initAPIVersionRoute(apiContainer *genericmux.APIContainer, prefix string, versions ...string) {
	versionHandler := apiserver.APIVersionHandler(kapi.Codecs, func(req *restful.Request) *unversioned.APIVersions {
		apiVersionsForDiscovery := unversioned.APIVersions{
			// TODO: ServerAddressByClientCIDRs: s.getServerAddressByClientCIDRs(req.Request),
			Versions: versions,
		}
		return &apiVersionsForDiscovery
	})
	ws := new(restful.WebService).
		Path(prefix).
		Doc("list supported server API versions")
	ws.Route(ws.GET("/").To(versionHandler).
		Doc("list supported server API versions").
		Produces(restful.MIME_JSON).
		Consumes(restful.MIME_JSON).
		Operation("get" + strings.Title(prefix[1:]) + "Version"))
	apiContainer.Add(ws)
}
Exemple #13
0
// initReadinessCheckRoute initializes an HTTP endpoint for readiness checking
func initReadinessCheckRoute(apiContainer *genericmux.APIContainer, path string, readyFunc func() bool) {
	ws := new(restful.WebService).
		Path(path).
		Doc("return the readiness state of the master")
	ws.Route(ws.GET("/").To(func(req *restful.Request, resp *restful.Response) {
		if readyFunc() {
			resp.ResponseWriter.WriteHeader(http.StatusOK)
			resp.ResponseWriter.Write([]byte("ok"))

		} else {
			resp.ResponseWriter.WriteHeader(http.StatusServiceUnavailable)
		}
	}).Doc("return the readiness state of the master").
		Returns(http.StatusOK, "if the master is ready", nil).
		Returns(http.StatusServiceUnavailable, "if the master is not ready", nil).
		Produces(restful.MIME_JSON))

	apiContainer.Add(ws)
}
Exemple #14
0
// NewService encapsulates code to open an HTTP server on the given address:port that serves the
// expansion API using the given Expander backend to do the actual expansion.  After calling
// NewService, call ListenAndServe to start the returned service.
func NewService(address string, port int, backend Expander) *Service {

	restful.EnableTracing(true)
	webService := new(restful.WebService)
	webService.Consumes(restful.MIME_JSON)
	webService.Produces(restful.MIME_JSON)
	handler := func(req *restful.Request, resp *restful.Response) {
		util.LogHandlerEntry("expansion service", req.Request)
		request := &ServiceRequest{}
		if err := req.ReadEntity(&request); err != nil {
			badRequest(resp, err.Error())
			return
		}

		reqMsg := fmt.Sprintf("\nhandling request:\n%s\n", util.ToYAMLOrError(request))
		util.LogHandlerText("expansion service", reqMsg)
		response, err := backend.ExpandChart(request)
		if err != nil {
			badRequest(resp, fmt.Sprintf("error expanding chart: %s", err))
			return
		}

		util.LogHandlerExit("expansion service", http.StatusOK, "OK", resp.ResponseWriter)
		respMsg := fmt.Sprintf("\nreturning response:\n%s\n", util.ToYAMLOrError(response.Resources))
		util.LogHandlerText("expansion service", respMsg)
		resp.WriteEntity(response)
	}
	webService.Route(
		webService.POST("/expand").
			To(handler).
			Doc("Expand a chart.").
			Reads(&ServiceRequest{}).
			Writes(&ServiceResponse{}))

	container := restful.DefaultContainer
	container.Add(webService)
	server := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", address, port),
		Handler: container,
	}

	return &Service{
		webService: webService,
		server:     server,
		container:  container,
	}
}
Exemple #15
0
// initOAuthAuthorizationServerMetadataRoute initializes an HTTP endpoint for OAuth 2.0 Authorization Server Metadata discovery
// https://tools.ietf.org/id/draft-ietf-oauth-discovery-04.html#rfc.section.2
// masterPublicURL should be internally and externally routable to allow all users to discover this information
func initOAuthAuthorizationServerMetadataRoute(container *restful.Container, path, masterPublicURL string) {
	// Build OAuth metadata once
	metadata, err := json.MarshalIndent(discovery.Get(masterPublicURL, OpenShiftOAuthAuthorizeURL(masterPublicURL), OpenShiftOAuthTokenURL(masterPublicURL)), "", "  ")
	if err != nil {
		glog.Errorf("Unable to initialize OAuth authorization server metadata route: %v", err)
		return
	}

	// Set up a service to return the OAuth metadata.
	oauthWS := new(restful.WebService)
	oauthWS.Path(path)
	oauthWS.Doc("OAuth 2.0 Authorization Server Metadata")
	oauthWS.Route(
		oauthWS.GET("/").To(func(_ *restful.Request, resp *restful.Response) {
			writeJSON(resp, metadata)
		}).
			Doc("get the server's OAuth 2.0 Authorization Server Metadata").
			Operation("getOAuthAuthorizationServerMetadata").
			Produces(restful.MIME_JSON))

	container.Add(oauthWS)
}
Exemple #16
0
// initVersionRoute initializes an HTTP endpoint for the server's version information.
func initVersionRoute(container *restful.Container, path string) {
	// Build version info once
	versionInfo, err := json.MarshalIndent(version.Get(), "", "  ")
	if err != nil {
		glog.Errorf("Unable to initialize version route: %v", err)
		return
	}

	// Set up a service to return the git code version.
	versionWS := new(restful.WebService)
	versionWS.Path(path)
	versionWS.Doc("git code version from which this is built")
	versionWS.Route(
		versionWS.GET("/").To(func(_ *restful.Request, resp *restful.Response) {
			writeJSON(resp, versionInfo)
		}).
			Doc("get the code version").
			Operation("getCodeVersion").
			Produces(restful.MIME_JSON))

	container.Add(versionWS)
}
Exemple #17
0
// RegisterModel registers the Model API endpoints.
// All endpoints that end with a {metric-name} also receive a start time query parameter.
// The start and end times should be specified as a string, formatted according to RFC 3339.
func (a *Api) RegisterModel(container *restful.Container) {
	ws := new(restful.WebService)
	ws.Path("/api/v1/model").
		Doc("Root endpoint of the stats model").
		Consumes("*/*").
		Produces(restful.MIME_JSON)

	addClusterMetricsRoutes(a, ws)

	ws.Route(ws.GET("/debug/allkeys").
		To(metrics.InstrumentRouteFunc("debugAllKeys", a.allKeys)).
		Doc("Get keys of all metric sets available").
		Operation("debugAllKeys"))
	container.Add(ws)
}
Exemple #18
0
func register(container *restful.Container) {
	restful.RegisterEntityAccessor(MIME_MSGPACK, NewEntityAccessorMsgPack())
	ws := new(restful.WebService)
	ws.
		Path("/test").
		Consumes(restful.MIME_JSON, MIME_MSGPACK).
		Produces(restful.MIME_JSON, MIME_MSGPACK)
	// route user api
	ws.Route(ws.POST("/msgpack").
		To(do).
		Reads(user{}).
		Writes(userResponse{}))
	container.Add(ws)
}
Exemple #19
0
// Register the Api on the specified endpoint.
func (a *Api) Register(container *restful.Container) {
	ws := new(restful.WebService)
	ws.
		Path("/api/v1/metric-export").
		Doc("Exports the latest point for all Heapster metrics").
		Produces(restful.MIME_JSON)
	ws.Route(ws.GET("").
		Filter(compressionFilter).
		To(a.exportMetrics).
		Doc("export the latest data point for all metrics").
		Operation("exportMetrics").
		Writes([]*Timeseries{}))
	container.Add(ws)
	ws = new(restful.WebService)
	ws.Path("/api/v1/metric-export-schema").
		Doc("Schema for metrics exported by heapster").
		Produces(restful.MIME_JSON)
	ws.Route(ws.GET("").
		To(a.exportMetricsSchema).
		Doc("export the schema for all metrics").
		Operation("exportmetricsSchema").
		Writes(TimeseriesSchema{}))
	container.Add(ws)
	ws = new(restful.WebService)
	ws.Path("/api/v1/sinks").
		Doc("Configuration for Heapster sinks for exporting data").
		Produces(restful.MIME_JSON)
	ws.Route(ws.POST("").
		To(a.setSinks).
		Doc("set the current sinks").
		Operation("setSinks").
		Reads([]string{}))
	ws.Route(ws.GET("").
		To(a.getSinks).
		Doc("get the current sinks").
		Operation("getSinks").
		Writes([]string{}))
	container.Add(ws)

	// Register the endpoints of the model
	a.RegisterModel(container)
}
Exemple #20
0
func main() {
	ws := new(restful.WebService)
	ws.Path("/itrain").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON)
	ws.Route(ws.GET("/version").
		To(report_version).
		Doc("get itrain version number").
		Operation("version"))

	ws.Route(ws.GET("/report_inverter").
		To(report_inverter).
		Doc("get inverter report data").
		Operation("report_inverter").
		Param(ws.QueryParameter("sd", "startdate")))

	restful.Add(ws)

	config := swagger.Config{
		WebServices:    restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible
		WebServicesUrl: "/",
		ApiPath:        "/apidocs.json",
		// specifiy where the UI is located
		SwaggerPath:     "/apidocs/",
		SwaggerFilePath: "./swaggerui"}
	swagger.RegisterSwaggerService(config, restful.DefaultContainer)

	var (
		hostname string = "127.0.0.1"
		port     int    = 8080
	)
	// Listen on hostname:port
	fmt.Printf("Listening on %s:%d...\n", hostname, port)
	err := http.ListenAndServe(fmt.Sprintf("%s:%d", hostname, port), nil)
	if err != nil {
		log.Fatal("Error: ", err)
	}

}
// addAggregationRoutes adds routes to a webservice which point to a metricsAggregationFetcher's methods
func addAggregationRoutes(a metricsAggregationFetcher, ws *restful.WebService) {
	// The /metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for the Cluster entity of the historical API.
	ws.Route(ws.GET("/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("clusterMetrics", a.clusterAggregations)).
		Doc("Export some cluster-level metric aggregations").
		Operation("clusterAggregations").
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	// The /nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for a Node entity of the historical API.
	// The {node-name} parameter is the hostname of a specific node.
	ws.Route(ws.GET("/nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("nodeMetrics", a.nodeAggregations)).
		Doc("Export a node-level metric").
		Operation("nodeAggregations").
		Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")).
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	if a.isRunningInKubernetes() {
		// The /namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations
		// for a Namespace entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("namespaceMetrics", a.namespaceAggregations)).
			Doc("Export some namespace-level metric aggregations").
			Operation("namespaceAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Pod entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)).
			Doc("Export some pod-level metric aggregations").
			Operation("podAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Container entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)).
			Doc("Export some aggregations for a Pod Container").
			Operation("podContainerAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to use").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Pod entity of the historical API.
		ws.Route(ws.GET("/pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)).
			Doc("Export some pod-level metric aggregations").
			Operation("podAggregations").
			Param(ws.PathParameter("pod-id", "The UID of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Container entity of the historical API.
		ws.Route(ws.GET("/pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)).
			Doc("Export some aggregations for a Pod Container").
			Operation("podContainerAggregations").
			Param(ws.PathParameter("pod-id", "The name of the pod to use").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))
	}

	// The /nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
	// some aggregations for a free Container entity of the historical API.
	ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("freeContainerMetrics", a.freeContainerAggregations)).
		Doc("Export a contsome iner-level metric aggregations for a free container").
		Operation("freeContainerAggregations").
		Param(ws.PathParameter("node-name", "The name of the node to use").DataType("string")).
		Param(ws.PathParameter("container-name", "The name of the container to use").DataType("string")).
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	if a.isRunningInKubernetes() {
		// The /namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// metrics for a list of pods of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)).
			Doc("Export some aggregations for all pods from the given list").
			Operation("podListAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-list", "Comma separated list of pod names to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResultList{}))

		// The /pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// metrics for a list of pod ids of the historical API.
		ws.Route(ws.GET("/pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)).
			Doc("Export an aggregation for all pods from the given list").
			Operation("podListAggregations").
			Param(ws.PathParameter("pod-id-list", "Comma separated list of pod UIDs to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResultList{}))
	}
}
Exemple #22
0
// InstallDefaultHandlers registers the default set of supported HTTP request
// patterns with the restful Container.
func (s *Server) InstallDefaultHandlers() {
	healthz.InstallHandler(s.restfulCont,
		healthz.PingHealthz,
		healthz.NamedCheck("syncloop", s.syncLoopHealthCheck),
	)
	var ws *restful.WebService
	ws = new(restful.WebService)
	ws.
		Path("/pods").
		Produces(restful.MIME_JSON)
	ws.Route(ws.GET("").
		To(s.getPods).
		Operation("getPods"))
	s.restfulCont.Add(ws)

	s.restfulCont.Handle("/stats/", &httpHandler{f: s.handleStats})
	s.restfulCont.Handle("/metrics", prometheus.Handler())

	ws = new(restful.WebService)
	ws.
		Path("/spec/").
		Produces(restful.MIME_JSON)
	ws.Route(ws.GET("").
		To(s.getSpec).
		Operation("getSpec").
		Writes(cadvisorapi.MachineInfo{}))
	s.restfulCont.Add(ws)
}
Exemple #23
0
// addClusterMetricsRoutes adds all the standard model routes to a WebService.
// It should already have a base path registered.
func addClusterMetricsRoutes(a clusterMetricsFetcher, ws *restful.WebService) {
	// The /metrics/ endpoint returns a list of all available metrics for the Cluster entity of the model.
	ws.Route(ws.GET("/metrics/").
		To(metrics.InstrumentRouteFunc("availableClusterMetrics", a.availableClusterMetrics)).
		Doc("Get a list of all available metrics for the Cluster entity").
		Operation("availableClusterMetrics"))

	// The /metrics/{metric-name} endpoint exposes an aggregated metric for the Cluster entity of the model.
	ws.Route(ws.GET("/metrics/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("clusterMetrics", a.clusterMetrics)).
		Doc("Export an aggregated cluster-level metric").
		Operation("clusterMetrics").
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricResult{}))

	// The /nodes/{node-name}/metrics endpoint returns a list of all nodes with some metrics.
	ws.Route(ws.GET("/nodes/").
		To(metrics.InstrumentRouteFunc("nodeList", a.nodeList)).
		Doc("Get a list of all nodes that have some current metrics").
		Operation("nodeList"))

	// The /nodes/{node-name}/metrics endpoint returns a list of all available metrics for a Node entity.
	ws.Route(ws.GET("/nodes/{node-name}/metrics/").
		To(metrics.InstrumentRouteFunc("availableNodeMetrics", a.availableNodeMetrics)).
		Doc("Get a list of all available metrics for a Node entity").
		Operation("availableNodeMetrics").
		Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")))

	// The /nodes/{node-name}/metrics/{metric-name} endpoint exposes a metric for a Node entity of the model.
	// The {node-name} parameter is the hostname of a specific node.
	ws.Route(ws.GET("/nodes/{node-name}/metrics/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("nodeMetrics", a.nodeMetrics)).
		Doc("Export a node-level metric").
		Operation("nodeMetrics").
		Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricResult{}))

	if a.isRunningInKubernetes() {

		ws.Route(ws.GET("/namespaces/").
			To(metrics.InstrumentRouteFunc("namespaceList", a.namespaceList)).
			Doc("Get a list of all namespaces that have some current metrics").
			Operation("namespaceList"))

		// The /namespaces/{namespace-name}/metrics endpoint returns a list of all available metrics for a Namespace entity.
		ws.Route(ws.GET("/namespaces/{namespace-name}/metrics").
			To(metrics.InstrumentRouteFunc("availableNamespaceMetrics", a.availableNamespaceMetrics)).
			Doc("Get a list of all available metrics for a Namespace entity").
			Operation("availableNamespaceMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")))

		// The /namespaces/{namespace-name}/metrics/{metric-name} endpoint exposes an aggregated metrics
		// for a Namespace entity of the model.
		ws.Route(ws.GET("/namespaces/{namespace-name}/metrics/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("namespaceMetrics", a.namespaceMetrics)).
			Doc("Export an aggregated namespace-level metric").
			Operation("namespaceMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricResult{}))

		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/").
			To(metrics.InstrumentRouteFunc("namespacePodList", a.namespacePodList)).
			Doc("Get a list of pods from the given namespace that have some metrics").
			Operation("namespacePodList").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")))

		// The /namespaces/{namespace-name}/pods/{pod-name}/metrics endpoint returns a list of all available metrics for a Pod entity.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics").
			To(metrics.InstrumentRouteFunc("availablePodMetrics", a.availablePodMetrics)).
			Doc("Get a list of all available metrics for a Pod entity").
			Operation("availablePodMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")))

		// The /namespaces/{namespace-name}/pods/{pod-name}/metrics/{metric-name} endpoint exposes
		// an aggregated metric for a Pod entity of the model.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podMetrics", a.podMetrics)).
			Doc("Export an aggregated pod-level metric").
			Operation("podMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricResult{}))

		// The /namespaces/{namespace-name}/pods/{pod-name}/containers endpoint
		// returns a list of all containers for a Pod entity.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers").
			To(metrics.InstrumentRouteFunc("podContainerList", a.podContainerList)).
			Doc("Get a list of containers for a Pod entity ").
			Operation("podContainerList").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")))

		// The /namespaces/{namespace-name}/pods/{pod-name}/containers/metrics/{container-name}/metrics endpoint
		// returns a list of all available metrics for a Pod Container entity.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics").
			To(metrics.InstrumentRouteFunc("availableContainerMetrics", a.availablePodContainerMetrics)).
			Doc("Get a list of all available metrics for a Pod entity").
			Operation("availableContainerMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")))

		// The /namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics/{metric-name} endpoint exposes
		// a metric for a Container entity of the model.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerMetrics)).
			Doc("Export an aggregated metric for a Pod Container").
			Operation("podContainerMetrics").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to use").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricResult{}))
	}

	ws.Route(ws.GET("/nodes/{node-name}/freecontainers/").
		To(metrics.InstrumentRouteFunc("systemContainerList", a.nodeSystemContainerList)).
		Doc("Get a list of all non-pod containers with some metrics").
		Operation("systemContainerList").
		Param(ws.PathParameter("node-name", "The name of the namespace to lookup").DataType("string")))

	// The /nodes/{node-name}/freecontainers/{container-name}/metrics endpoint
	// returns a list of all available metrics for a Free Container entity.
	ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics").
		To(metrics.InstrumentRouteFunc("availableMetrics", a.availableFreeContainerMetrics)).
		Doc("Get a list of all available metrics for a free Container entity").
		Operation("availableMetrics").
		Param(ws.PathParameter("node-name", "The name of the namespace to lookup").DataType("string")).
		Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")))

	// The /nodes/{node-name}/freecontainers/{container-name}/metrics/{metric-name} endpoint exposes
	// a metric for a free Container entity of the model.
	ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("freeContainerMetrics", a.freeContainerMetrics)).
		Doc("Export a container-level metric for a free container").
		Operation("freeContainerMetrics").
		Param(ws.PathParameter("node-name", "The name of the node to use").DataType("string")).
		Param(ws.PathParameter("container-name", "The name of the container to use").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricResult{}))

	if a.isRunningInKubernetes() {
		// The /namespaces/{namespace-name}/pod-list/{pod-list}/metrics/{metric-name} endpoint exposes
		// metrics for a list of pods of the model.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pod-list/{pod-list}/metrics/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podListMetric", a.podListMetrics)).
			Doc("Export a metric for all pods from the given list").
			Operation("podListMetric").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-list", "Comma separated list of pod names to lookup").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricResult{}))
	}
}
Exemple #24
0
// Creates a new HTTP handler that handles all requests to the API of the backend.
func CreateHttpApiHandler(client *client.Client) http.Handler {
	apiHandler := ApiHandler{client}
	wsContainer := restful.NewContainer()

	deployWs := new(restful.WebService)
	deployWs.Path("/api/appdeployments").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployWs.Route(
		deployWs.POST("").
			To(apiHandler.handleDeploy).
			Reads(AppDeployment{}).
			Writes(AppDeployment{}))
	wsContainer.Add(deployWs)

	replicaSetWs := new(restful.WebService)
	replicaSetWs.Path("/api/replicasets").
		Produces(restful.MIME_JSON)
	replicaSetWs.Route(
		replicaSetWs.GET("").
			To(apiHandler.handleGetReplicaSetList).
			Writes(ReplicaSetList{}))
	replicaSetWs.Route(
		replicaSetWs.GET("/{namespace}/{replicaSet}").
			To(apiHandler.handleGetReplicaSetDetail).
			Writes(ReplicaSetDetail{}))
	wsContainer.Add(replicaSetWs)

	namespaceListWs := new(restful.WebService)
	namespaceListWs.Path("/api/namespaces").
		Produces(restful.MIME_JSON)
	namespaceListWs.Route(
		namespaceListWs.GET("").
			To(apiHandler.handleGetNamespaceList).
			Writes(NamespacesList{}))
	wsContainer.Add(namespaceListWs)

	return wsContainer
}
// RegisterMetrics registers the Metrics API endpoints.
// All endpoints that end with a {metric-name} also receive a start time query parameter.
// The start and end times should be specified as a string, formatted according to RFC 3339.
// These apis are experimental, so they may change or disappear in the future.
func (a *Api) RegisterMetrics(container *restful.Container) {
	ws := new(restful.WebService)
	ws.
		Path("/experimental/v2").
		Doc("Root endpoint of the stats model").
		Consumes("*/*").
		Produces(restful.MIME_JSON)

	ws.Route(ws.GET("/nodeMetrics/derived/").
		To(a.derivedNodeMetricsList).
		Filter(compressionFilter).
		Doc("Get a list of all available metrics for all nodes").
		Writes([]types.DerivedNodeMetrics{}).
		Operation("derivedNodeMetricsList"))

	ws.Route(ws.GET("/nodeMetrics/derived/{node-name}").
		To(a.derivedNodeMetrics).
		Filter(compressionFilter).
		Doc("Get a list of all raw metrics for a Node entity").
		Writes(types.DerivedNodeMetrics{}).
		Operation("derivedNodeMetrics").
		Param(ws.PathParameter("node-name", "The name of the node to look up").DataType("string")))

	container.Add(ws)
}
Exemple #26
0
// Creates a new HTTP handler that handles all requests to the API of the backend.
func CreateHttpApiHandler(client *client.Client, heapsterClient HeapsterClient,
	clientConfig clientcmd.ClientConfig) http.Handler {

	apiHandler := ApiHandler{client, heapsterClient, clientConfig}
	wsContainer := restful.NewContainer()

	deployWs := new(restful.WebService)
	deployWs.Filter(wsLogger)
	deployWs.Path("/api/v1/appdeployments").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployWs.Route(
		deployWs.POST("").
			To(apiHandler.handleDeploy).
			Reads(AppDeploymentSpec{}).
			Writes(AppDeploymentSpec{}))
	deployWs.Route(
		deployWs.POST("/validate/name").
			To(apiHandler.handleNameValidity).
			Reads(AppNameValiditySpec{}).
			Writes(AppNameValidity{}))
	deployWs.Route(
		deployWs.POST("/validate/protocol").
			To(apiHandler.handleProtocolValidity).
			Reads(ProtocolValiditySpec{}).
			Writes(ProtocolValidity{}))
	deployWs.Route(
		deployWs.GET("/protocols").
			To(apiHandler.handleGetAvailableProcotols).
			Writes(Protocols{}))
	wsContainer.Add(deployWs)

	deployFromFileWs := new(restful.WebService)
	deployFromFileWs.Path("/api/v1/appdeploymentfromfile").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployFromFileWs.Route(
		deployFromFileWs.POST("").
			To(apiHandler.handleDeployFromFile).
			Reads(AppDeploymentFromFileSpec{}).
			Writes(AppDeploymentFromFileResponse{}))
	wsContainer.Add(deployFromFileWs)

	replicationControllerWs := new(restful.WebService)
	replicationControllerWs.Filter(wsLogger)
	replicationControllerWs.Path("/api/v1/replicationcontrollers").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	replicationControllerWs.Route(
		replicationControllerWs.GET("").
			To(apiHandler.handleGetReplicationControllerList).
			Writes(ReplicationControllerList{}))
	replicationControllerWs.Route(
		replicationControllerWs.GET("/{namespace}/{replicationController}").
			To(apiHandler.handleGetReplicationControllerDetail).
			Writes(ReplicationControllerDetail{}))
	replicationControllerWs.Route(
		replicationControllerWs.POST("/{namespace}/{replicationController}/update/pods").
			To(apiHandler.handleUpdateReplicasCount).
			Reads(ReplicationControllerSpec{}))
	replicationControllerWs.Route(
		replicationControllerWs.DELETE("/{namespace}/{replicationController}").
			To(apiHandler.handleDeleteReplicationController))
	replicationControllerWs.Route(
		replicationControllerWs.GET("/pods/{namespace}/{replicationController}").
			To(apiHandler.handleGetReplicationControllerPods).
			Writes(ReplicationControllerPods{}))
	wsContainer.Add(replicationControllerWs)

	namespacesWs := new(restful.WebService)
	namespacesWs.Filter(wsLogger)
	namespacesWs.Path("/api/v1/namespaces").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	namespacesWs.Route(
		namespacesWs.POST("").
			To(apiHandler.handleCreateNamespace).
			Reads(NamespaceSpec{}).
			Writes(NamespaceSpec{}))
	namespacesWs.Route(
		namespacesWs.GET("").
			To(apiHandler.handleGetNamespaces).
			Writes(NamespaceList{}))
	wsContainer.Add(namespacesWs)

	logsWs := new(restful.WebService)
	logsWs.Filter(wsLogger)
	logsWs.Path("/api/v1/logs").
		Produces(restful.MIME_JSON)
	logsWs.Route(
		logsWs.GET("/{namespace}/{podId}").
			To(apiHandler.handleLogs).
			Writes(Logs{}))
	logsWs.Route(
		logsWs.GET("/{namespace}/{podId}/{container}").
			To(apiHandler.handleLogs).
			Writes(Logs{}))
	wsContainer.Add(logsWs)

	eventsWs := new(restful.WebService)
	eventsWs.Filter(wsLogger)
	eventsWs.Path("/api/v1/events").
		Produces(restful.MIME_JSON)
	eventsWs.Route(
		eventsWs.GET("/{namespace}/{replicationController}").
			To(apiHandler.handleEvents).
			Writes(Events{}))
	wsContainer.Add(eventsWs)

	nodesWs := new(restful.WebService)
	nodesWs.Path("/api/nodes").
		Produces(restful.MIME_JSON)
	nodesWs.Route(
		nodesWs.GET("").
			To(apiHandler.handleGetNodes).
			Writes(NodeList{}))
	nodesWs.Route(
		nodesWs.GET("/{name}/stats").
			To(apiHandler.handleGetNodeStats).
			Writes(NodeStats{}))
	wsContainer.Add(nodesWs)

	secretsWs := new(restful.WebService)
	secretsWs.Path("/api/v1/secrets").Produces(restful.MIME_JSON)
	secretsWs.Route(
		secretsWs.GET("/{namespace}").
			To(apiHandler.handleGetSecrets).
			Writes(SecretsList{}))
	secretsWs.Route(
		secretsWs.POST("").
			To(apiHandler.handleCreateImagePullSecret).
			Reads(ImagePullSecretSpec{}).
			Writes(Secret{}))
	wsContainer.Add(secretsWs)

	return wsContainer
}
Exemple #27
0
// initControllerRoutes adds a web service endpoint for managing the execution
// state of the controllers.
func initControllerRoutes(root *restful.WebService, path string, canStart bool, plug plug.Plug) {
	root.Route(root.GET(path).To(func(req *restful.Request, resp *restful.Response) {
		if !canStart {
			resp.ResponseWriter.WriteHeader(http.StatusMethodNotAllowed)
			fmt.Fprintf(resp, "disabled")
			return
		}
		if plug.IsStarted() {
			resp.ResponseWriter.WriteHeader(http.StatusOK)
			fmt.Fprintf(resp, "ok")
		} else {
			resp.ResponseWriter.WriteHeader(http.StatusAccepted)
			fmt.Fprintf(resp, "waiting")
		}
	}).Doc("Check whether the controllers are running on this master").
		Returns(http.StatusOK, "if controllers are running", nil).
		Returns(http.StatusMethodNotAllowed, "if controllers are disabled", nil).
		Returns(http.StatusAccepted, "if controllers are waiting to be started", nil).
		Produces(restful.MIME_JSON))

	root.Route(root.PUT(path).To(func(req *restful.Request, resp *restful.Response) {
		if !canStart {
			resp.ResponseWriter.WriteHeader(http.StatusMethodNotAllowed)
			fmt.Fprintf(resp, "disabled")
			return
		}
		plug.Start()
		resp.ResponseWriter.WriteHeader(http.StatusOK)
		fmt.Fprintf(resp, "ok")
	}).Doc("Start controllers on this master").
		Returns(http.StatusOK, "if controllers have started", nil).
		Returns(http.StatusMethodNotAllowed, "if controllers are disabled", nil).
		Produces(restful.MIME_JSON))

	root.Route(root.DELETE(path).To(func(req *restful.Request, resp *restful.Response) {
		resp.ResponseWriter.WriteHeader(http.StatusAccepted)
		fmt.Fprintf(resp, "terminating")
		plug.Stop()
	}).Doc("Stop the master").
		Returns(http.StatusAccepted, "if the master will stop", nil).
		Produces(restful.MIME_JSON))
}
Exemple #28
0
// Creates a new HTTP handler that handles all requests to the API of the backend.
func CreateHttpApiHandler(client *client.Client) http.Handler {
	apiHandler := ApiHandler{client}
	wsContainer := restful.NewContainer()

	deployWs := new(restful.WebService)
	deployWs.Path("/api/deploy").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployWs.Route(
		deployWs.POST("").
			To(apiHandler.handleDeploy).
			Reads(AppDeployment{}).
			Writes(AppDeployment{}))
	wsContainer.Add(deployWs)

	microserviceListWs := new(restful.WebService)
	microserviceListWs.Path("/api/microservice").
		Produces(restful.MIME_JSON)
	microserviceListWs.Route(
		microserviceListWs.GET("").
			To(apiHandler.handleGetMicroserviceList).
			Writes(MicroserviceList{}))
	wsContainer.Add(microserviceListWs)

	return wsContainer
}
Exemple #29
0
// InstallDeguggingHandlers registers the HTTP request patterns that serve logs or run commands/containers
func (s *Server) InstallDebuggingHandlers() {
	var ws *restful.WebService

	ws = new(restful.WebService)
	ws.
		Path("/run")
	ws.Route(ws.POST("/{podNamespace}/{podID}/{containerName}").
		To(s.getRun).
		Operation("getRun"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{uid}/{containerName}").
		To(s.getRun).
		Operation("getRun"))
	s.restfulCont.Add(ws)

	ws = new(restful.WebService)
	ws.
		Path("/exec")
	ws.Route(ws.GET("/{podNamespace}/{podID}/{containerName}").
		To(s.getExec).
		Operation("getExec"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{containerName}").
		To(s.getExec).
		Operation("getExec"))
	ws.Route(ws.GET("/{podNamespace}/{podID}/{uid}/{containerName}").
		To(s.getExec).
		Operation("getExec"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{uid}/{containerName}").
		To(s.getExec).
		Operation("getExec"))
	s.restfulCont.Add(ws)

	ws = new(restful.WebService)
	ws.
		Path("/attach")
	ws.Route(ws.GET("/{podNamespace}/{podID}/{containerName}").
		To(s.getAttach).
		Operation("getAttach"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{containerName}").
		To(s.getAttach).
		Operation("getAttach"))
	ws.Route(ws.GET("/{podNamespace}/{podID}/{uid}/{containerName}").
		To(s.getAttach).
		Operation("getAttach"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{uid}/{containerName}").
		To(s.getAttach).
		Operation("getAttach"))
	s.restfulCont.Add(ws)

	ws = new(restful.WebService)
	ws.
		Path("/portForward")
	ws.Route(ws.POST("/{podNamespace}/{podID}").
		To(s.getPortForward).
		Operation("getPortForward"))
	ws.Route(ws.POST("/{podNamespace}/{podID}/{uid}").
		To(s.getPortForward).
		Operation("getPortForward"))
	s.restfulCont.Add(ws)

	ws = new(restful.WebService)
	ws.
		Path("/logs/")
	ws.Route(ws.GET("").
		To(s.getLogs).
		Operation("getLogs"))
	ws.Route(ws.GET("/{logpath:*}").
		To(s.getLogs).
		Operation("getLogs"))
	s.restfulCont.Add(ws)

	ws = new(restful.WebService)
	ws.
		Path("/containerLogs")
	ws.Route(ws.GET("/{podNamespace}/{podID}/{containerName}").
		To(s.getContainerLogs).
		Operation("getContainerLogs"))
	s.restfulCont.Add(ws)

	handlePprofEndpoint := func(req *restful.Request, resp *restful.Response) {
		name := strings.TrimPrefix(req.Request.URL.Path, pprofBasePath)
		switch name {
		case "profile":
			pprof.Profile(resp, req.Request)
		case "symbol":
			pprof.Symbol(resp, req.Request)
		case "cmdline":
			pprof.Cmdline(resp, req.Request)
		default:
			pprof.Index(resp, req.Request)
		}
	}

	// Setup pporf handlers.
	ws = new(restful.WebService).Path(pprofBasePath)
	ws.Route(ws.GET("/{subpath:*}").To(func(req *restful.Request, resp *restful.Response) {
		handlePprofEndpoint(req, resp)
	})).Doc("pprof endpoint")
	s.restfulCont.Add(ws)

	// The /runningpods endpoint is used for testing only.
	ws = new(restful.WebService)
	ws.
		Path("/runningpods/").
		Produces(restful.MIME_JSON)
	ws.Route(ws.GET("").
		To(s.getRunningPods).
		Operation("getRunningPods"))
	s.restfulCont.Add(ws)
}
Exemple #30
0
func setupHandlers(sources []api.Source, sink sinks.ExternalSinkManager, m manager.Manager) http.Handler {
	// Make API handler.
	wsContainer := restful.NewContainer()
	a := v1.NewApi(m)
	a.Register(wsContainer)

	// Validation/Debug handler.
	handleValidate := func(req *restful.Request, resp *restful.Response) {
		err := validate.HandleRequest(resp, sources, sink)
		if err != nil {
			fmt.Fprintf(resp, "%s", err)
		}
	}
	ws := new(restful.WebService).
		Path("/validate").
		Produces("text/plain")
	ws.Route(ws.GET("").To(handleValidate)).
		Doc("get validation information")
	wsContainer.Add(ws)

	// TODO(jnagal): Add a main status page.
	// Redirect root to /validate
	redirectHandler := http.RedirectHandler(validate.ValidatePage, http.StatusTemporaryRedirect)
	handleRoot := func(req *restful.Request, resp *restful.Response) {
		redirectHandler.ServeHTTP(resp, req.Request)
	}
	ws = new(restful.WebService)
	ws.Route(ws.GET("/").To(handleRoot))
	wsContainer.Add(ws)

	handlePprofEndpoint := func(req *restful.Request, resp *restful.Response) {
		name := strings.TrimPrefix(req.Request.URL.Path, pprofBasePath)
		switch name {
		case "profile":
			pprof.Profile(resp, req.Request)
		case "symbol":
			pprof.Symbol(resp, req.Request)
		case "cmdline":
			pprof.Cmdline(resp, req.Request)
		default:
			pprof.Index(resp, req.Request)
		}
	}

	// Setup pporf handlers.
	ws = new(restful.WebService).Path(pprofBasePath)
	ws.Route(ws.GET("/{subpath:*}").To(func(req *restful.Request, resp *restful.Response) {
		handlePprofEndpoint(req, resp)
	})).Doc("pprof endpoint")
	wsContainer.Add(ws)

	return wsContainer
}