コード例 #1
0
func (p *ClusterService) CreateUserCluster(cluster entity.Cluster, x_auth_token string) (newCluster *entity.Cluster,
	errorCode string, err error) {

	// generate ObjectId
	cluster.ObjectId = bson.NewObjectId()

	userId := cluster.UserId
	if len(userId) == 0 {
		err = errors.New("user_id not provided")
		errorCode = COMMON_ERROR_INVALIDATE
		logrus.Errorf("create cluster [%v] error is %v", cluster, err)
		return
	}

	user, err := GetUserById(userId, x_auth_token)
	if err != nil {
		logrus.Errorf("get user by id err is %v", err)
		errorCode = CLUSTER_ERROR_CALL_USERMGMT
		return nil, errorCode, err
	}
	cluster.TenantId = user.TenantId
	cluster.Owner = user.Username

	// set created_time and updated_time
	cluster.TimeCreate = dao.GetCurrentTime()
	cluster.TimeUpdate = cluster.TimeCreate
	cluster.Status = CLUSTER_STATUS_DEPLOYING
	// insert bson to mongodb
	err = dao.HandleInsert(p.collectionName, cluster)
	if err != nil {
		errorCode = CLUSTER_ERROR_CALL_MONGODB
		logrus.Errorf("create cluster [%v] to bson error is %v", cluster, err)
		return
	}

	//add records of hosts in db
	for i := 0; i < cluster.Instances; i++ {
		host := entity.Host{}
		host.ClusterId = cluster.ObjectId.Hex()
		host.ClusterName = cluster.Name
		host.Status = HOST_STATUS_DEPLOYING
		host.UserId = cluster.UserId
		host.TimeCreate = dao.GetCurrentTime()
		host.TimeUpdate = host.TimeCreate

		_, _, err := GetHostService().Create(host, x_auth_token)
		if err != nil {
			logrus.Errorf("insert host to db error is [%v]", err)
		}
	}

	if IsDeploymentEnabled() {
		//call deployment
		go CreateCluster(cluster, x_auth_token)
	}

	newCluster = &cluster
	return
}
コード例 #2
0
func (p *HostService) UpdateById(objectId string, host entity.Host, x_auth_token string) (created bool,
	errorCode string, err error) {
	logrus.Infof("start to update host [%v]", host)
	// do authorize first
	if authorized := GetAuthService().Authorize("update_host", x_auth_token, objectId, p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("update host with objectId [%v] error is %v", objectId, err)
		return
	}

	if !bson.IsObjectIdHex(objectId) {
		err = errors.New("invalide ObjectId.")
		errorCode = COMMON_ERROR_INVALIDATE
		return
	}

	// FIXING
	//	hostquery, _, _  := p.QueryById(objectId, x_auth_token)
	var selector = bson.M{}
	selector["_id"] = bson.ObjectIdHex(objectId)

	host.ObjectId = bson.ObjectIdHex(objectId)
	host.TimeUpdate = dao.GetCurrentTime()

	logrus.Infof("start to change host")
	err = dao.HandleUpdateByQueryPartial(p.collectionName, selector, &host)
	//	created, err = dao.HandleUpdateOne(&host, dao.QueryStruct{p.collectionName, selector, 0, 0, ""})
	if err != nil {
		logrus.Errorf("update host [%v] error is %v", host, err)
		errorCode = HOST_ERROR_UPDATE
	}
	created = true
	return
}
コード例 #3
0
func (p *UserService) createAndInsertUser(userName string, password string, email string, tenanId string, roleId string, company string) (userId string, err error) {
	// var jsondocument interface{}
	currentUser, erro := p.getAllUserByName(userName)
	if erro != nil {
		logrus.Error("get all user by username err is %v", erro)
		return "", erro
	}
	if len(currentUser) != 0 {
		logrus.Infoln("user already exist! username:"******"create user error %v", err)
		return
	}
	userId = user.ObjectId.Hex()

	return
}
コード例 #4
0
// CreateAndInsertTenant creat the tenant and insert to collection according
// by tenantname and desc.
func (p *TenantService) createAndInsertTenant(tenantName string, desc string) (tenantId string, err error) {
	tenant, erro := p.getTenantByName(tenantName)
	if erro == nil {
		logrus.Infoln("tenant already exist! tenantname: ", tenantName)
		tenantId = tenant.ObjectId.Hex()
		return
	}

	currentTime := dao.GetCurrentTime()
	objectId := bson.NewObjectId()
	newTenant := entity.Tenant{
		ObjectId:    objectId,
		Tenantname:  tenantName,
		Description: desc,
		TimeCreate:  currentTime,
		TimeUpdate:  currentTime,
	}

	err = dao.HandleInsert(p.collectionName, &newTenant)
	if err != nil {
		logrus.Error("create tenant error %v", err)
		return
	}
	tenantId = newTenant.ObjectId.Hex()
	return

}
コード例 #5
0
// CreateAndInsertRole creat and insert the role items according to the given
// rolename and desc.
func (p *RoleService) createAndInsertRole(roleName string, desc string) (roleId string, err error) {
	role := &entity.Role{}
	role, err = p.getRoleByName(roleName)
	if err == nil {
		logrus.Infoln("role already exist! roleName: ", roleName)
		roleId = role.ObjectId.Hex()
		return
	}

	currentTime := dao.GetCurrentTime()
	objectId := bson.NewObjectId()
	role = &entity.Role{
		ObjectId:    objectId,
		Rolename:    roleName,
		Description: desc,
		TimeCreate:  currentTime,
		TimeUpdate:  currentTime,
	}

	err = dao.HandleInsert(p.collectionName, role)
	if err != nil {
		logrus.Warnln("create role error %v", err)
		return
	}
	roleId = role.ObjectId.Hex()
	return

}
コード例 #6
0
func (p *UserService) UserChangePassword(token string, id string, password string, newpassword string, confirm_newpassword string) (created bool, errorCode string, err error) {
	code, err := GetTokenService().TokenValidate(token)
	if err != nil {
		return false, code, err
	}

	if authorized := GetAuthService().Authorize("change_password", token, id, p.userCollectionName); !authorized {
		logrus.Errorln("required opertion is not allowed!")
		return false, COMMON_ERROR_UNAUTHORIZED, errors.New("Required opertion is not authorized!")
	}

	user, err := p.GetUserByUserId(id)
	if err != nil {
		logrus.Errorln("user does exist %v", err)
		return false, COMMON_ERROR_INTERNAL, errors.New("User does not exist!")
	}

	pwdEncry := HashString(password)
	if !strings.EqualFold(pwdEncry, user.Password) {
		logrus.Errorln("incorrect password!")
		return false, USER_ERROR_WRONGPW, errors.New("Incorrect password!")
	}

	if !strings.EqualFold(newpassword, confirm_newpassword) {
		logrus.Errorln("inconsistence new password!")
		return false, USER_ERROR_WRONGPW, errors.New("Inconsistent new password!")
	}

	newpasswordEncry := HashString(newpassword)
	user.Password = newpasswordEncry

	user.TimeUpdate = dao.GetCurrentTime()

	// userDoc := ConvertToBson(*user)
	selector := bson.M{}
	selector["_id"] = bson.ObjectIdHex(id)

	queryStruct := dao.QueryStruct{
		CollectionName: p.userCollectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	created, err = dao.HandleUpdateOne(user, queryStruct)
	if err != nil {
		logrus.Error("update user password error! %v", err)
		return created, USER_ERROR_UPDATE, err
	}

	return created, "", nil
}
コード例 #7
0
func (p *ProviderService) Create(provider entity.IaaSProvider, token string) (newProvider entity.IaaSProvider, errorCode string, err error) {
	logrus.Infof("create provider [%v]", provider)
	errorCode, err = TokenValidation(token)
	if err != nil {
		logrus.Errorf("token validation failed for provider creation [%v]", err)
		return
	}

	// do authorize first
	if authorized := GetAuthService().Authorize("create_provider", token, "", p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("create provider [%v] error is %v", provider, err)
		return
	}

	userId := provider.UserId
	if len(userId) == 0 {
		err = errors.New("user_id not provided")
		errorCode = COMMON_ERROR_INVALIDATE
		logrus.Errorf("create provider [%v] error is %v", provider, err)
		return
	}

	user, err := GetUserById(userId, token)
	if err != nil {
		logrus.Errorf("get user by id err is %v", err)
		errorCode = COMMON_ERROR_INTERNAL
		return newProvider, errorCode, err
	}

	provider.ObjectId = bson.NewObjectId()
	provider.TenantId = user.TenantId
	// set created_time and updated_time
	provider.TimeCreate = dao.GetCurrentTime()
	provider.TimeUpdate = provider.TimeCreate

	err = dao.HandleInsert(p.collectionName, provider)
	if err != nil {
		errorCode = PROVIDER_ERROR_CREATE
		logrus.Errorf("create provider [%v] to bson error is %v", provider, err)
		return
	}

	newProvider = provider

	return

}
コード例 #8
0
func (p *UserService) UserUpdate(token string, newuser entity.User, userId string) (created bool, id string, errorCode string, err error) {
	code, err := GetTokenService().TokenValidate(token)
	if err != nil {
		return false, userId, code, err
	}

	if authorized := GetAuthService().Authorize("update_user", token, userId, p.userCollectionName); !authorized {
		logrus.Errorln("required opertion is not allowed!")
		return false, userId, COMMON_ERROR_UNAUTHORIZED, errors.New("Required opertion is not authorized!")
	}

	if !bson.IsObjectIdHex(userId) {
		logrus.Errorf("invalid user id format for user update %v", userId)
		return false, "", COMMON_ERROR_INVALIDATE, errors.New("Invalid object Id for user update")
	}

	selector := bson.M{}
	selector["_id"] = bson.ObjectIdHex(userId)

	queryStruct := dao.QueryStruct{
		CollectionName: p.userCollectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	user := new(entity.User)
	err = dao.HandleQueryOne(user, queryStruct)
	if err != nil {
		logrus.Errorf("get user by id error %v", err)
		return false, "", USER_ERROR_UPDATE, err
	}

	if len(newuser.Company) > 0 {
		user.Company = newuser.Company
	}
	if len(newuser.Email) > 0 {
		user.Email = newuser.Email
	}

	user.TimeUpdate = dao.GetCurrentTime()

	created, err = dao.HandleUpdateOne(user, queryStruct)
	return created, userId, "", nil
}
コード例 #9
0
func (p *HostService) Create(host entity.Host, x_auth_token string) (newHost entity.Host,
	errorCode string, err error) {
	logrus.Infof("start to create host [%v]", host)
	// do authorize first
	if authorized := GetAuthService().Authorize("create_host", x_auth_token, "", p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("create host [%v] error is %v", host, err)
		return
	}

	// generate ObjectId
	host.ObjectId = bson.NewObjectId()

	token, err := GetTokenById(x_auth_token)
	if err != nil {
		errorCode = HOST_ERROR_CREATE
		logrus.Errorf("get token failed when create host [%v], error is %v", host, err)
		return
	}

	// set token_id and user_id from token
	host.TenantId = token.Tenant.Id
	host.UserId = token.User.Id

	// set created_time and updated_time
	host.TimeCreate = dao.GetCurrentTime()
	host.TimeUpdate = host.TimeCreate

	// insert bson to mongodb
	err = dao.HandleInsert(p.collectionName, host)
	if err != nil {
		errorCode = HOST_ERROR_CREATE
		logrus.Errorf("insert host [%v] to db error is %v", host, err)
		return
	}

	newHost = host

	return
}
コード例 #10
0
func (p *HostService) UpdateStatusById(objectId string, status string, x_auth_token string) (created bool,
	errorCode string, err error) {
	logrus.Infof("start to update host by objectId [%v] status to %v", objectId, status)
	// do authorize first
	if authorized := GetAuthService().Authorize("update_host", x_auth_token, objectId, p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("update host with objectId [%v] status to [%v] failed, error is %v", objectId, status, err)
		return
	}
	// validate objectId
	if !bson.IsObjectIdHex(objectId) {
		err = errors.New("invalide ObjectId.")
		errorCode = COMMON_ERROR_INVALIDATE
		return
	}
	host, _, err := p.QueryById(objectId, x_auth_token)
	if err != nil {
		logrus.Errorf("get host by objeceId [%v] failed, error is %v", objectId, err)
		return
	}
	if host.Status == status {
		logrus.Infof("this host [%v] is already in state [%v]", host, status)
		return false, "", nil
	}
	var selector = bson.M{}
	selector["_id"] = bson.ObjectIdHex(objectId)

	change := bson.M{"status": status, "time_update": dao.GetCurrentTime()}
	err = dao.HandleUpdateByQueryPartial(p.collectionName, selector, change)
	if err != nil {
		logrus.Errorf("update host with objectId [%v] status to [%v] failed, error is %v", objectId, status, err)
		created = false
		return
	}
	created = true
	return

}
コード例 #11
0
// CheckAndGenerateToken check the token and creat the new token.
func (p *TokenService) checkAndGenerateToken(user string, passwd string, tenant string, needPasswd bool) (result string, err error) {
	//get user by name
	userobjAll, err := GetUserService().getAllUserByName(user)
	if err != nil {
		logrus.Errorf("get user by username err is %v", err)
		return result, err
	}
	if len(userobjAll) == 0 {
		logrus.Errorln("user does not exist! username:"******"user does not exit!")
	}
	userobj := userobjAll[0]

	//get tenant by name
	tenantobj, err := GetTenantService().getTenantByTenantId(tenant)
	if err != nil {
		logrus.Errorln("tenant does not exist! name:", tenant)
		return result, errors.New("tenant does not exist!")
	}

	tenantid := tenantobj.ObjectId.Hex()
	tenantname := tenantobj.Tenantname

	userid := userobj.ObjectId.Hex()
	password := userobj.Password
	role := userobj.RoleId

	if needPasswd {
		encryPassword := HashString(passwd)

		if !strings.EqualFold(encryPassword, password) {
			logrus.Errorln("invalid password!")
			return result, errors.New("invalid password!")
		}
	}

	//get role
	roleobj, err := GetRoleService().getRoleByRoleId(role)
	if err != nil {
		logrus.Errorln("role does not exist! rolename:", role)
		return result, errors.New("role does not exist!")
	}

	roleid := roleobj.ObjectId.Hex()

	time := common.UTIL.Props.GetString("expiration_time", "21600")
	newtime, err := strconv.ParseInt(strings.TrimSpace(time), 10, 64)
	if err != nil {
		logrus.Warnln("invalid expire time configured %v", err)
		newtime = int64(21600)
	}
	expireTime := GenerateExpireTime(newtime)
	currentTime := dao.GetCurrentTime()

	userpart := entity.UserPart{Id: userid, Username: user}
	tenantpart := entity.TenantPart{Id: tenantid, Tenantname: tenantname}
	rolepart := entity.RolePart{Id: roleid, Rolename: roleobj.Rolename}

	objectId := bson.NewObjectId()
	newtoken := entity.Token{
		ObjectId:   objectId,
		Expire:     expireTime,
		User:       userpart,
		Tenant:     tenantpart,
		Role:       rolepart,
		TimeCreate: currentTime,
		TimeUpdate: currentTime,
	}

	err = dao.HandleInsert(p.collectionName, &newtoken)
	result = newtoken.ObjectId.Hex()

	if err != nil {
		logrus.Errorf("save token err is %v", err)
		return result, err
	}

	return
}
コード例 #12
0
//terminate specified hosts of a cluster
func (p *ClusterService) TerminateHosts(clusterId string, hostIds []string, x_auth_token string) (errorCode string, err error) {
	logrus.Infof("start to decrease cluster hosts [%v]", hostIds)

	if !bson.IsObjectIdHex(clusterId) {
		err = errors.New("Invalid cluster_id")
		errorCode = COMMON_ERROR_INVALIDATE
		return
	}

	if len(hostIds) == 0 {
		errorCode = COMMON_ERROR_INVALIDATE
		err = errors.New("Empty array of host id")
		return errorCode, err
	}

	//query cluster by clusterId
	cluster := entity.Cluster{}
	clusterSelector := bson.M{}
	clusterSelector["_id"] = bson.ObjectIdHex(clusterId)
	err = dao.HandleQueryOne(&cluster, dao.QueryStruct{p.collectionName, clusterSelector, 0, 0, ""})

	_, currentHosts, errorCode, err := GetHostService().QueryHosts(clusterId, 0, 0, HOST_STATUS_RUNNING, x_auth_token)
	if err != nil {
		logrus.Errorf("get host by clusterId[%v] error [%v]", clusterId, err)
		return errorCode, err
	}

	if !deletable(currentHosts, hostIds) {
		logrus.Errorf("cluster's running node should not less than 5 nodes!")
		return CLUSTER_ERROR_DELETE_NODE_NUM, errors.New("cluster's running node should not less than 5 nodes!")
	}

	hosts := []entity.Host{}
	originStatus := make(map[string]string)
	directDeletedHosts := 0
	for _, hostId := range hostIds {
		//query host
		host, errorCode, err := GetHostService().QueryById(hostId, x_auth_token)
		if err != nil {
			return errorCode, err
		}

		//no host name means current host has not been created by docker-machine
		if len(strings.TrimSpace(host.HostName)) <= 0 {
			logrus.Warnf("host has no hostname, will be terminated directly, hostid: %s", hostId)
			_, _, err := GetHostService().UpdateStatusById(hostId, HOST_STATUS_TERMINATED, x_auth_token)
			if err != nil {
				logrus.Warnf("set no hostname host[%s] status to termianted error %v", hostId, err)
			}
			directDeletedHosts++
			continue
		}

		hosts = append(hosts, host)

		//protect master node
		if host.IsMasterNode {
			return HOST_ERROR_DELETE_MASTER, errors.New("Cannot delete master node")
		}

		originStatus[host.ObjectId.Hex()] = host.Status
		//call API to terminate host(master node cannot be deleted now)
		_, errorCode, err = GetHostService().UpdateStatusById(hostId, HOST_STATUS_TERMINATING, x_auth_token)
		if err != nil {
			logrus.Errorf("terminate host error is %s,%v", errorCode, err)
			continue
		}
	}

	if directDeletedHosts > 0 {
		logrus.Infof("update cluster instances - %d", directDeletedHosts)
		newvalue := cluster.Instances - directDeletedHosts
		selector := bson.M{}
		selector["_id"] = cluster.ObjectId

		change := bson.M{"instances": newvalue, "time_update": dao.GetCurrentTime()}
		erro := dao.HandleUpdateByQueryPartial(p.collectionName, selector, change)
		if erro != nil {
			logrus.Errorf("update cluster with objectId [%v] instances to [%d] failed, error is %v", clusterId, newvalue, erro)
		}
	}

	if len(hosts) <= 0 {
		logrus.Infof("no valid hosts will be deleted!")
		return
	}

	if IsDeploymentEnabled() {
		//call deployment module to delete nodes
		go DeleteNodes(cluster, hosts, originStatus, x_auth_token)
	}

	return
}
コード例 #13
0
func (p *ClusterService) DeleteById(clusterId string, x_auth_token string) (errorCode string, err error) {
	logrus.Infof("start to delete Cluster with id [%v]", clusterId)
	// do authorize first
	if authorized := GetAuthService().Authorize("delete_cluster", x_auth_token, clusterId, p.collectionName); !authorized {
		err = errors.New("required opertion is not authorized!")
		errorCode = COMMON_ERROR_UNAUTHORIZED
		logrus.Errorf("authorize failure when deleting cluster with id [%v] , error is %v", clusterId, err)
		return errorCode, err
	}
	if !bson.IsObjectIdHex(clusterId) {
		err = errors.New("Invalid cluster id.")
		errorCode = COMMON_ERROR_INVALIDATE
		return errorCode, err
	}

	//query cluster
	cluster, errorCode, err := p.QueryById(clusterId, x_auth_token)
	if err != nil {
		logrus.Errorf("query cluster error is %v", err)
		return errorCode, err
	}

	//check status
	switch cluster.Status {
	case CLUSTER_STATUS_DEPLOYING, CLUSTER_STATUS_TERMINATING, CLUSTER_STATUS_TERMINATED:
		logrus.Errorf("Cannot operate on a %s cluster", cluster.Status)
		return CLUSTER_ERROR_INVALID_STATUS, errors.New("Cannot operate on a " + cluster.Status + " cluster")

	case CLUSTER_STATUS_RUNNING, CLUSTER_STATUS_FAILED:
		//query all hosts
		var total int
		total, hosts, errorCode, err := GetHostService().QueryHosts(clusterId, 0, 0, "unterminated", x_auth_token)
		if err != nil {
			logrus.Errorf("query hosts in cluster %s error is %v", clusterId, err)
			return errorCode, err
		}

		successNode := 0
		directDeletedHosts := 0
		//set status of all hosts TERMINATING
		for _, host := range hosts {

			//no host name means current host has not been created by docker-machine
			if len(strings.TrimSpace(host.HostName)) <= 0 {
				hostId := host.ObjectId.Hex()
				logrus.Warnf("cluster[%s] host [%s] has no hostname, will be terminated directly", cluster.Name, hostId)
				_, _, err := GetHostService().UpdateStatusById(hostId, HOST_STATUS_TERMINATED, x_auth_token)
				if err != nil {
					logrus.Warnf("set no hostname host status to termianted error %v", err)
				}

				directDeletedHosts++
				continue
			}

			//deploying and terminating host is not allowed to be terminated
			if host.Status == HOST_STATUS_DEPLOYING || host.Status == HOST_STATUS_TERMINATING {
				logrus.Errorf("status of host [%v] is [%s], cluster can not be deleted!", host.HostName, host.Status)
				return CLUSTER_ERROR_DELETE_NOT_ALLOWED, errors.New("cannot delete cluster because not all nodes are ready")
			}

			//set host status to termianting
			_, _, err = GetHostService().UpdateStatusById(host.ObjectId.Hex(), HOST_STATUS_TERMINATING, x_auth_token)
			if err != nil {
				logrus.Warnf("delete host [objectId=%v] error is %v", host.ObjectId.Hex(), err)
			} else {
				successNode++
			}
		}

		logrus.Infof("Cluster %s has %d hosts, %d successfully terminating", cluster.Name, total, successNode)

		selector := bson.M{}
		selector["_id"] = cluster.ObjectId
		change := bson.M{"status": CLUSTER_STATUS_TERMINATING, "time_update": dao.GetCurrentTime()}
		if directDeletedHosts > 0 {
			logrus.Infof("update cluster instances - %d", directDeletedHosts)
			newvalue := cluster.Instances - directDeletedHosts
			change["instances"] = newvalue
		}
		logrus.Debugf("update cluster status and instance bson[%v]", change)
		erro := dao.HandleUpdateByQueryPartial(p.collectionName, selector, change)
		if erro != nil {
			logrus.Errorf("update cluster with objectId [%v] failed, error is %v", clusterId, erro)
		}

		if IsDeploymentEnabled() {
			//call deployment module API
			go DeleteCluster(cluster, x_auth_token)
		}
	default:
		logrus.Errorf("Unknown cluster status %s", cluster.Status)
		return CLUSTER_ERROR_INVALID_STATUS, errors.New("Unknown cluster status " + cluster.Status)
	}

	return
}
コード例 #14
0
func (p *ClusterService) CreateMgmtCluster(cluster entity.Cluster, x_auth_token string) (newCluster *entity.Cluster,
	errorCode string, err error) {
	//check if mgmt cluster already exist
	//only 1 allowed in database
	query := bson.M{}
	query["type"] = "mgmt"
	n, _, _, err := p.queryByQuery(query, 0, 0, "", x_auth_token, false)
	if n > 0 {
		return nil, CLUSTER_ERROR_CALL_MONGODB, errors.New("mgmt cluster already exist")
	}

	if cluster.Name == "" {
		cluster.Name = "Management"
	}
	token, err := GetTokenById(x_auth_token)
	if err != nil {
		logrus.Errorf("get token by id error is %v", err)
		errorCode = CLUSTER_ERROR_CALL_USERMGMT
		return nil, errorCode, err
	}
	if cluster.UserId == "" {
		cluster.UserId = token.User.Id
	}
	if cluster.Owner == "" {
		cluster.Owner = token.User.Username
	}
	if cluster.Details == "" {
		cluster.Details = "Cluster to manage other clusters"
	}
	cluster.TimeCreate = dao.GetCurrentTime()
	cluster.TimeUpdate = cluster.TimeCreate

	cluster.Status = CLUSTER_STATUS_DEPLOYING

	// insert bson to mongodb
	err = dao.HandleInsert(p.collectionName, cluster)
	if err != nil {
		errorCode = CLUSTER_ERROR_CALL_MONGODB
		logrus.Errorf("create cluster [%v] to bson error is %v", cluster, err)
		return
	}

	for i := 0; i < cluster.Instances; i++ {
		host := entity.Host{}
		host.ClusterId = cluster.ObjectId.Hex()
		host.ClusterName = cluster.Name
		host.Status = HOST_STATUS_DEPLOYING
		host.UserId = cluster.UserId
		host.TimeCreate = dao.GetCurrentTime()
		host.TimeUpdate = host.TimeCreate

		_, _, err := GetHostService().Create(host, x_auth_token)
		if err != nil {
			logrus.Errorf("insert host to db error is [%v]", err)
		}
	}

	newCluster = &cluster

	return
}
コード例 #15
0
//call dcos deployment module to add nodes
func AddNodes(cluster entity.Cluster, createNumber int, hosts []entity.Host, x_auth_token string) (err error) {
	request := new(dcosentity.AddNodeRequest)
	request.UserName = cluster.Owner
	request.ClusterName = cluster.Name
	request.CreateNumber = createNumber
	request.ExistedNumber = cluster.Instances
	request.ProviderInfo = getProvider(cluster.UserId, x_auth_token)

	//create hosts
	_, currentHosts, _, err := GetHostService().QueryHosts(cluster.ObjectId.Hex(), 0, 0, "unterminated", x_auth_token)
	if err != nil {
		logrus.Errorf("get current hosts by clusterId error %v", err)
		removeAddedNodes(hosts, x_auth_token)
		return err
	}

	request.ConsulServer, request.DnsServers, request.SwarmMaster = getNodeInfo(currentHosts)

	logrus.Debugf("add node request is %v", request)

	//call
	//dcos deployment module returns newly-created nodes info
	var servers *[]dcosentity.Server
	servers, err = SendAddNodesRequest(request)
	if err != nil {
		logrus.Errorf("send request to dcos deploy error is %v", err)
		removeAddedNodes(hosts, x_auth_token)
		return
	}

	ok_count := len(*servers)
	logrus.Infof("try to add %d nodes, %d success", createNumber, ok_count)

	//update newly-created hosts
	for i, server := range *servers {
		host := hosts[i]
		id := host.ObjectId.Hex()
		host.HostName = server.Hostname
		host.Status = HOST_STATUS_RUNNING
		host.IP = server.IpAddress
		host.PrivateIp = server.PrivateIpAddress
		host.IsMasterNode = server.IsMaster
		host.IsSlaveNode = server.IsSlave
		host.IsSwarmMaster = server.IsSwarmMaster
		host.TimeUpdate = dao.GetCurrentTime()
		_, _, err := GetHostService().UpdateById(id, host, x_auth_token)
		if err != nil {
			logrus.Errorf("update host error is [%v] \n", err)
		}
	}

	//update status of failed nodes
	for i := ok_count; i < createNumber; i++ {
		_, _, err := GetHostService().UpdateStatusById(hosts[i].ObjectId.Hex(), HOST_STATUS_FAILED, x_auth_token)
		if err != nil {
			logrus.Errorf("update host error is [%v] \n", err)
		}
	}

	//update cluster nodes number and status
	logrus.Infoln("update cluster number and status")
	cluster.Instances = cluster.Instances + len(hosts)
	cluster.Status = CLUSTER_STATUS_RUNNING
	GetClusterService().UpdateCluster(cluster, x_auth_token)
	// //update cluster status
	// logrus.Infoln("set cluster status to RUNNING")
	// GetClusterService().UpdateStatusById(cluster.ObjectId.Hex(), CLUSTER_STATUS_RUNNING, x_auth_token)
	return
}