예제 #1
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
}
예제 #2
0
func (etcdClient *EtcdClient) GetKeysAPI() (returnedKeysAPI client.KeysAPI, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetKeysAPI Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			etcdClient.KeysAPI = nil
			returnedKeysAPI = nil
			returnedError = err.(error)
		}
	}()

	if etcdClient.KeysAPI != nil {
		return etcdClient.KeysAPI, nil
	} else {
		config := client.Config{
			Endpoints:               etcdClient.EtcdEndpoints,
			Transport:               client.DefaultTransport,
			HeaderTimeoutPerRequest: etcdClient.EtcdHeaderTimeoutPerRequest,
		}
		configuredClient, err := client.New(config)
		if err != nil {
			etcdClient.KeysAPI = nil
			log.Error(err)
			return nil, err
		}
		keysAPI := client.NewKeysAPI(configuredClient)

		etcdClient.KeysAPI = keysAPI
		return keysAPI, nil
	}
}
예제 #3
0
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
		}
	}
}
func (cassandraClient *CassandraClient) CreateTableIfNotExist(tableSchema string, retryAmount int, retryInterval time.Duration) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("CreateTableIfNotExist Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	session, err := cassandraClient.GetSession()
	if err != nil {
		return err
	}

	for i := 0; i < retryAmount; i++ {
		if err := session.Query(tableSchema).Exec(); err == nil {
			return nil
		} else {
			log.Error("Check if not exist then create table schema %s error: %s", tableSchema, err)
			returnedError = err
		}
		time.Sleep(retryInterval)
	}

	return returnedError
}
예제 #5
0
func (configuration *Configuration) createConfigurationFileIfNotExist(programName string, configurationContent string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("configuration Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	directoryPath := rootPath + string(os.PathSeparator) + programName
	if err := os.MkdirAll(directoryPath, os.ModePerm); err != nil {
		return err
	}

	fileNameAndPath := directoryPath + string(os.PathSeparator) + fileName

	if _, err := os.Stat(fileNameAndPath); os.IsNotExist(err) {
		outputFile, err := os.Create(fileNameAndPath)
		if err != nil {
			log.Error("createConfigurationFileIfNotExist create file %s with error: %s", fileNameAndPath, err)
			return err
		}
		outputFile.WriteString(configurationContent)
	}

	configuration.fileNameAndPath = fileNameAndPath

	return nil
}
예제 #6
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 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
	}
}
예제 #8
0
func DeleteReplicationControllerAndRelatedPod(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("DeleteReplicationControllerAndRelatedPod Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	err := DeleteReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
	if err != nil {
		return err
	} else {
		nameSlice, err := GetAllPodNameBelongToReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
		if err != nil {
			return err
		} else {
			for _, name := range nameSlice {
				err := DeletePod(kubeApiServerEndPoint, kubeApiServerToken, namespace, name)
				if err != nil {
					return err
				}
			}
			return nil
		}
	}
}
예제 #9
0
func (glusterfsCluster *GlusterfsCluster) parseSize(field string) (returnedSize int, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("Parse size error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedSize = -1
			returnedError = err.(error)
		}
	}()

	var value string
	if strings.Contains(field, "=") {
		value = strings.Split(field, "=")[1]
	} else {
		value = field
	}

	size, err := strconv.Atoi(strings.TrimSpace(value))

	if err != nil {
		log.Error("Parse size error %s", err)
		return -1, err
	} else {
		return size, nil
	}
}
예제 #10
0
func (glusterfsCluster *GlusterfsCluster) parseVolumeInfo(text string) (returnedGlusterfsVolumeSlice []GlusterfsVolume, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("parseVolumeInfo Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedGlusterfsVolumeSlice = nil
			returnedError = err.(error)
		}
	}()

	glusterfsVolumeSlice := make([]GlusterfsVolume, 0)

	scanner := bufio.NewScanner(bytes.NewBufferString(text))
	var glusterfsVolume *GlusterfsVolume = nil
	for scanner.Scan() {
		line := scanner.Text()
		if line == " " {
			if glusterfsVolume != nil {
				glusterfsVolumeSlice = append(glusterfsVolumeSlice, *glusterfsVolume)
			}
			glusterfsVolume = &GlusterfsVolume{}
		} else if strings.HasPrefix(line, "Volume Name: ") {
			glusterfsVolume.VolumeName = line[len("Volume Name: "):]
		} else if strings.HasPrefix(line, "Type: ") {
			glusterfsVolume.Type = line[len("Type: "):]
		} else if strings.HasPrefix(line, "Volume ID: ") {
			glusterfsVolume.VolumeID = line[len("Volume ID: "):]
		} else if strings.HasPrefix(line, "Status: ") {
			glusterfsVolume.Status = line[len("Status: "):]
		} else if strings.HasPrefix(line, "Number of Bricks: ") {
			glusterfsVolume.NumberOfBricks = line[len("Number of Bricks: "):]
			glusterfsVolume.Size, _ = glusterfsCluster.parseSize(glusterfsVolume.NumberOfBricks)
		} else if strings.HasPrefix(line, "Transport-type: ") {
			glusterfsVolume.TransportType = line[len("Transport-type: "):]
		} else if line == "Bricks:" {
			brickSlice := make([]string, 0)
			for i := 0; i < glusterfsVolume.Size; i++ {
				scanner.Scan()
				brickSlice = append(brickSlice, scanner.Text())
			}
			glusterfsVolume.Bricks = brickSlice
		} else {
			// Ignore unexpected data
		}
	}
	if glusterfsVolume != nil {
		glusterfsVolumeSlice = append(glusterfsVolumeSlice, *glusterfsVolume)
	}
	if err := scanner.Err(); err != nil {
		log.Error("Scanner error %s", err)
		return nil, err
	}
	return glusterfsVolumeSlice, nil
}
예제 #11
0
func MonitorReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedReplicationControllerMetric *ReplicationControllerMetric, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("MonitorReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedReplicationControllerMetric = nil
			returnedError = err.(error)
		}
	}()

	exist, err := ExistReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
	if err != nil {
		log.Error("Fail to get the replication controller with endpoint: %s, token: %s, namespace: %s, replication controller name: %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
		return nil, err
	}
	if exist == false {
		log.Error("Replication controller doesn't exist with endpoint: %s, token: %s, namespace: %s, replication controller name: %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
		return nil, err
	}

	podNameSlice, err := control.GetAllPodNameBelongToReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
	if err != nil {
		log.Error("Fail to get all pod name belong to the replication controller with endpoint: %s, token: %s, namespace: %s, replication controller name: %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
		return nil, err
	}

	replicationControllerMetric := &ReplicationControllerMetric{}
	replicationControllerMetric.Namespace = namespace
	replicationControllerMetric.ReplicationControllerName = replicationControllerName
	replicationControllerMetric.Size = len(podNameSlice)
	replicationControllerMetric.ValidPodSlice = make([]bool, replicationControllerMetric.Size)
	replicationControllerMetric.PodMetricSlice = make([]PodMetric, replicationControllerMetric.Size)
	errorMessage := "The following index of pod has error: "
	errorHappened := false
	for index, podName := range podNameSlice {
		podMetric, err := MonitorPod(kubeApiServerEndPoint, kubeApiServerToken, namespace, podName)
		if err != nil {
			errorMessage = errorMessage + err.Error()
			errorHappened = true
			replicationControllerMetric.ValidPodSlice[index] = false
		} else {
			replicationControllerMetric.ValidPodSlice[index] = true
			replicationControllerMetric.PodMetricSlice[index] = *podMetric
		}
	}

	if errorHappened {
		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, errorMessage)
		return replicationControllerMetric, errors.New(errorMessage)
	} else {
		return replicationControllerMetric, nil
	}
}
예제 #12
0
파일: image.go 프로젝트: cloudawan/cloudone
func BuildUpgrade(imageInformationName string, description string) (returnedOutputMessage string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("BuildUpgrade Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedOutputMessage = ""
			returnedError = err.(error)
		}
	}()

	imageInformation, err := GetStorage().LoadImageInformation(imageInformationName)
	if err != nil {
		log.Error("Load image information error: %s", err)
		return "", err
	}

	var buildError error = nil
	imageRecord, outputMessage, err := Build(imageInformation, description)
	if err != nil {
		log.Error("Build error: %s Output message: %s", err, outputMessage)
		if imageRecord == nil {
			return outputMessage, err
		} else {
			buildError = err
			outputMessage = outputMessage + "\n" + err.Error()
		}
	}

	// Save image record
	err = GetStorage().saveImageRecord(imageRecord)
	if err != nil {
		log.Error("Save image record error: %s", err)
		return outputMessage, err
	}

	imageInformation.CurrentVersion = imageRecord.Version
	// Save image information
	err = GetStorage().SaveImageInformation(imageInformation)
	if err != nil {
		log.Error("Save image information error: %s", err)
		return outputMessage, err
	}

	// Save build log
	err = SendBuildLog(imageRecord, outputMessage)
	if err != nil {
		log.Error("Save build log error: %s", err)
		return outputMessage, err
	}

	return outputMessage, buildError
}
예제 #13
0
func GetAvailablekubeApiServerEndPoint() (returnedEndPoint string, returnedToken string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedEndPoint = ""
			returnedToken = ""
			returnedError = err.(error)
			log.Error("GetAvailablekubeApiServerEndPoint Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
		}
	}()

	kubeApiServerEndPointSlice, ok := LocalConfiguration.GetStringSlice("kubeApiServerEndPoints")
	if ok == false {
		log.Error("Fail to get configuration kubeApiServerEndPoints")
		return "", "", errors.New("Fail to get configuration kubeApiServerEndPoints")
	}

	kubeApiServerHealthCheckTimeoutInMilliSecond, ok := LocalConfiguration.GetInt("kubeApiServerHealthCheckTimeoutInMilliSecond")
	if ok == false {
		kubeApiServerHealthCheckTimeoutInMilliSecond = KubeApiServerHealthCheckTimeoutInMilliSecond
	}

	kubeApiServerToken, ok := LocalConfiguration.GetString("kubeApiServerToken")
	if ok == false {
		log.Error("Fail to get configuration kubeApiServerToken")
		return "", "", errors.New("Fail to get configuration kubeApiServerToken")
	}

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

	for _, kubeApiServerEndPoint := range kubeApiServerEndPointSlice {
		result, err := restclient.HealthCheck(
			kubeApiServerEndPoint,
			headerMap,
			time.Duration(kubeApiServerHealthCheckTimeoutInMilliSecond)*time.Millisecond)

		if result {
			return kubeApiServerEndPoint, token, nil
		} else {
			if err != nil {
				log.Error(err)
			}
		}
	}

	log.Error("No available kube apiserver endpoint")
	return "", "", errors.New("No available kube apiserver endpoint")
}
예제 #14
0
func DeleteReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("DeleteReplicationController 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
	_, err := restclient.RequestDelete(url, nil, headerMap, true)
	return err
}
예제 #15
0
파일: node.go 프로젝트: cloudawan/cloudone
func GetAllNodeIP(kubeApiServerEndPoint string, kubeApiServerToken string) (returnedIpSlice []string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetAllNodeIP Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedIpSlice = nil
			returnedError = err.(error)
		}
	}()

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

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

	url := kubeApiServerEndPoint + "/api/v1/nodes/"
	_, err := restclient.RequestGetWithStructure(url, &jsonMap, headerMap)
	if err != nil {
		log.Error(err)
		return nil, err
	}

	ipSlice := make([]string, 0)

	itemSlice, _ := jsonMap["items"].([]interface{})
	for _, item := range itemSlice {
		itemJsonMap, _ := item.(map[string]interface{})
		statusJsonMap, _ := itemJsonMap["status"].(map[string]interface{})
		addressesJsonSlice, _ := statusJsonMap["addresses"].([]interface{})
		address := ""
		for _, value := range addressesJsonSlice {
			addressJsonMap, _ := value.(map[string]interface{})
			addressType, _ := addressJsonMap["type"].(string)
			addressAddress, _ := addressJsonMap["address"].(string)
			if addressType == "InternalIP" {
				address = addressAddress
				break
			}
		}

		if len(address) > 0 {
			ipSlice = append(ipSlice, address)
		}
	}

	return ipSlice, nil
}
예제 #16
0
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
		}
	}
}
예제 #17
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
}
예제 #18
0
func (configuration *Configuration) readConfigurationFromFile() (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("readConfigurationFromFile Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	// open input file
	inputFile, err := os.Open(configuration.fileNameAndPath)
	if err != nil {
		log.Error("readConfigurationFromFile open file error: %s", err)
		return err
	}
	defer inputFile.Close()

	byteSlice := make([]byte, 0)
	buffer := make([]byte, 1024)
	for {
		// read a chunk
		n, err := inputFile.Read(buffer)
		if err != nil && err != io.EOF {
			log.Error("readConfigurationFromFile read file error: %s", err)
			return err
		}
		if n == 0 {
			break
		}

		byteSlice = append(byteSlice, buffer[0:n]...)
	}

	jsonMap := make(map[string]interface{})
	err = json.Unmarshal(byteSlice, &jsonMap)
	if err != nil {
		log.Error("readConfigurationFromFile parse file error: %s", err)
		return err
	}

	configuration.jsonMap = jsonMap

	return nil
}
예제 #19
0
func (cassandraClient *CassandraClient) GetSession() (returnedSession *gocql.Session, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("GetSession Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			cassandraClient.session = nil
			returnedSession = nil
			returnedError = err.(error)
		}
	}()

	if cassandraClient.session != nil {
		return cassandraClient.session, nil
	} else {
		cluster := gocql.NewCluster(cassandraClient.clusterIp...)
		cluster.Timeout = cassandraClient.timeout
		cluster.Port = cassandraClient.clusterPort
		session, err := cluster.CreateSession()
		if err != nil {
			log.Critical("Fail to create Cassandra session: %s", err)
			cassandraClient.session = nil
			return nil, err
		} else {
			if err := session.Query("CREATE KEYSPACE IF NOT EXISTS " + cassandraClient.keyspace + " WITH replication = " + cassandraClient.replicationStrategy).Exec(); err != nil {
				log.Critical("Fail to check if not exist then create keyspace error: %s", err)
				cassandraClient.session = nil
				return nil, err
			} else {
				session.Close()
				cluster.Keyspace = cassandraClient.keyspace
				session, err := cluster.CreateSession()
				if err != nil {
					log.Critical("Fail to create Cassandra session: %s", err)
					cassandraClient.session = nil
					return nil, err
				} else {
					cassandraClient.session = session
					return cassandraClient.session, nil
				}
			}
		}
	}
}
func periodicalRunHistoricalRecordEvent() {
	defer func() {
		if err := recover(); err != nil {
			log.Error("periodicalRunHistoricalRecordEvent Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
		}
	}()

	kubeApiServerEndPoint, kubeApiServerToken, err := configuration.GetAvailablekubeApiServerEndPoint()
	if err != nil {
		log.Error("Fail to get configuration endpoint and token with error %s", err)
		return
	}

	if err := event.RecordHistoricalEvent(kubeApiServerEndPoint, kubeApiServerToken); err != nil {
		log.Error(err)
		return
	}
}
func RecordHistoricalAllNamespace(kubeApiServerEndPoint string, kubeApiServerToken string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("RecordHistoricalAllNamespace Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	namespaceNameSlice, err := control.GetAllNamespaceName(kubeApiServerEndPoint, kubeApiServerToken)
	if err != nil {
		log.Error(err)
		return err
	}

	allNamespaceContainerRecordSlice := make([]map[string]interface{}, 0)
	for _, namespaceName := range namespaceNameSlice {
		replicationControllerNameSlice, err := control.GetAllReplicationControllerName(kubeApiServerEndPoint, kubeApiServerToken, namespaceName)
		if err != nil {
			log.Error(err)
		} else {
			for _, replicationControllerName := range replicationControllerNameSlice {
				replicationControllerContainerRecordSlice, err := RecordHistoricalReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespaceName, replicationControllerName)
				if err != nil {
					log.Error(err)
				} else {
					allNamespaceContainerRecordSlice = append(allNamespaceContainerRecordSlice, replicationControllerContainerRecordSlice...)
				}
			}
		}
	}

	for _, containerRecord := range allNamespaceContainerRecordSlice {
		index, _ := containerRecord["searchMetaData"].(map[string]interface{})["index"].(string)
		documentType, _ := containerRecord["searchMetaData"].(map[string]interface{})["documentType"].(string)
		id, _ := containerRecord["searchMetaData"].(map[string]interface{})["id"].(string)
		if err := saveContainerRecord(index, documentType, id, containerRecord); err != nil {
			log.Error("Save error %s", err)
		}
	}

	return nil
}
예제 #22
0
func DeleteNamespace(kubeApiServerEndPoint string, kubeApiServerToken string, name string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("DeleteNamespace Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

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

	_, err := restclient.RequestDelete(kubeApiServerEndPoint+"/api/v1/namespaces/"+name, nil, headerMap, true)
	if err != nil {
		log.Error("Fail to delete namespace with endpoint: %s, token: %s, name: %s, error: %s", kubeApiServerEndPoint, kubeApiServerToken, name, err.Error())
		return err
	}

	return nil
}
예제 #23
0
func DeleteEvent(kubeApiServerEndPoint string, kubeApiServerToken string, selfLink string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("DeleteEvent Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

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

	_, err := restclient.RequestDelete(kubeApiServerEndPoint+selfLink, nil, headerMap, true)
	if err != nil {
		log.Error("Fail to delete event selfLink %s with endpoint: %s, token: %s, error: %s", selfLink, kubeApiServerEndPoint, kubeApiServerToken, err.Error())
		return err
	}

	return nil
}
예제 #24
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
	}
}
예제 #25
0
func CreateServiceWithJson(kubeApiServerEndPoint string, kubeApiServerToken string, namespace 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/"
	_, err := restclient.RequestPost(url, bodyJsonMap, headerMap, true)

	if err != nil {
		log.Error(err)
		return err
	} else {
		return nil
	}
}
예제 #26
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
}
func RecordHistoricalReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationControllerName string) (returnedReplicationControllerContainerRecordSlice []map[string]interface{}, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("RecordHistoricalReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
			returnedReplicationControllerContainerRecordSlice = nil
		}
	}()

	podNameSlice, err := control.GetAllPodNameBelongToReplicationController(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
	if err != nil {
		log.Error("Fail to get all pod name belong to the replication controller with endpoint %s, token: %s, namespace: %s, replication controller name: %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName)
		return nil, err
	}

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

	replicationControllerContainerRecordSlice := make([]map[string]interface{}, 0)
	for _, podName := range podNameSlice {
		podContainerRecordSlice, err := RecordHistoricalPod(kubeApiServerEndPoint, kubeApiServerToken, namespace, replicationControllerName, podName)
		if err != nil {
			errorHappened = true
			log.Error("RecordHistoricalPod error %s", err)
			errorBuffer.WriteString("RecordHistoricalPod error " + err.Error())
		} else {
			replicationControllerContainerRecordSlice = append(replicationControllerContainerRecordSlice, podContainerRecordSlice...)
		}
	}

	if errorHappened {
		log.Error("Fail to get all container inofrmation with endpoint %s, token: %s, namespace: %s, error %s", kubeApiServerEndPoint, kubeApiServerToken, namespace, errorBuffer.String())
		return nil, errors.New(errorBuffer.String())
	} else {
		return replicationControllerContainerRecordSlice, nil
	}
}
예제 #28
0
파일: pod.go 프로젝트: cloudawan/cloudone
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)
}
예제 #29
0
파일: pod.go 프로젝트: cloudawan/cloudone
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
}
예제 #30
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
	}
}