Example #1
0
// allNamespaces returns a list of all the available namespaces in the cluster.
func (a *Api) allNamespaces(request *restful.Request, response *restful.Response) {
	cluster := a.manager.GetCluster()
	if cluster == nil {
		response.WriteError(400, errModelNotActivated)
	}
	response.WriteEntity(cluster.GetNamespaces())
}
// namespaceList lists all namespaces for which we have metrics
func (a *HistoricalApi) namespaceList(request *restful.Request, response *restful.Response) {
	if resp, err := a.historicalSource.GetNamespaces(); err != nil {
		response.WriteError(http.StatusInternalServerError, err)
	} else {
		response.WriteEntity(resp)
	}
}
Example #3
0
// getPortForward handles a new restful port forward request. It determines the
// pod name and uid and then calls ServePortForward.
func (s *Server) getPortForward(request *restful.Request, response *restful.Response) {
	params := getRequestParams(request)
	pod, ok := s.host.GetPodByName(params.podNamespace, params.podName)
	if !ok {
		response.WriteError(http.StatusNotFound, fmt.Errorf("pod does not exist"))
		return
	}
	if len(params.podUID) > 0 && pod.UID != params.podUID {
		response.WriteError(http.StatusNotFound, fmt.Errorf("pod not found"))
		return
	}

	redirect, err := s.host.GetPortForward(pod.Name, pod.Namespace, pod.UID)
	if err != nil {
		streaming.WriteError(err, response.ResponseWriter)
		return
	}
	if redirect != nil {
		http.Redirect(response.ResponseWriter, request.Request, redirect.String(), http.StatusFound)
		return
	}

	portforward.ServePortForward(response.ResponseWriter,
		request.Request,
		s.host,
		kubecontainer.GetPodFullName(pod),
		params.podUID,
		s.host.StreamingConnectionIdleTimeout(),
		remotecommand.DefaultStreamCreationTimeout)
}
// processMetricNamesRequest retrieves the available metrics for the object at the specified key.
func (a *HistoricalApi) processMetricNamesRequest(key core.HistoricalKey, response *restful.Response) {
	if resp, err := a.historicalSource.GetMetricNames(key); err != nil {
		response.WriteError(http.StatusInternalServerError, err)
	} else {
		response.WriteEntity(resp)
	}
}
// namespacePodList lists all pods for which we have metrics in a particular namespace
func (a *HistoricalApi) namespacePodList(request *restful.Request, response *restful.Response) {
	if resp, err := a.historicalSource.GetPodsFromNamespace(request.PathParameter("namespace-name")); err != nil {
		response.WriteError(http.StatusInternalServerError, err)
	} else {
		response.WriteEntity(resp)
	}
}
Example #6
0
func (a *Api) getSinks(req *restful.Request, resp *restful.Response) {
	sinkUris := a.manager.SinkUris()
	if sinkUris == nil {
		sinkUris = make(manager.Uris, 0)
	}
	resp.WriteEntity(sinkUris)
}
// getExec handles requests to run a command inside a container.
func (s *Server) getExec(request *restful.Request, response *restful.Response) {
	params := getRequestParams(request)
	pod, ok := s.host.GetPodByName(params.podNamespace, params.podName)
	if !ok {
		response.WriteError(http.StatusNotFound, fmt.Errorf("pod does not exist"))
		return
	}

	podFullName := kubecontainer.GetPodFullName(pod)
	redirect, err := s.host.GetExec(podFullName, params.podUID, params.containerName, params.cmd, params.streamOpts)
	if err != nil {
		response.WriteError(streaming.HTTPStatus(err), err)
		return
	}
	if redirect != nil {
		http.Redirect(response.ResponseWriter, request.Request, redirect.String(), http.StatusFound)
		return
	}

	remotecommand.ServeExec(response.ResponseWriter,
		request.Request,
		s.host,
		podFullName,
		params.podUID,
		params.containerName,
		s.host.StreamingConnectionIdleTimeout(),
		remotecommand.DefaultStreamCreationTimeout,
		remotecommand.SupportedStreamingProtocols)
}
// nodeSystemContainerList lists all system containers on a node for which we have metrics
func (a *HistoricalApi) nodeSystemContainerList(request *restful.Request, response *restful.Response) {
	if resp, err := a.historicalSource.GetSystemContainersFromNode(request.PathParameter("node-name")); err != nil {
		response.WriteError(http.StatusInternalServerError, err)
	} else {
		response.WriteEntity(resp)
	}
}
Example #9
0
// podContainerMetrics returns a metric timeseries for a metric of the Container entity.
// freeContainerMetrics addresses only pod containers, by using the namespace-name/pod-name/container-name path.
func (a *Api) podContainerMetrics(request *restful.Request, response *restful.Response) {
	cluster := a.manager.GetCluster()

	// Get namespace name
	namespace := request.PathParameter("namespace-name")

	// Get pod name
	pod := request.PathParameter("pod-name")

	// Get container name
	container := request.PathParameter("container-name")

	// Get metric name
	metric_name := request.PathParameter("metric-name")

	// Get start time, parse as time.Time
	req_stamp := parseRequestStartParam(request, response)

	timeseries, new_stamp, err := cluster.GetPodContainerMetric(namespace, pod, container, metric_name, req_stamp)
	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		glog.Errorf("unable to get cluster metric: %s", err)
		return
	}
	response.WriteEntity(exportTimeseries(timeseries, new_stamp))
}
Example #10
0
// Handles deploy from file API call.
func (apiHandler *ApiHandler) handleDeployFromFile(request *restful.Request, response *restful.Response) {
	deploymentSpec := new(AppDeploymentFromFileSpec)
	if err := request.ReadEntity(deploymentSpec); err != nil {
		handleInternalError(response, err)
		return
	}

	isDeployed, err := DeployAppFromFile(
		deploymentSpec, CreateObjectFromInfoFn, apiHandler.clientConfig)
	if !isDeployed {
		handleInternalError(response, err)
		return
	}

	errorMessage := ""
	if err != nil {
		errorMessage = err.Error()
	}

	response.WriteHeaderAndEntity(http.StatusCreated, AppDeploymentFromFileResponse{
		Name:    deploymentSpec.Name,
		Content: deploymentSpec.Content,
		Error:   errorMessage,
	})
}
Example #11
0
func (s *server) serveAttach(req *restful.Request, resp *restful.Response) {
	containerID := req.PathParameter("containerID")
	if containerID == "" {
		resp.WriteError(http.StatusBadRequest, errors.New("missing required containerID path parameter"))
		return
	}

	streamOpts, err := remotecommand.NewOptions(req.Request)
	if err != nil {
		resp.WriteError(http.StatusBadRequest, err)
		return
	}

	remotecommand.ServeAttach(
		resp.ResponseWriter,
		req.Request,
		s.runtime,
		"", // unused: podName
		"", // unusued: podUID
		containerID,
		streamOpts,
		s.config.StreamIdleTimeout,
		s.config.StreamCreationTimeout,
		s.config.SupportedProtocols)
}
Example #12
0
// containerPaths returns a list of all the available API paths that are available for a container.
func (a *Api) containerPaths(request *restful.Request, response *restful.Response) {
	entities := []string{
		"metrics/",
		"stats/",
	}
	response.WriteEntity(entities)
}
Example #13
0
func (a *Api) exportMetricsSchema(request *restful.Request, response *restful.Response) {
	result := TimeseriesSchema{}
	for _, label := range sinksApi.CommonLabels() {
		result.CommonLabels = append(result.CommonLabels, LabelDescriptor{
			Key:         label.Key,
			Description: label.Description,
		})
	}
	for _, label := range sinksApi.PodLabels() {
		result.PodLabels = append(result.PodLabels, LabelDescriptor{
			Key:         label.Key,
			Description: label.Description,
		})
	}

	for _, metric := range sinksApi.SupportedStatMetrics() {
		md := MetricDescriptor{
			Name:        metric.Name,
			Description: metric.Description,
			Type:        metric.Type.String(),
			ValueType:   metric.ValueType.String(),
			Units:       metric.Units.String(),
		}
		for _, label := range metric.Labels {
			md.Labels = append(md.Labels, LabelDescriptor{
				Key:         label.Key,
				Description: label.Description,
			})
		}
		result.Metrics = append(result.Metrics, md)
	}
	response.WriteEntity(result)
}
Example #14
0
// nodePaths returns a list of all the available API paths that are available for a node.
func (a *Api) nodePaths(request *restful.Request, response *restful.Response) {
	entities := []string{
		"freecontainers/",
		"metrics/",
	}
	response.WriteEntity(entities)
}
Example #15
0
// namespacePaths returns a list of all the available API paths that are available for a namespace.
func (a *Api) namespacePaths(request *restful.Request, response *restful.Response) {
	entities := []string{
		"pods/",
		"metrics/",
	}
	response.WriteEntity(entities)
}
Example #16
0
// nodePods returns a list of all the available API paths that are available for a node.
func (a *Api) nodePods(request *restful.Request, response *restful.Response) {
	model := a.manager.GetModel()
	if model == nil {
		response.WriteError(400, errModelNotActivated)
	}
	node := request.PathParameter("node-name")
	response.WriteEntity(makeExternalEntityList(model.GetNodePods(node)))
}
Example #17
0
// allFreeContainers returns a list of all the available free containers in the cluster.
func (a *Api) allFreeContainers(request *restful.Request, response *restful.Response) {
	cluster := a.manager.GetCluster()
	if cluster == nil {
		response.WriteError(400, errModelNotActivated)
	}
	node := request.PathParameter("node-name")
	response.WriteEntity(cluster.GetFreeContainers(node))
}
Example #18
0
// allNamespaces returns a list of all the available namespaces in the model.
func (a *Api) allNamespaces(request *restful.Request, response *restful.Response) {
	model := a.manager.GetModel()
	if model == nil {
		response.WriteError(400, errModelNotActivated)
		return
	}
	response.WriteEntity(makeExternalEntityList(model.GetNamespaces()))
}
Example #19
0
// allEntities returns a list of all the top-level paths that are available in the API.
func (a *Api) allEntities(request *restful.Request, response *restful.Response) {
	entities := []string{
		"metrics/",
		"namespaces/",
		"nodes/",
	}
	response.WriteEntity(entities)
}
Example #20
0
// availableMetrics returns a list of available metric names.
// These metric names can be used to extract metrics from the various model entities.
func (a *Api) availableMetrics(request *restful.Request, response *restful.Response) {
	cluster := a.manager.GetCluster()
	if cluster == nil {
		response.WriteError(400, errModelNotActivated)
	}
	result := cluster.GetAvailableMetrics()
	response.WriteEntity(result)
}
Example #21
0
// allPods returns a list of all the available pods in the cluster.
func (a *Api) allPods(request *restful.Request, response *restful.Response) {
	cluster := a.manager.GetCluster()
	if cluster == nil {
		response.WriteError(400, errModelNotActivated)
	}
	namespace := request.PathParameter("namespace-name")
	response.WriteEntity(cluster.GetPods(namespace))
}
Example #22
0
// Handles nodes API call.
func (apiHandler *ApiHandler) handleGetNodes(request *restful.Request, response *restful.Response) {
	result, err := GetNodeList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, result)
}
Example #23
0
// getSpec handles spec requests against the Kubelet.
func (s *Server) getSpec(request *restful.Request, response *restful.Response) {
	info, err := s.host.GetCachedMachineInfo()
	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}
	response.WriteEntity(info)
}
Example #24
0
// Handle node stats API call.
func (apiHandler *ApiHandler) handleGetNodeStats(request *restful.Request, response *restful.Response) {
	name := request.PathParameter("name")
	result, err := GetNodeStats(name)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, result)
}
Example #25
0
// Handles get secrets list API call.
func (apiHandler *ApiHandler) handleGetSecrets(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	result, err := GetSecrets(apiHandler.client, namespace)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusOK, result)
}
Example #26
0
// Handles protocol validation API call.
func (apiHandler *ApiHandler) handleProtocolValidity(request *restful.Request, response *restful.Response) {
	spec := new(ProtocolValiditySpec)
	if err := request.ReadEntity(spec); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, ValidateProtocol(spec))
}
Example #27
0
func (a *Api) nodeMetricsList(request *restful.Request, response *restful.Response) {
	res := v1alpha1.NodeMetricsList{}
	for _, node := range a.metricSink.GetNodes() {
		if m := a.getNodeMetrics(node); m != nil {
			res.Items = append(res.Items, *m)
		}
	}
	response.WriteEntity(&res)
}
// podListMetrics returns a list of metric timeseries for each for the listed nodes
func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response) {
	start, end, err := getStartEndTimeHistorical(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}

	keys := []core.HistoricalKey{}
	if request.PathParameter("pod-id-list") != "" {
		for _, podId := range strings.Split(request.PathParameter("pod-id-list"), ",") {
			key := core.HistoricalKey{
				ObjectType: core.MetricSetTypePod,
				PodId:      podId,
			}
			keys = append(keys, key)
		}
	} else {
		for _, podName := range strings.Split(request.PathParameter("pod-list"), ",") {
			key := core.HistoricalKey{
				ObjectType:    core.MetricSetTypePod,
				NamespaceName: request.PathParameter("namespace-name"),
				PodName:       podName,
			}
			keys = append(keys, key)
		}
	}

	labels, err := getLabels(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}

	metricName := request.PathParameter("metric-name")
	convertedMetricName := convertMetricName(metricName)

	var metrics map[core.HistoricalKey][]core.TimestampedMetricValue
	if labels != nil {
		metrics, err = a.historicalSource.GetLabeledMetric(convertedMetricName, labels, keys, start, end)
	} else {
		metrics, err = a.historicalSource.GetMetric(convertedMetricName, keys, start, end)
	}

	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}

	result := types.MetricResultList{
		Items: make([]types.MetricResult, 0, len(keys)),
	}
	for _, key := range keys {
		result.Items = append(result.Items, exportTimestampedMetricValue(metrics[key]))
	}
	response.PrettyPrint(false)
	response.WriteEntity(result)
}
Example #29
0
// Write marshals the value to byte slice and set the Content-Type Header.
func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error {
	if v == nil {
		resp.WriteHeader(status)
		// do not write a nil representation
		return nil
	}
	resp.WriteHeader(status)
	return msgpack.NewEncoder(resp).Encode(v)
}
Example #30
0
// getPods returns a list of pods bound to the Kubelet and their spec.
func (s *Server) getPods(request *restful.Request, response *restful.Response) {
	pods := s.host.GetPods()
	data, err := encodePods(pods)
	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}
	response.Write(data)
}