func GetAllReplicationControllerName(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string) (returnedNameSlice []string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedNameSlice = nil
			returnedError = err.(error)
		}
	}()

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/"

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	jsonMap, err := restclient.RequestGet(url, headerMap, true)
	if err != nil {
		log.Error(err)
		return nil, err
	} else {
		nameSlice := make([]string, 0)
		for _, item := range jsonMap.(map[string]interface{})["items"].([]interface{}) {
			name, ok := item.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
			if ok {
				nameSlice = append(nameSlice, name)
			}
		}
		return nameSlice, nil
	}
}
Esempio n. 2
0
// @Title get
// @Description get container log in the pod
// @Param namespace path string true "The name of namespace"
// @Param pod path string true "The name of pod"
// @Success 200 {string} {}
// @Failure 404 error reason
// @router /podlog/:namespace/:pod [get]
func (c *PodLogController) Get() {
	namespace := c.GetString(":namespace")
	pod := c.GetString(":pod")

	cloudoneProtocol := beego.AppConfig.String("cloudoneProtocol")
	cloudoneHost := beego.AppConfig.String("cloudoneHost")
	cloudonePort := beego.AppConfig.String("cloudonePort")

	url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort +
		"/api/v1/podlogs/" + namespace + "/" + pod

	tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

	result, err := restclient.RequestGet(url, tokenHeaderMap, true)

	if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
		return
	}

	jsonMap, _ := result.(map[string]interface{})

	if err != nil {
		// Error
		c.Data["json"] = make(map[string]interface{})
		c.Data["json"].(map[string]interface{})["error"] = err.Error()
		c.Ctx.Output.Status = 404
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = make(map[string]interface{})
		c.Data["json"].(map[string]interface{})["logJsonMap"] = jsonMap
		c.ServeJSON()
	}
}
Esempio n. 3
0
func GetAllNamespaceName(kubeApiServerEndPoint string, kubeApiServerToken string) (returnedNameSlice []string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllNamespaceName Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedNameSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/", headerMap, true)
	if err != nil {
		log.Error("Fail to get all namespace name with endpoint: %s, token: %s, error: %s", kubeApiServerEndPoint, kubeApiServerToken, err.Error())
		return nil, err
	}
	jsonMap, _ := result.(map[string]interface{})

	nameSlice := make([]string, 0)
	for _, data := range jsonMap["items"].([]interface{}) {
		name, ok := data.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
		if ok {
			statusJsonMap, _ := data.(map[string]interface{})["status"].(map[string]interface{})
			phase, _ := statusJsonMap["phase"].(string)
			if phase == "Active" {
				nameSlice = append(nameSlice, name)
			}
		}

	}

	return nameSlice, nil
}
Esempio n. 4
0
func GetAllEvent(kubeApiServerEndPoint string, kubeApiServerToken string) (returnedEventSlice []map[string]interface{}, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllEvent Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedEventSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	jsonMap, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/events/", headerMap, true)
	if err != nil {
		log.Error("Fail to get all event with endpoint: %s, token: %s, error: %s", kubeApiServerEndPoint, kubeApiServerToken, err.Error())
		return nil, err
	}

	eventSlice := make([]map[string]interface{}, 0)
	for _, data := range jsonMap.(map[string]interface{})["items"].([]interface{}) {
		value, ok := data.(map[string]interface{})
		if ok {
			eventSlice = append(eventSlice, value)
		}
	}

	return eventSlice, nil
}
func UpdateReplicationControllerSize(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string, size int) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("UpdateReplicationControllerSize Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/" + replicationControllerName + "/"
	result, err := restclient.RequestGet(url, headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Get replication controller information failure where size: %d, endpoint: %s, token: %s, namespace: %s, replicationControllerName: %s, err: %s", size, kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, err.Error())
		return err
	} else {
		jsonMap["spec"].(map[string]interface{})["replicas"] = float64(size)
		_, err := restclient.RequestPut(url, jsonMap, headerMap, true)

		if err != nil {
			return err
		} else {
			return nil
		}
	}
}
Esempio n. 6
0
func (privateRegistry *PrivateRegistry) GetAllImageTag(repositoryName string) ([]string, error) {
	result, err := restclient.RequestGet(privateRegistry.getPrivateRegistryEndpoint()+"/v2/"+repositoryName+"/tags/list", nil, false)
	if err != nil {
		log.Error("Fail to get all image tags with repository %s and private registry: %v, error: %s", repositoryName, privateRegistry, err)
		return nil, err
	}

	jsonMap, _ := result.(map[string]interface{})
	tagJsonSlice, _ := jsonMap["tags"].([]interface{})
	tagSlice := make([]string, 0)
	for _, tagJsonInterface := range tagJsonSlice {
		if tag, ok := tagJsonInterface.(string); ok {
			request, err := http.NewRequest("GET", privateRegistry.getPrivateRegistryEndpoint()+"/v2/"+repositoryName+"/manifests/"+tag, nil)
			if err != nil {
				log.Error(err)
				return nil, err
			}

			// For registry version 2.3 and later
			request.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json")
			response, err := restclient.GetInsecureHTTPSClient().Do(request)
			if err != nil {
				log.Error(err)
				return nil, err
			}
			digest := response.Header.Get("Docker-Content-Digest")

			if len(digest) > 0 {
				tagSlice = append(tagSlice, tag)
			}
		}
	}

	return tagSlice, nil
}
func ResizeReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string, delta int, maximumSize int, minimumSize int) (resized bool, size int, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("ResizeReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			resized = false
			size = -1
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/" + replicationControllerName + "/"
	result, err := restclient.RequestGet(url, headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Get replication controller information failure where delta: %d, endpoint: %s, token: %s, namespace: %s, replicationControllerName: %s, err: %s", delta, kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, err.Error())
		return false, -1, err
	} else {
		replicas, _ := jsonparse.ConvertToInt64(jsonMap["spec"].(map[string]interface{})["replicas"])
		currentSize := int(replicas)
		newSize := currentSize + delta
		if newSize < minimumSize {
			newSize = minimumSize
		}
		if newSize > maximumSize {
			newSize = maximumSize
		}

		if newSize == currentSize {
			return false, currentSize, nil
		}

		jsonMap["spec"].(map[string]interface{})["replicas"] = float64(newSize)
		result, err := restclient.RequestPut(url, jsonMap, headerMap, true)
		resultJsonMap, _ := result.(map[string]interface{})
		if err != nil {
			return false, currentSize, err
		} else {
			replicas, _ := jsonparse.ConvertToInt64(resultJsonMap["spec"].(map[string]interface{})["replicas"])
			return true, int(replicas), nil
		}
	}
}
Esempio n. 8
0
func getContainerMonitorData(urlSlice []string) ([]map[string]interface{}, []error) {
	dataMapSlice := make([]map[string]interface{}, 0)
	errorSlice := make([]error, 0)
	for _, url := range urlSlice {
		result, err := restclient.RequestGet(url, nil, true)
		jsonMap, _ := result.(map[string]interface{})
		if err != nil {
			dataMapSlice = append(dataMapSlice, nil)
			errorSlice = append(errorSlice, err)
		} else {
			dataMapSlice = append(dataMapSlice, jsonMap)
			errorSlice = append(errorSlice, nil)
		}
	}

	return dataMapSlice, errorSlice
}
Esempio n. 9
0
func GetPodLog(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, podName string) (returnedLog map[string]interface{}, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetPodLog Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedLog = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/"+podName, headerMap, false)
	if err != nil {
		log.Error("Fail to get pod information with namespace %s pod %s endpoint: %s, token: %s, error: %s", namespace, podName, kubeApiServerEndPoint, kubeApiServerToken, err.Error())
		return nil, err
	}

	containerNameSlice := make([]string, 0)

	jsonMap, _ := result.(map[string]interface{})
	specJsonMap, _ := jsonMap["spec"].(map[string]interface{})
	containerSlice, _ := specJsonMap["containers"].([]interface{})
	for _, container := range containerSlice {
		containerJsonMap, _ := container.(map[string]interface{})
		containerName, ok := containerJsonMap["name"].(string)
		if ok {
			containerNameSlice = append(containerNameSlice, containerName)
		}
	}

	logJsonMap := make(map[string]interface{})
	for _, containerName := range containerNameSlice {
		byteSlice, err := restclient.RequestGetByteSliceResult(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/"+podName+"/log?container="+containerName, headerMap)
		if err != nil {
			log.Error("Fail to get log with namespace %s pod %s container %s endpoint: %s, token: %s, error: %s", namespace, podName, containerName, kubeApiServerEndPoint, kubeApiServerToken, err.Error())
			return nil, err
		} else {
			logJsonMap[containerName] = string(byteSlice)
		}
	}

	return logJsonMap, nil
}
Esempio n. 10
0
func (privateRegistry *PrivateRegistry) GetAllRepository() ([]string, error) {
	result, err := restclient.RequestGet(privateRegistry.getPrivateRegistryEndpoint()+"/v2/_catalog", nil, false)
	if err != nil {
		log.Error("Fail to get all repository with private registry: %v, error: %s", privateRegistry, err)
		return nil, err
	}

	jsonMap, _ := result.(map[string]interface{})
	repositoryJsonSlice, _ := jsonMap["repositories"].([]interface{})
	repositorySlice := make([]string, 0)
	for _, repositoryJsonInterface := range repositoryJsonSlice {
		if repository, ok := repositoryJsonInterface.(string); ok {
			repositorySlice = append(repositorySlice, repository)
		}
	}

	return repositorySlice, nil
}
Esempio n. 11
0
func ExistReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedExist bool, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("ExistReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedExist = false
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	_, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/replicationcontrollers/"+replicationControllerName, headerMap, true)
	if err != nil {
		log.Error("Fail to detect replication controller existence with endpoint: %s, token: %s, namespace: %s, replication controller name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, err.Error())
		return false, err
	} else {
		return true, nil
	}
}
Esempio n. 12
0
func GetReplicationControllerNameFromSelector(kubeApiServerEndPoint, kubeApiServerToken, namespace string, targetSelectorName string) (returnedReplicationControllerNameSlice []string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetReplicationControllerNameFromSelector Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedReplicationControllerNameSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/replicationcontrollers/", headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Fail to get all replication controller with endpoint: %s, token: %s, namespace: %s, selector name: %s",
			kubeApiServerEndPoint, kubeApiServerToken, namespace, targetSelectorName)
		return nil, err
	}

	nameSlice := make([]string, 0)
	for _, item := range jsonMap["items"].([]interface{}) {
		selector, ok := item.(map[string]interface{})["spec"].(map[string]interface{})["selector"].(map[string]interface{})
		if ok {
			selectorName, ok := selector["name"].(string)
			if ok {
				if targetSelectorName == selectorName {
					name, ok := item.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
					if ok {
						nameSlice = append(nameSlice, name)
					}
				}
			}
		}
	}

	return nameSlice, nil
}
Esempio n. 13
0
func GetAllPodBelongToReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedPodSlice []Pod, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllPodBelongToReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedPodSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/", headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Fail to get all pod inofrmation with endpoint %s, token: %s, namespace: %s, replication controller name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, err.Error())
		return nil, err
	}

	return GetAllPodBelongToReplicationControllerFromData(replicationControllerName, jsonMap)
}
Esempio n. 14
0
func GetAllPodNameBelongToReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedNameSlice []string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllPodNameBelongToReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedNameSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/", headerMap, true)
	if err != nil {
		log.Error("Fail to get replication controller inofrmation with endpoint %s, token: %s, namespace: %s, replication controller name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, err.Error())
		return nil, err
	}
	jsonMap, _ := result.(map[string]interface{})

	generateName := replicationControllerName + "-"
	podNameSlice := make([]string, 0)
	for _, data := range jsonMap["items"].([]interface{}) {
		generateNameField, _ := data.(map[string]interface{})["metadata"].(map[string]interface{})["generateName"].(string)
		nameField, nameFieldOk := data.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
		if generateName == generateNameField {
			if nameFieldOk {
				podNameSlice = append(podNameSlice, nameField)
			}
		} else if replicationControllerName == nameField {
			if nameFieldOk {
				podNameSlice = append(podNameSlice, nameField)
			}
		}
	}

	return podNameSlice, nil
}
Esempio n. 15
0
func (smsNexmo *SMSNexmo) SendSMSNexmo(smsNexmoURL string, smsNexmoAPIKey string, smsNexmoAPISecret string,
	sender string, receiverNumberSlice []string, text string) error {

	hasError := false
	buffer := bytes.Buffer{}
	for _, receiverNumber := range receiverNumberSlice {
		convertedURL, err := url.Parse(smsNexmoURL)
		if err != nil {
			log.Error("Parse url %s error %s", smsNexmoURL, err)
			return err
		}

		parameters := url.Values{}
		parameters.Add("api_key", smsNexmoAPIKey)
		parameters.Add("api_secret", smsNexmoAPISecret)
		parameters.Add("from", sender)
		parameters.Add("to", receiverNumber)
		parameters.Add("text", text)
		convertedURL.RawQuery = parameters.Encode()

		result, err := restclient.RequestGet(convertedURL.String(), nil, true)
		bodyJsonMap, _ := result.(map[string]interface{})
		if err != nil {
			log.Error("Request url %s error bodyJsonMap %s error %s", convertedURL.String(), bodyJsonMap, err)
			hasError = true
			buffer.WriteString(err.Error())
		} else {
			log.Info("SMS send to %s, bodyJsonMap %s", convertedURL.String(), bodyJsonMap)
		}
	}

	if hasError {
		return errors.New(buffer.String())
	} else {
		return nil
	}
}
Esempio n. 16
0
func UpdateReplicationControllerWithJson(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string, bodyJsonMap map[string]interface{}) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("UpdateReplicationControllerWithJson Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/" + replicationControllerName
	result, err := restclient.RequestGet(url, headerMap, true)
	if err != nil {
		log.Error(err)
		return err
	}

	jsonMap, _ := result.(map[string]interface{})

	metadataJsonMap, _ := jsonMap["metadata"].(map[string]interface{})
	resourceVersion, _ := metadataJsonMap["resourceVersion"].(string)

	// Update requires the resoruce version
	bodyJsonMap["metadata"].(map[string]interface{})["resourceVersion"] = resourceVersion

	url = kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/" + replicationControllerName
	_, err = restclient.RequestPut(url, bodyJsonMap, headerMap, true)

	if err != nil {
		log.Error(err)
		return err
	} else {
		return nil
	}
}
Esempio n. 17
0
func UpdateServiceWithJson(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, serviceName string, bodyJsonMap map[string]interface{}) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("CreateServiceWithJson Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/services/" + serviceName
	result, err := restclient.RequestGet(url, headerMap, true)
	jsonMap, _ := result.(map[string]interface{})

	metadataJsonMap, _ := jsonMap["metadata"].(map[string]interface{})
	resourceVersion, _ := metadataJsonMap["resourceVersion"].(string)

	specJsonMap, _ := jsonMap["spec"].(map[string]interface{})
	clusterIP, _ := specJsonMap["clusterIP"].(string)

	// Update requires the resoruce version and cluster ip
	bodyJsonMap["metadata"].(map[string]interface{})["resourceVersion"] = resourceVersion
	bodyJsonMap["spec"].(map[string]interface{})["clusterIP"] = clusterIP

	url = kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/services/" + serviceName
	_, err = restclient.RequestPut(url, bodyJsonMap, headerMap, true)

	if err != nil {
		log.Error(err)
		return err
	} else {
		return nil
	}
}
Esempio n. 18
0
func (c *PodLogController) Get() {
	c.TplName = "inventory/replicationcontroller/pod_log.html"
	guimessage := guimessagedisplay.GetGUIMessage(c)

	// Authorization for web page display
	c.Data["layoutMenu"] = c.GetSession("layoutMenu")

	cloudoneProtocol := beego.AppConfig.String("cloudoneProtocol")
	cloudoneHost := beego.AppConfig.String("cloudoneHost")
	cloudonePort := beego.AppConfig.String("cloudonePort")

	namespace := c.GetString("namespace")
	pod := c.GetString("pod")

	url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort +
		"/api/v1/pods/" + namespace + "/" + pod + "/logs"

	tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

	result, err := restclient.RequestGet(url, tokenHeaderMap, true)

	if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
		return
	}

	jsonMap, _ := result.(map[string]interface{})

	if err != nil {
		// Error
		guimessage.AddDanger(guimessagedisplay.GetErrorMessage(err))
	} else {
		c.Data["logJsonMap"] = jsonMap
	}

	guimessage.OutputMessage(c.Data)
}
Esempio n. 19
0
func GetAllService(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string) (returnedServiceSlice []Service, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllService Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedServiceSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/services/"
	result, err := restclient.RequestGet(url, headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		return nil, err
	} else {
		serviceSlice := make([]Service, 0)
		for _, item := range jsonMap["items"].([]interface{}) {
			service := Service{}
			service.Name, _ = item.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
			service.Namespace, _ = item.(map[string]interface{})["metadata"].(map[string]interface{})["namespace"].(string)
			service.LabelMap, _ = item.(map[string]interface{})["metadata"].(map[string]interface{})["labels"].(map[string]interface{})
			service.ClusterIP, _ = item.(map[string]interface{})["spec"].(map[string]interface{})["clusterIP"].(string)
			service.Selector, _ = item.(map[string]interface{})["spec"].(map[string]interface{})["selector"].(map[string]interface{})
			service.SessionAffinity, _ = item.(map[string]interface{})["spec"].(map[string]interface{})["sessionAffinity"].(string)
			portSlice := item.(map[string]interface{})["spec"].(map[string]interface{})["ports"].([]interface{})
			servicePortSlice := make([]ServicePort, 0)
			for _, port := range portSlice {
				servicePort := ServicePort{}
				servicePort.Name, _ = port.(map[string]interface{})["name"].(string)
				servicePort.Protocol, _ = port.(map[string]interface{})["protocol"].(string)
				unknownTypePort := port.(map[string]interface{})["port"]
				switch knowTypePort := unknownTypePort.(type) {
				case json.Number:
					portInt64, _ := knowTypePort.Int64()
					servicePort.Port = int(portInt64)
				case string:
					servicePort.Port, _ = strconv.Atoi(knowTypePort)
				case int64:
					servicePort.Port = int(knowTypePort)
				case float64:
					servicePort.Port = int(knowTypePort)
				}
				unknownTypeTargetPort := port.(map[string]interface{})["targetPort"]
				switch knowTypeTargetPort := unknownTypeTargetPort.(type) {
				case json.Number:
					servicePort.TargetPort = knowTypeTargetPort.String()
				case string:
					servicePort.TargetPort = knowTypeTargetPort
				case int64:
					servicePort.TargetPort = strconv.FormatInt(knowTypeTargetPort, 10)
				case float64:
					servicePort.TargetPort = strconv.FormatFloat(knowTypeTargetPort, 'f', -1, 64)
				}
				unknownTypeNodePort := port.(map[string]interface{})["nodePort"]
				switch knowTypeNodePort := unknownTypeNodePort.(type) {
				case json.Number:
					nodePortInt64, _ := knowTypeNodePort.Int64()
					servicePort.NodePort = int(nodePortInt64)
				case string:
					servicePort.NodePort, _ = strconv.Atoi(knowTypeNodePort)
				case int64:
					servicePort.NodePort = int(knowTypeNodePort)
				case float64:
					servicePort.NodePort = int(knowTypeNodePort)
				default:
					servicePort.NodePort = -1
				}
				servicePortSlice = append(servicePortSlice, servicePort)
			}
			service.PortSlice = servicePortSlice
			serviceSlice = append(serviceSlice, service)
		}
		return serviceSlice, nil
	}
}
func GetAllReplicationControllerAndRelatedPodSlice(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string) (
	returnedReplicationControllerAndRelatedPodSlice []ReplicationControllerAndRelatedPod, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedReplicationControllerAndRelatedPodSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/replicationcontrollers/", headerMap, true)
	replicationControllerJsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Fail to get all replication controller inofrmation with endpoint %s, token: %s, namespace: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, err.Error())
		return nil, err
	} else {
		result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/", headerMap, true)
		podJsonMap, _ := result.(map[string]interface{})
		if err != nil {
			log.Error("Fail to get all pod information with endpoint %s, token: %s, namespace: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, err.Error())
			return nil, err
		} else {
			replicationControllerAndRelatedPodSlice := make([]ReplicationControllerAndRelatedPod, 0)

			itemSlice, _ := replicationControllerJsonMap["items"].([]interface{})
			for _, item := range itemSlice {
				name, _ := item.(map[string]interface{})["metadata"].(map[string]interface{})["name"].(string)
				namespace, _ := item.(map[string]interface{})["metadata"].(map[string]interface{})["namespace"].(string)
				replicaAmount, _ := jsonparse.ConvertToInt64(item.(map[string]interface{})["spec"].(map[string]interface{})["replicas"])
				aliveReplicaAmount, _ := jsonparse.ConvertToInt64(item.(map[string]interface{})["status"].(map[string]interface{})["replicas"])
				selectorField, _ := item.(map[string]interface{})["spec"].(map[string]interface{})["selector"].(map[string]interface{})
				labelField, _ := item.(map[string]interface{})["metadata"].(map[string]interface{})["labels"].(map[string]interface{})

				selectorMap := make(map[string]string)
				for key, value := range selectorField {
					selectorMap[key], _ = value.(string)
				}

				labelMap := make(map[string]string)
				for key, value := range labelField {
					labelMap[key], _ = value.(string)
				}

				podSlice, _ := GetAllPodBelongToReplicationControllerFromData(name, podJsonMap)
				replicationControllerAndRelatedPod := ReplicationControllerAndRelatedPod{
					name,
					namespace,
					int(replicaAmount),
					int(aliveReplicaAmount),
					selectorMap,
					labelMap,
					podSlice,
				}

				replicationControllerAndRelatedPodSlice = append(replicationControllerAndRelatedPodSlice, replicationControllerAndRelatedPod)
			}

			return replicationControllerAndRelatedPodSlice, nil
		}
	}
}
Esempio n. 21
0
func MonitorPod(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, podName string) (returnedPodMetric *PodMetric, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("MonitorPod Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedPodMetric = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/"+podName+"/", headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Fail to get pod inofrmation with endpoint: %s, token: %s, namespace: %s, pod name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, podName, err.Error())
		return nil, err
	}
	urlSlice, containerNameSlice, kubeletHost := getContainerLocationFromPodInformation(jsonMap)
	jsonMap["container_url_slice"] = urlSlice
	dataSlice, errorSlice := getContainerMonitorData(urlSlice)
	jsonMap["container_monitor_data_slice"] = dataSlice
	jsonMap["container_monitor_error_slice"] = errorSlice

	podMetric := &PodMetric{}
	podMetric.KubeletHost = kubeletHost
	podMetric.Namespace = namespace
	podMetric.PodName = podName
	podMetric.ValidContainerSlice = make([]bool, len(dataSlice))
	podMetric.ContainerMetricSlice = make([]ContainerMetric, len(dataSlice))
	errorMessage := "The following index of container has error: "
	errorHappened := false
	for index, data := range dataSlice {
		if errorSlice[index] != nil {
			errorMessage = errorMessage + errorSlice[index].Error()
			podMetric.ValidContainerSlice[index] = false
			errorHappened = true
		} else {
			podMetric.ValidContainerSlice[index] = true
			podMetric.ContainerMetricSlice[index] = ContainerMetric{}
			podMetric.ContainerMetricSlice[index].ContainerName = containerNameSlice[index]
			length := len(data["stats"].([]interface{}))
			// CPU
			podMetric.ContainerMetricSlice[index].CpuUsageTotalSlice = make([]int64, length)
			// Memory
			podMetric.ContainerMetricSlice[index].MemoryUsageSlice = make([]int64, length)
			// Disk I/O
			podMetric.ContainerMetricSlice[index].DiskIOServiceBytesStatsTotalSlice = make([]int64, length)
			podMetric.ContainerMetricSlice[index].DiskIOServicedStatsTotalSlice = make([]int64, length)
			// Network
			podMetric.ContainerMetricSlice[index].NetworkRXBytesSlice = make([]int64, length)
			podMetric.ContainerMetricSlice[index].NetworkTXBytesSlice = make([]int64, length)
			podMetric.ContainerMetricSlice[index].NetworkRXPacketsSlice = make([]int64, length)
			podMetric.ContainerMetricSlice[index].NetworkTXPacketsSlice = make([]int64, length)
			for i := 0; i < length; i++ {
				// CPU
				podMetric.ContainerMetricSlice[index].CpuUsageTotalSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["cpu"].(map[string]interface{})["usage"].((map[string]interface{}))["total"])
				// Memory
				podMetric.ContainerMetricSlice[index].MemoryUsageSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["memory"].(map[string]interface{})["usage"])
				// Disk I/O
				ioServiceBytesSlice := data["stats"].([]interface{})[i].(map[string]interface{})["diskio"].(map[string]interface{})["io_service_bytes"]
				if ioServiceBytesSlice != nil {
					for _, ioServiceBytes := range ioServiceBytesSlice.([]interface{}) {
						value, _ := jsonparse.ConvertToInt64(ioServiceBytes.(map[string]interface{})["stats"].(map[string]interface{})["Total"])
						podMetric.ContainerMetricSlice[index].DiskIOServiceBytesStatsTotalSlice[i] += value
					}
				}
				ioServicedSlice := data["stats"].([]interface{})[i].(map[string]interface{})["diskio"].(map[string]interface{})["io_serviced"]
				if ioServicedSlice != nil {
					for _, ioServiced := range ioServicedSlice.([]interface{}) {
						value, _ := jsonparse.ConvertToInt64(ioServiced.(map[string]interface{})["stats"].(map[string]interface{})["Total"])
						podMetric.ContainerMetricSlice[index].DiskIOServicedStatsTotalSlice[i] += value
					}
				}
				// Network
				podMetric.ContainerMetricSlice[index].NetworkRXBytesSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["rx_bytes"])
				podMetric.ContainerMetricSlice[index].NetworkTXBytesSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["tx_bytes"])
				podMetric.ContainerMetricSlice[index].NetworkRXPacketsSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["rx_packets"])
				podMetric.ContainerMetricSlice[index].NetworkTXPacketsSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["tx_packets"])
			}
		}
	}

	if errorHappened {
		log.Error("Fail to get all container inofrmation with endpoint %s, token: %s, namespace: %s, pod name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, podName, errorMessage)
		return podMetric, errors.New(errorMessage)
	} else {
		return podMetric, nil
	}
}
Esempio n. 22
0
func MonitorNode(kubeApiServerEndPoint string, kubeApiServerToken string) (returnedNodeMetricSlice []NodeMetric, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("MonitorNode Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedNodeMetricSlice = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/nodes", headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		log.Error("Fail to get node inofrmation with endpoint: %s, token: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, err.Error())
		return nil, err
	}
	urlSlice, addressSlice := getNodeLocationFromNodeInformation(jsonMap)
	dataSlice, errorSlice := getNodeMonitorData(urlSlice)

	nodeAmount := len(dataSlice)
	nodeMetricSlice := make([]NodeMetric, nodeAmount)
	errorMessage := "The following index of container has error: "
	errorHappened := false
	for index, data := range dataSlice {
		if errorSlice[index] != nil {
			errorMessage = errorMessage + errorSlice[index].Error()
			nodeMetricSlice[index].Valid = false
			nodeMetricSlice[index].KubeletHost = addressSlice[index]
			errorHappened = true
		} else {
			nodeMetricSlice[index].Valid = true
			nodeMetricSlice[index].KubeletHost = addressSlice[index]
			length := len(data["stats"].([]interface{}))
			// CPU
			nodeMetricSlice[index].CpuUsageTotalSlice = make([]int64, length)
			// Memory
			nodeMetricSlice[index].MemoryUsageSlice = make([]int64, length)
			// Disk I/O
			nodeMetricSlice[index].DiskIOServiceBytesStatsTotalSlice = make([]int64, length)
			nodeMetricSlice[index].DiskIOServicedStatsTotalSlice = make([]int64, length)
			// Network
			nodeMetricSlice[index].NetworkRXBytesSlice = make([]int64, length)
			nodeMetricSlice[index].NetworkTXBytesSlice = make([]int64, length)
			nodeMetricSlice[index].NetworkRXPacketsSlice = make([]int64, length)
			nodeMetricSlice[index].NetworkTXPacketsSlice = make([]int64, length)
			for i := 0; i < length; i++ {
				// CPU
				nodeMetricSlice[index].CpuUsageTotalSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["cpu"].(map[string]interface{})["usage"].((map[string]interface{}))["total"])
				// Memory
				nodeMetricSlice[index].MemoryUsageSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["memory"].(map[string]interface{})["usage"])
				// Disk I/O
				ioServiceBytesSlice := data["stats"].([]interface{})[i].(map[string]interface{})["diskio"].(map[string]interface{})["io_service_bytes"].([]interface{})
				for _, ioServiceBytes := range ioServiceBytesSlice {
					value, _ := jsonparse.ConvertToInt64(ioServiceBytes.(map[string]interface{})["stats"].(map[string]interface{})["Total"])
					nodeMetricSlice[index].DiskIOServiceBytesStatsTotalSlice[i] += value
				}
				ioServicedSlice := data["stats"].([]interface{})[i].(map[string]interface{})["diskio"].(map[string]interface{})["io_serviced"].([]interface{})
				for _, ioServiced := range ioServicedSlice {
					value, _ := jsonparse.ConvertToInt64(ioServiced.(map[string]interface{})["stats"].(map[string]interface{})["Total"])
					nodeMetricSlice[index].DiskIOServicedStatsTotalSlice[i] += value
				}
				// Network
				nodeMetricSlice[index].NetworkRXBytesSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["rx_bytes"])
				nodeMetricSlice[index].NetworkTXBytesSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["tx_bytes"])
				nodeMetricSlice[index].NetworkRXPacketsSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["rx_packets"])
				nodeMetricSlice[index].NetworkTXPacketsSlice[i], _ = jsonparse.ConvertToInt64(data["stats"].([]interface{})[i].(map[string]interface{})["network"].(map[string]interface{})["tx_packets"])
			}
		}
	}

	if errorHappened {
		log.Error("Fail to get all node inofrmation with endpoint %s, token: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, errorMessage)
		return nodeMetricSlice, nil
	} else {
		return nodeMetricSlice, nil
	}
}
func RecordHistoricalPod(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string, podName string) (returnedPodContainerRecordSlice []map[string]interface{}, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("RecordHistoricalPod Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedPodContainerRecordSlice = nil
			returnedError = err.(error)
		}
	}()

	podContainerRecordSlice := make([]map[string]interface{}, 0)

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	result, err := restclient.RequestGet(kubeApiServerEndPoint+"/api/v1/namespaces/"+namespace+"/pods/"+podName+"/", headerMap, true)
	if err != nil {
		log.Error("Fail to get pod inofrmation with endpoint %s, token: %s, namespace: %s, pod name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, podName, err.Error())
		return nil, err
	}
	jsonMap, _ := result.(map[string]interface{})

	errorBuffer := bytes.Buffer{}
	errorBuffer.WriteString("The following container has error: ")
	errorHappened := false

	kubeletHost, _ := jsonMap["status"].(map[string]interface{})["hostIP"].(string)
	uid, _ := jsonMap["metadata"].(map[string]interface{})["uid"].(string)
	containerSlice, _ := jsonMap["spec"].(map[string]interface{})["containers"].([]interface{})
	for _, container := range containerSlice {
		containerName, _ := container.(map[string]interface{})["name"].(string)
		url := "https://" + kubeletHost + ":10250/stats/" + namespace + "/" + podName + "/" + uid + "/" + containerName
		result, err := restclient.RequestGet(url, nil, true)
		containerJsonMap, _ := result.(map[string]interface{})
		if err != nil {
			errorHappened = true
			log.Error("Request to url %s error %s", url, err)
			errorBuffer.WriteString("Request to url " + url + " error " + err.Error())
		} else {
			// ElasticSearch doesn't allow to use character '.' in the field name so it should be replaced with '_'
			if containerJsonMap["spec"].(map[string]interface{})["labels"] != nil {
				for key, value := range containerJsonMap["spec"].(map[string]interface{})["labels"].(map[string]interface{}) {
					if strings.Contains(key, ".") {
						newKey := strings.Replace(key, ".", "_", -1)
						containerJsonMap["spec"].(map[string]interface{})["labels"].(map[string]interface{})[newKey] = value
						delete(containerJsonMap["spec"].(map[string]interface{})["labels"].(map[string]interface{}), key)
					}
				}
			}

			// Historical data
			containerRecordSlice, err := splitHistoricalDataIntoSecondBased(namespace, replicationControllerName,
				podName, containerName, containerJsonMap)
			if err != nil {
				errorHappened = true
				log.Error("Save container record %s error %s", containerJsonMap, err)
				errorBuffer.WriteString("Save container record  " + containerName + " error " + err.Error())
			} else {
				podContainerRecordSlice = append(podContainerRecordSlice, containerRecordSlice...)
			}
		}
	}

	if errorHappened {
		log.Error("Fail to get all container inofrmation with endpoint %s, token: %s, namespace: %s, pod name: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, podName, errorBuffer.String())
		return nil, errors.New(errorBuffer.String())
	} else {
		return podContainerRecordSlice, nil
	}
}
Esempio n. 24
0
// @Title get
// @Description get historical container data of the replication controller
// @Param replicationController path string true "The name of replication controller or All"
// @Param from query string true "from (format: 01/02/2006 15:04 PM)"
// @Param to query string true "to (format: 01/02/2006 15:04 PM)"
// @Success 200 {string} {}
// @Failure 404 error reason
// @router /:replicationController [get]
func (c *DataController) Get() {
	replicationControllerName := c.GetString(":replicationController")
	fromText := c.GetString("from")
	toText := c.GetString("to")

	cloudoneAnalysisProtocol := beego.AppConfig.String("cloudoneAnalysisProtocol")
	cloudoneAnalysisHost := beego.AppConfig.String("cloudoneAnalysisHost")
	cloudoneAnalysisPort := beego.AppConfig.String("cloudoneAnalysisPort")

	namespaces, _ := c.GetSession("namespace").(string)
	timeZoneOffset, _ := c.GetSession("timeZoneOffset").(int)

	//current := time.Now()
	//_, serverTimeZoneOffsetInSecond := current.Zone()

	from, err := time.Parse("01/02/2006 15:04 PM", fromText)
	if err != nil {
		// Error
		errorJsonMap := make(map[string]interface{})
		errorJsonMap["warning"] = "From time is not selected."
		c.Data["json"] = errorJsonMap
		c.ServeJSON()
		return
		/*
			from = current.Add(-1 * time.Hour)
			// Convert to UTC
			// Offset server time zone
			from = from.Add(-1 * time.Second * time.Duration(serverTimeZoneOffsetInSecond))
			// Offset browser time zone since time from browser doesn't contain time zone
			from = from.Add(time.Minute * time.Duration(timeZoneOffset))
		*/
	} else {
		// Convert to UTC
		// Offset browser time zone since time from browser doesn't contain time zone
		from = from.Add(time.Minute * time.Duration(timeZoneOffset))
	}

	fromInRFC3339Nano := from.Format(time.RFC3339Nano)

	to, err := time.Parse("01/02/2006 15:04 PM", toText)
	if err != nil {
		// Error
		errorJsonMap := make(map[string]interface{})
		errorJsonMap["warning"] = "To time is not selected."
		c.Data["json"] = errorJsonMap
		c.ServeJSON()
		return
		/*
			to = current
			// Convert to UTC
			// Offset server time zone
			to.Add(-1 * time.Second * time.Duration(serverTimeZoneOffsetInSecond))
			// Offset browser time zone since time from browser doesn't contain time zone
			to = to.Add(time.Minute * time.Duration(timeZoneOffset))
		*/
	} else {
		// Convert to UTC
		// Offset browser time zone since time from browser doesn't contain time zone
		to = to.Add(time.Minute * time.Duration(timeZoneOffset))
	}

	toInRFC3339Nano := to.Format(time.RFC3339Nano)

	// Make sure from is before to
	if from.Before(to) == false {
		// Error
		errorJsonMap := make(map[string]interface{})
		errorJsonMap["warning"] = "From need to be before to."
		c.Data["json"] = errorJsonMap
		c.ServeJSON()
		return
	}

	allHistoricalReplicationControllerMetricJsonMap := make(map[string]interface{})
	if replicationControllerName != "" && replicationControllerName != allKeyword {

		encodingUrl, _ := url.Parse(cloudoneAnalysisProtocol + "://" + cloudoneAnalysisHost + ":" + cloudoneAnalysisPort +
			"/api/v1/historicalreplicationcontrollermetrics/" + namespaces + "/" + replicationControllerName)
		parameters := url.Values{}
		parameters.Add("from", fromInRFC3339Nano)
		parameters.Add("to", toInRFC3339Nano)
		parameters.Add("aggregationAmount", strconv.Itoa(aggregationAmount))
		encodingUrl.RawQuery = parameters.Encode()

		tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

		result, err := restclient.RequestGet(encodingUrl.String(), tokenHeaderMap, true)

		if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
			return
		}

		historicalReplicationControllerMetricJsonMap, ok := result.(map[string]interface{})
		if err != nil || ok == false {
			// Error
			errorJsonMap := make(map[string]interface{})
			errorJsonMap["error"] = err.Error()
			c.Data["json"] = errorJsonMap
			c.ServeJSON()
			return
		}
		allHistoricalReplicationControllerMetricJsonMap[replicationControllerName] = historicalReplicationControllerMetricJsonMap
	} else {
		encodingUrl, _ := url.Parse(cloudoneAnalysisProtocol + "://" + cloudoneAnalysisHost + ":" + cloudoneAnalysisPort +
			"/api/v1/historicalreplicationcontrollermetrics/" + namespaces)
		parameters := url.Values{}
		parameters.Add("from", fromInRFC3339Nano)
		parameters.Add("to", toInRFC3339Nano)
		parameters.Add("aggregationAmount", strconv.Itoa(aggregationAmount))
		encodingUrl.RawQuery = parameters.Encode()

		tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

		result, err := restclient.RequestGet(encodingUrl.String(), tokenHeaderMap, true)

		if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
			return
		}

		var ok bool
		allHistoricalReplicationControllerMetricJsonMap, ok = result.(map[string]interface{})
		if err != nil || ok == false {
			// Error
			errorJsonMap := make(map[string]interface{})
			errorJsonMap["error"] = err.Error()
			c.Data["json"] = errorJsonMap
			c.ServeJSON()
			return
		}
	}

	// At least two points to draw a line
	// Filtered out those less than 2
	filterHistoricalReplicationControllerMetricJsonMap := make(map[string]interface{})
	for key, historicalReplicationControllerMetricJsonMap := range allHistoricalReplicationControllerMetricJsonMap {
		timestampSlice, _ := historicalReplicationControllerMetricJsonMap.(map[string]interface{})["timestamp"].([]interface{})
		resultAmount := len(timestampSlice)
		if resultAmount >= 2 {
			filterHistoricalReplicationControllerMetricJsonMap[key] = historicalReplicationControllerMetricJsonMap
		}
	}

	// No data to show
	if len(filterHistoricalReplicationControllerMetricJsonMap) == 0 {
		// Error
		errorJsonMap := make(map[string]interface{})
		errorJsonMap["error"] = "Insufficient data"
		c.Data["json"] = errorJsonMap
		c.ServeJSON()
		return
	}

	// Due to boundary (start + end), it may be aggregationAmount or aggregationAmount + 1 for different replication controller metrics.
	// If the covered range has no data, it may be less. Force to use the smallest one to align.
	smallestResultAmount := aggregationAmount
	for _, historicalReplicationControllerMetricJsonMap := range filterHistoricalReplicationControllerMetricJsonMap {
		timestampSlice, _ := historicalReplicationControllerMetricJsonMap.(map[string]interface{})["timestamp"].([]interface{})
		resultAmount := len(timestampSlice)
		if resultAmount < smallestResultAmount {
			smallestResultAmount = resultAmount
		}
	}

	resultAmount := smallestResultAmount
	differenceAmount := resultAmount - 1

	// CPU usage total
	cpuUsageTotalJsonMap := make(map[string]interface{})
	cpuUsageTotalJsonMap["metadata"] = make(map[string]interface{})
	cpuUsageTotalJsonMap["metadata"].(map[string]interface{})["title"] = "CPU (ms/1s)"
	cpuUsageTotalJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	cpuUsageTotalJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		cpuUsageTotalJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		cpuUsageTotalJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Memory usage
	memoryUsageJsonMap := make(map[string]interface{})
	memoryUsageJsonMap["metadata"] = make(map[string]interface{})
	memoryUsageJsonMap["metadata"].(map[string]interface{})["title"] = "Memory(MB)"
	memoryUsageJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	memoryUsageJsonMap["data"] = make([]interface{}, resultAmount)
	for i := 0; i < resultAmount; i++ {
		memoryUsageJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		memoryUsageJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Disk I/O byte
	diskIOServiceBytesStatsJsonMap := make(map[string]interface{})
	diskIOServiceBytesStatsJsonMap["metadata"] = make(map[string]interface{})
	diskIOServiceBytesStatsJsonMap["metadata"].(map[string]interface{})["title"] = "Disk I/O (Byte/s)"
	diskIOServiceBytesStatsJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	diskIOServiceBytesStatsJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		diskIOServiceBytesStatsJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		diskIOServiceBytesStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Disk I/O count
	diskIOServicedStatsJsonMap := make(map[string]interface{})
	diskIOServicedStatsJsonMap["metadata"] = make(map[string]interface{})
	diskIOServicedStatsJsonMap["metadata"].(map[string]interface{})["title"] = "Disk I/O (count/s)"
	diskIOServicedStatsJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	diskIOServicedStatsJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		diskIOServicedStatsJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		diskIOServicedStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Network RX Byte
	networkRXBytesJsonMap := make(map[string]interface{})
	networkRXBytesJsonMap["metadata"] = make(map[string]interface{})
	networkRXBytesJsonMap["metadata"].(map[string]interface{})["title"] = "Network RX (Bytes/s)"
	networkRXBytesJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	networkRXBytesJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		networkRXBytesJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		networkRXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Network TX Byte
	networkTXBytesJsonMap := make(map[string]interface{})
	networkTXBytesJsonMap["metadata"] = make(map[string]interface{})
	networkTXBytesJsonMap["metadata"].(map[string]interface{})["title"] = "Network TX (Bytes/s)"
	networkTXBytesJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	networkTXBytesJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		networkTXBytesJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		networkTXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Network RX Packet
	networkRXPacketsJsonMap := make(map[string]interface{})
	networkRXPacketsJsonMap["metadata"] = make(map[string]interface{})
	networkRXPacketsJsonMap["metadata"].(map[string]interface{})["title"] = "Network RX (packet/s)"
	networkRXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	networkRXPacketsJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		networkRXPacketsJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		networkRXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	// Network TX Packet
	networkTXPacketsJsonMap := make(map[string]interface{})
	networkTXPacketsJsonMap["metadata"] = make(map[string]interface{})
	networkTXPacketsJsonMap["metadata"].(map[string]interface{})["title"] = "Network TX (packet/s)"
	networkTXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"] = make([]string, 0)
	networkTXPacketsJsonMap["data"] = make([]interface{}, differenceAmount)
	for i := 0; i < differenceAmount; i++ {
		networkTXPacketsJsonMap["data"].([]interface{})[i] = make(map[string]interface{})
		networkTXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = make([]int64, 0)
	}

	allHistoricalReplicationControllerMetricKeySlice := getAllKeyFromJsonMap(filterHistoricalReplicationControllerMetricJsonMap)
	for _, replicationControllerName := range allHistoricalReplicationControllerMetricKeySlice {
		differenceTimestampSlice := make([]string, 0)
		originalTimestampSlice := make([]string, 0)
		timestampSlice, _ := filterHistoricalReplicationControllerMetricJsonMap[replicationControllerName].(map[string]interface{})["timestamp"].([]interface{})
		for index, value := range timestampSlice {
			timestamp, _ := time.Parse(time.RFC3339Nano, value.(string))
			// Convert from UTC to local time zone
			timestamp = timestamp.Add(-1 * time.Minute * time.Duration(timeZoneOffset))
			timestampText := timestamp.Format("2006-01-02 15:04:05")
			if index == 0 {
				originalTimestampSlice = append(originalTimestampSlice, timestampText)
			} else {
				originalTimestampSlice = append(originalTimestampSlice, timestampText)
				differenceTimestampSlice = append(differenceTimestampSlice, timestampText)
			}
		}

		allHistoricalPodJsonMap, _ := filterHistoricalReplicationControllerMetricJsonMap[replicationControllerName].(map[string]interface{})
		allHistoricalPodKeySlice := getAllKeyFromJsonMap(allHistoricalPodJsonMap)
		for _, podName := range allHistoricalPodKeySlice {
			if podName != "timestamp" {
				allHistoricalContainerJsonMap, _ := allHistoricalPodJsonMap[podName].(map[string]interface{})
				allHistoricalContainerKeySlice := getAllKeyFromJsonMap(allHistoricalContainerJsonMap)
				for _, containerName := range allHistoricalContainerKeySlice {
					historicalContainerJsonMap, _ := allHistoricalContainerJsonMap[containerName].(map[string]interface{})

					// CPU usage total
					cpuUsageTotalJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						cpuUsageTotalJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Memory usage
					memoryUsageJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						memoryUsageJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Disk I/O byte
					diskIOServiceBytesStatsJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						diskIOServiceBytesStatsJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Disk I/O count
					diskIOServicedStatsJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						diskIOServicedStatsJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Network RX Byte
					networkRXBytesJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						networkRXBytesJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Network TX Byte
					networkTXBytesJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						networkTXBytesJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Network RX Packet
					networkRXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						networkRXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)
					// Network TX Packet
					networkTXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"] = append(
						networkTXPacketsJsonMap["metadata"].(map[string]interface{})["lineName"].([]string),
						replicationControllerName+"/"+podName+"/"+containerName)

					for i := 0; i < differenceAmount; i++ {
						count, _ := historicalContainerJsonMap["documentCountSlice"].([]interface{})[i].(json.Number).Int64()
						// CPU usage total
						second, _ := historicalContainerJsonMap["minimumCpuUsageTotalSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ := historicalContainerJsonMap["minimumCpuUsageTotalSlice"].([]interface{})[i].(json.Number).Int64()
						value := (second - first) / count
						// Convert from ns to ms
						value /= 1000000
						cpuUsageTotalJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							cpuUsageTotalJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						cpuUsageTotalJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Disk I/O byte
						second, _ = historicalContainerJsonMap["minimumDiskioIoServiceBytesStatsTotalSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumDiskioIoServiceBytesStatsTotalSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						diskIOServiceBytesStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							diskIOServiceBytesStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						diskIOServiceBytesStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Disk I/O byte
						second, _ = historicalContainerJsonMap["minimumDiskioIoServicedStatsTotalSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumDiskioIoServicedStatsTotalSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						diskIOServicedStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							diskIOServicedStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						diskIOServicedStatsJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Network RX Byte
						second, _ = historicalContainerJsonMap["minimumNetworkRxBytesSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumNetworkRxBytesSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						networkRXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							networkRXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						networkRXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Network TX Byte
						second, _ = historicalContainerJsonMap["minimumNetworkTxBytesSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumNetworkTxBytesSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						networkTXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							networkTXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						networkTXBytesJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Network RX Packet
						second, _ = historicalContainerJsonMap["minimumNetworkRxPacketsSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumNetworkRxPacketsSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						networkRXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							networkRXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						networkRXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]

						// Network TX Packet
						second, _ = historicalContainerJsonMap["minimumNetworkTxPacketsSlice"].([]interface{})[i+1].(json.Number).Int64()
						first, _ = historicalContainerJsonMap["minimumNetworkTxPacketsSlice"].([]interface{})[i].(json.Number).Int64()
						value = (second - first) / count
						networkTXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							networkTXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						networkTXPacketsJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = differenceTimestampSlice[i]
					}

					for i := 0; i < resultAmount; i++ {
						// Memory usage
						value, _ := historicalContainerJsonMap["averageMemoryUsageSlice"].([]interface{})[i].(json.Number).Int64()
						// Convert from byte to MB
						value /= (1024 * 1024)
						memoryUsageJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"] = append(
							memoryUsageJsonMap["data"].([]interface{})[i].(map[string]interface{})["y"].([]int64), value)
						memoryUsageJsonMap["data"].([]interface{})[i].(map[string]interface{})["x"] = originalTimestampSlice[i]
					}
				}
			}
		}
	}

	chartSlice := make(map[string]interface{})

	// CPU usage total
	chartSlice["cpuUsageTotal"] = cpuUsageTotalJsonMap
	// Memory usage
	chartSlice["memoryUsage"] = memoryUsageJsonMap
	// Disk I/O byte
	chartSlice["diskIOServiceBytesStats"] = diskIOServiceBytesStatsJsonMap
	// Disk I/O count
	chartSlice["diskIOServicedStats"] = diskIOServicedStatsJsonMap
	// Network RX Byte
	chartSlice["networkRXBytes"] = networkRXBytesJsonMap
	// Network TX Byte
	chartSlice["networkTXBytes"] = networkTXBytesJsonMap

	// Network RX Packet
	chartSlice["networkRXPackets"] = networkRXPacketsJsonMap
	// Network TX Packet
	chartSlice["networkTXPackets"] = networkTXPacketsJsonMap

	c.Data["json"] = chartSlice

	c.ServeJSON()
}
Esempio n. 25
0
func GetReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (replicationController *ReplicationController, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			replicationController = nil
			returnedError = err.(error)
		}
	}()

	headerMap := make(map[string]string)
	headerMap["Authorization"] = kubeApiServerToken

	url := kubeApiServerEndPoint + "/api/v1/namespaces/" + namespace + "/replicationcontrollers/" + replicationControllerName
	result, err := restclient.RequestGet(url, headerMap, true)
	jsonMap, _ := result.(map[string]interface{})
	if err != nil {
		return nil, err
	} else {
		replicationController := new(ReplicationController)
		replicationController.Name, _ = jsonMap["metadata"].(map[string]interface{})["name"].(string)
		selector := jsonMap["spec"].(map[string]interface{})["selector"]
		if selector != nil {
			replicationController.Selector.Name, _ = selector.(map[string]interface{})["name"].(string)
			replicationController.Selector.Version, _ = selector.(map[string]interface{})["version"].(string)
		}

		replicas, _ := jsonparse.ConvertToInt64(jsonMap["spec"].(map[string]interface{})["replicas"])
		replicationController.ReplicaAmount = int(replicas)
		replicationControllerLabelMap := jsonMap["metadata"].(map[string]interface{})["labels"]
		if replicationControllerLabelMap != nil {
			replicationController.Label.Name, _ = replicationControllerLabelMap.(map[string]interface{})["name"].(string)
		}

		containerSlice := jsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"]
		if containerSlice != nil {
			replicationController.ContainerSlice = make([]ReplicationControllerContainer, 0)
			for _, container := range containerSlice.([]interface{}) {
				replicationControllerContainer := ReplicationControllerContainer{}
				replicationControllerContainer.Name, _ = container.(map[string]interface{})["name"].(string)
				replicationControllerContainer.Image, _ = container.(map[string]interface{})["image"].(string)
				portSlice, _ := container.(map[string]interface{})["ports"].([]interface{})
				replicationControllerContainer.PortSlice = make([]ReplicationControllerContainerPort, 0)
				for _, port := range portSlice {
					replicationControllerContainerPort := ReplicationControllerContainerPort{}
					replicationControllerContainerPort.Name, _ = port.(map[string]interface{})["name"].(string)
					containerPort, _ := jsonparse.ConvertToInt64(port.(map[string]interface{})["containerPort"])
					replicationControllerContainerPort.ContainerPort = int(containerPort)
					replicationControllerContainer.PortSlice = append(replicationControllerContainer.PortSlice, replicationControllerContainerPort)
				}

				environmentSlice, _ := container.(map[string]interface{})["env"].([]interface{})
				replicationControllerContainer.EnvironmentSlice = make([]ReplicationControllerContainerEnvironment, 0)
				for _, environment := range environmentSlice {
					name := environment.(map[string]interface{})["name"].(string)
					value := environment.(map[string]interface{})["value"].(string)
					replicationControllerContainer.EnvironmentSlice = append(replicationControllerContainer.EnvironmentSlice, ReplicationControllerContainerEnvironment{name, value})
				}

				replicationControllerContainer.ResourceMap, _ = container.(map[string]interface{})["resources"].(map[string]interface{})

				replicationController.ContainerSlice = append(replicationController.ContainerSlice, replicationControllerContainer)
			}
		}

		return replicationController, nil
	}
}