Пример #1
0
func sendAuditLog(token string, requestURI string, method string, path string, requestBody string, queryParameterMap map[string][]string, pathParameterMap map[string]string, remoteAddress string) {
	// Get cache. If not exsiting, retrieving from authorization server.
	user := getCache(token)
	userName := "******"
	if user != nil {
		userName = user.Name
	}

	cloudoneAnalysisHost, ok := configuration.LocalConfiguration.GetString("cloudoneAnalysisHost")
	if ok == false {
		log.Error("Fail to get configuration cloudoneAnalysisHost")
		return
	}
	cloudoneAnalysisPort, ok := configuration.LocalConfiguration.GetInt("cloudoneAnalysisPort")
	if ok == false {
		log.Error("Fail to get configuration cloudoneAnalysisPort")
		return
	}

	// Header is not used since the header has no useful information for now
	auditLog := audit.CreateAuditLog(componentName, path, userName, remoteAddress, queryParameterMap, pathParameterMap, method, requestURI, requestBody, nil)

	url := "https://" + cloudoneAnalysisHost + ":" + strconv.Itoa(cloudoneAnalysisPort) + "/api/v1/auditlogs"

	headerMap := make(map[string]string)
	headerMap["token"] = authorization.SystemAdminToken

	_, err := restclient.RequestPost(url, auditLog, headerMap, false)
	if err != nil {
		log.Error("Fail to send audit log with error %s", err)
	}
}
Пример #2
0
func SendBuildLog(imageRecord *ImageRecord, outputMessage string) error {
	cloudoneAnalysisHost, ok := configuration.LocalConfiguration.GetString("cloudoneAnalysisHost")
	if ok == false {
		log.Error("Fail to get configuration cloudoneAnalysisHost")
		return errors.New("Fail to get configuration cloudoneAnalysisHost")
	}
	cloudoneAnalysisPort, ok := configuration.LocalConfiguration.GetInt("cloudoneAnalysisPort")
	if ok == false {
		log.Error("Fail to get configuration cloudoneAnalysisPort")
		return errors.New("Fail to get configuration cloudoneAnalysisPort")
	}

	buildLog := build.BuildLog{
		imageRecord.ImageInformation,
		imageRecord.Version,
		imageRecord.VersionInfo,
		imageRecord.CreatedTime,
		outputMessage,
	}

	url := "https://" + cloudoneAnalysisHost + ":" + strconv.Itoa(cloudoneAnalysisPort) + "/api/v1/buildlogs"

	headerMap := make(map[string]string)
	headerMap["token"] = authorization.SystemAdminToken

	_, err := restclient.RequestPost(url, buildLog, headerMap, false)
	if err != nil {
		log.Error("Fail to send build log %v with error %s", buildLog, err)
	}

	return err
}
Пример #3
0
// @Title create
// @Description create the cluster application template
// @Param body body guirestapi.repository.thirdparty.Cluster true "body for cluster application template"
// @Success 200 {string} {}
// @Failure 404 error reason
// @router / [post]
func (c *EditController) Post() {
	inputBody := c.Ctx.Input.CopyBody(limit.InputPostBodyMaximum)
	cluster := Cluster{}
	err := json.Unmarshal(inputBody, &cluster)
	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
	}

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

	if cluster.ReplicationControllerJson == "" {
		cluster.ReplicationControllerJson = "{}"
	}
	if cluster.ServiceJson == "" {
		cluster.ServiceJson = "{}"
	}

	url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort +
		"/api/v1/clusterapplications/"

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

	_, err = restclient.RequestPost(url, cluster, tokenHeaderMap, true)

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

	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.ServeJSON()
	}
}
Пример #4
0
func auditLogWithoutVerified(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	requestURI := req.Request.URL.RequestURI()
	method := req.Request.Method
	path := req.SelectedRoutePath()
	queryParameterMap := req.Request.URL.Query()
	pathParameterMap := req.PathParameters()
	remoteAddress := req.Request.RemoteAddr

	requestBody, _ := ioutil.ReadAll(req.Request.Body)
	// Write data back for the later use
	req.Request.Body = ioutil.NopCloser(bytes.NewReader(requestBody))

	go func() {
		userData := UserData{}
		req.ReadEntity(&userData)
		userName := userData.Username

		cloudoneAnalysisHost, ok := configuration.LocalConfiguration.GetString("cloudoneAnalysisHost")
		if ok == false {
			log.Error("Fail to get configuration cloudoneAnalysisHost")
			return
		}
		cloudoneAnalysisPort, ok := configuration.LocalConfiguration.GetInt("cloudoneAnalysisPort")
		if ok == false {
			log.Error("Fail to get configuration cloudoneAnalysisPort")
			return
		}

		// Header is not used since the header has no useful information for now
		auditLog := audit.CreateAuditLog(componentName, path, userName, remoteAddress, queryParameterMap, pathParameterMap, method, requestURI, string(requestBody), nil)

		url := "https://" + cloudoneAnalysisHost + ":" + strconv.Itoa(cloudoneAnalysisPort) + "/api/v1/auditlogs"

		headerMap := make(map[string]string)
		headerMap["token"] = authorization.SystemAdminToken

		_, err := restclient.RequestPost(url, auditLog, headerMap, false)
		if err != nil {
			log.Error("Fail to send audit log with error %s", err)
		}
	}()

	chain.ProcessFilter(req, resp)
}
Пример #5
0
func sendAuditLog(ctx *context.Context, userName string, saveParameter bool) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedError = err.(error)
		}
	}()

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

	tokenHeaderMap, tokenHeaderMapOK := ctx.Input.Session("tokenHeaderMap").(map[string]string)
	requestURI := ctx.Input.URI()
	method := ctx.Input.Method()
	path := ctx.Input.URL()
	remoteAddress := ctx.Request.RemoteAddr
	queryParameterMap := ctx.Request.Form

	proxySlice := ctx.Input.Proxy()
	if proxySlice != nil && len(proxySlice) > 0 {
		proxySlice = append(proxySlice, remoteAddress)
		remoteAddress = fmt.Sprintf("%v", proxySlice)
	}

	if saveParameter == false {
		// Not to save parameter, such as password
		requestURI = path
		queryParameterMap = nil
	}

	// Header is not used since the header has no useful information for now
	// Body is not used since the backend component will record again.
	// Path is not used since the backend component will record again.
	auditLog := audit.CreateAuditLog(componentName, path, userName, remoteAddress, queryParameterMap, nil, method, requestURI, "", nil)

	if tokenHeaderMapOK {
		url := cloudoneAnalysisProtocol + "://" + cloudoneAnalysisHost + ":" + cloudoneAnalysisPort + "/api/v1/auditlogs"

		restclient.RequestPost(url, auditLog, tokenHeaderMap, false)
		// err is logged in analysis so don't need to here
	}

	return nil
}
Пример #6
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
	}
}
Пример #7
0
func CreateNamespace(kubeApiServerEndPoint string, kubeApiServerToken string, name string) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("CreateNamespace Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	jsonMap := make(map[string]interface{})
	jsonMap["metadata"] = make(map[string]interface{})
	jsonMap["metadata"].(map[string]interface{})["name"] = name

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

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

	return nil
}
Пример #8
0
func CreateService(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, service Service) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("CreateService Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	hasNodePort := false

	portJsonMapSlice := make([]map[string]interface{}, 0)
	for _, port := range service.PortSlice {
		portJsonMap := make(map[string]interface{})
		portJsonMap["name"] = port.Name
		portJsonMap["protocol"] = port.Protocol
		portJsonMap["port"] = port.Port
		targetPortNumber, err := strconv.Atoi(port.TargetPort)
		if err != nil {
			portJsonMap["targetPort"] = port.TargetPort
		} else {
			portJsonMap["targetPort"] = targetPortNumber
		}

		// < 0 not used, == 0 auto-generated, > 0 port number
		if port.NodePort >= 0 {
			hasNodePort = true
			if port.NodePort > 0 {
				portJsonMap["nodePort"] = port.NodePort
			}
		}

		portJsonMapSlice = append(portJsonMapSlice, portJsonMap)
	}

	bodyJsonMap := make(map[string]interface{})
	bodyJsonMap["kind"] = "Service"
	bodyJsonMap["apiVersion"] = "v1"
	bodyJsonMap["metadata"] = make(map[string]interface{})
	bodyJsonMap["metadata"].(map[string]interface{})["name"] = service.Name
	bodyJsonMap["metadata"].(map[string]interface{})["labels"] = service.LabelMap
	bodyJsonMap["spec"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["ports"] = portJsonMapSlice
	bodyJsonMap["spec"].(map[string]interface{})["selector"] = service.Selector

	// Use sticky session so the same client will be forwarded to the same pod
	if service.SessionAffinity != "" {
		bodyJsonMap["spec"].(map[string]interface{})["sessionAffinity"] = service.SessionAffinity
	}

	if hasNodePort {
		bodyJsonMap["spec"].(map[string]interface{})["type"] = "NodePort"
	}

	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
}
Пример #9
0
func (c *EditController) Post() {
	guimessage := guimessagedisplay.GetGUIMessage(c)

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

	name := c.GetString("name")
	description := c.GetString("description")

	scriptType := c.GetString("scriptType")

	// Name need to be a DNS 952 label
	match, _ := regexp.MatchString("^[a-z]{1}[a-z0-9-]{1,23}$", name)
	if match == false {
		guimessage.AddDanger("The name need to be a DNS 952 label ^[a-z]{1}[a-z0-9-]{1,23}$")
		c.Ctx.Redirect(302, "/gui/repository/thirdparty/list")
		guimessage.RedirectMessage(c)
		return
	}

	// Replciation Controller
	replicationControllerJson := c.GetString("replicationControllerJson")
	if replicationControllerJson == "" {
		replicationControllerJson = "{}"
	}

	file, _, err := c.GetFile("fileReplicationController")
	if err == nil {
		byteSlice, err := ioutil.ReadAll(file)
		if err == nil {
			replicationControllerJson = string(byteSlice)
		}
	}
	if file != nil {
		file.Close()
	}

	// Service
	serviceJson := c.GetString("serviceJson")
	if serviceJson == "" {
		serviceJson = "{}"
	}

	file, _, err = c.GetFile("fileService")
	if err == nil {
		byteSlice, err := ioutil.ReadAll(file)
		if err == nil {
			serviceJson = string(byteSlice)
		}
	}
	if file != nil {
		file.Close()
	}

	// Environment
	environmentText := c.GetString("environment")
	if environmentText == "" {
		environmentText = "{}"
	}

	file, _, err = c.GetFile("fileEnvironment")
	if err == nil {
		byteSlice, err := ioutil.ReadAll(file)
		if err == nil {
			environmentText = string(byteSlice)
		}
	}
	if file != nil {
		file.Close()
	}

	// Script
	scriptContent := c.GetString("scriptContent")

	file, _, err = c.GetFile("fileScript")
	if err == nil {
		byteSlice, err := ioutil.ReadAll(file)
		if err == nil {
			scriptContent = string(byteSlice)
		}
	}
	if file != nil {
		file.Close()
	}

	// Test replication controller
	replicationControllerJsonMap := make(map[string]interface{})
	// Try json
	err = json.Unmarshal([]byte(replicationControllerJson), &replicationControllerJsonMap)
	if err != nil {
		// Try yaml
		err := yaml.Unmarshal([]byte(replicationControllerJson), &replicationControllerJsonMap)
		if err != nil {
			// Error
			guimessage.AddDanger("Replication controller can't be parsed by json or yaml")
			guimessage.AddDanger(err.Error())
			c.Ctx.Redirect(302, "/gui/repository/thirdparty/list")
			guimessage.RedirectMessage(c)
			return
		}
	}

	// Test service
	serviceJsonMap := make(map[string]interface{})
	// Try json
	err = json.Unmarshal([]byte(serviceJson), &serviceJsonMap)
	if err != nil {
		// Try yaml
		err := yaml.Unmarshal([]byte(serviceJson), &serviceJsonMap)
		if err != nil {
			// Error
			guimessage.AddDanger("Service can't be parsed by json or yaml")
			guimessage.AddDanger(err.Error())
			c.Ctx.Redirect(302, "/gui/repository/thirdparty/list")
			guimessage.RedirectMessage(c)
			return
		}
	}

	environmentJsonMap := make(map[string]string)
	// Try json
	err = json.Unmarshal([]byte(environmentText), &environmentJsonMap)
	if err != nil {
		// Try yaml
		err := yaml.Unmarshal([]byte(environmentText), &environmentJsonMap)
		if err != nil {
			// Error
			guimessage.AddDanger("Environment can't be parsed by json or yaml")
			guimessage.AddDanger(err.Error())
			c.Ctx.Redirect(302, "/gui/repository/thirdparty/list")
			guimessage.RedirectMessage(c)
			return
		}
	}

	cluster := Cluster{
		name,
		description,
		replicationControllerJson,
		serviceJson,
		environmentJsonMap,
		scriptType,
		scriptContent,
	}

	url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort +
		"/api/v1/clusterapplications/"

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

	_, err = restclient.RequestPost(url, cluster, tokenHeaderMap, true)

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

	if err != nil {
		// Error
		guimessage.AddDanger(guimessagedisplay.GetErrorMessage(err))
	} else {
		guimessage.AddSuccess("Third party application " + name + " is edited")
	}

	c.Ctx.Redirect(302, "/gui/repository/thirdparty/list")

	guimessage.RedirectMessage(c)
}
Пример #10
0
func CreateReplicationController(kubeApiServerEndPoint string, kubeApiServerToken string, namespace string, replicationController ReplicationController) (returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("CreateReplicationController Error: %s", err)
			log.Error(logger.GetStackTrace(4096, false))
			returnedError = err.(error)
		}
	}()

	containerJsonMapSlice := make([]interface{}, 0)
	for _, replicationControllerContainer := range replicationController.ContainerSlice {
		containerJsonMap := make(map[string]interface{})
		containerJsonMap["name"] = replicationControllerContainer.Name
		containerJsonMap["image"] = replicationControllerContainer.Image
		containerJsonMap["resources"] = replicationControllerContainer.ResourceMap

		portJsonMapSlice := make([]interface{}, 0)
		for _, replicationControllerContainerPort := range replicationControllerContainer.PortSlice {
			portJsonMap := make(map[string]interface{})
			portJsonMap["name"] = replicationControllerContainerPort.Name
			portJsonMap["containerPort"] = replicationControllerContainerPort.ContainerPort
			portJsonMapSlice = append(portJsonMapSlice, portJsonMap)
		}
		containerJsonMap["ports"] = portJsonMapSlice

		environmentJsonMapSlice := make([]interface{}, 0)
		for _, environment := range replicationControllerContainer.EnvironmentSlice {
			environmentJsonMap := make(map[string]interface{})
			environmentJsonMap["name"] = environment.Name
			environmentJsonMap["value"] = environment.Value
			environmentJsonMapSlice = append(environmentJsonMapSlice, environmentJsonMap)
		}
		containerJsonMap["env"] = environmentJsonMapSlice

		// FIXME temporarily to use nested docker
		volumeMountJsonMap := make(map[string]interface{})
		volumeMountJsonMap["name"] = "docker"
		volumeMountJsonMap["readOnly"] = true
		volumeMountJsonMap["mountPath"] = "/var/run/docker.sock"
		volumeMountJsonMapSlice := make([]interface{}, 0)
		volumeMountJsonMapSlice = append(volumeMountJsonMapSlice, volumeMountJsonMap)
		containerJsonMap["volumeMounts"] = volumeMountJsonMapSlice

		containerJsonMapSlice = append(containerJsonMapSlice, containerJsonMap)
	}

	bodyJsonMap := make(map[string]interface{})
	bodyJsonMap["kind"] = "ReplicationController"
	bodyJsonMap["apiVersion"] = "v1"
	bodyJsonMap["metadata"] = make(map[string]interface{})
	bodyJsonMap["metadata"].(map[string]interface{})["name"] = replicationController.Name
	bodyJsonMap["metadata"].(map[string]interface{})["labels"] = make(map[string]interface{})
	bodyJsonMap["metadata"].(map[string]interface{})["labels"].(map[string]interface{})["name"] = replicationController.Label.Name
	bodyJsonMap["spec"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["replicas"] = replicationController.ReplicaAmount
	bodyJsonMap["spec"].(map[string]interface{})["selector"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["selector"].(map[string]interface{})["name"] = replicationController.Selector.Name
	bodyJsonMap["spec"].(map[string]interface{})["selector"].(map[string]interface{})["version"] = replicationController.Selector.Version
	bodyJsonMap["spec"].(map[string]interface{})["template"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["metadata"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["metadata"].(map[string]interface{})["labels"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["metadata"].(map[string]interface{})["labels"].(map[string]interface{})["name"] = replicationController.Selector.Name
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["metadata"].(map[string]interface{})["labels"].(map[string]interface{})["version"] = replicationController.Selector.Version
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"] = make(map[string]interface{})
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"] = containerJsonMapSlice

	// FIXME temporarily to use nested docker
	volumeJsonMap := make(map[string]interface{})
	volumeJsonMap["name"] = "docker"
	volumeJsonMap["hostPath"] = make(map[string]interface{})
	volumeJsonMap["hostPath"].(map[string]interface{})["path"] = "/var/run/docker.sock"
	volumeJsonMapSlice := make([]interface{}, 0)
	volumeJsonMapSlice = append(volumeJsonMapSlice, volumeJsonMap)
	bodyJsonMap["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["volumes"] = volumeJsonMapSlice

	// Configure extra json body
	// It is used for user to input any configuration
	if replicationController.ExtraJsonMap != nil {
		deepcopy.DeepOverwriteJsonMap(replicationController.ExtraJsonMap, bodyJsonMap)
	}

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

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

	if err != nil {
		return err
	} else {
		return nil
	}
}