models

package
v0.0.0-...-9649b88 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 16, 2020 License: Apache-2.0 Imports: 37 Imported by: 4

Documentation

Index

Constants

View Source
const (
	MaxIpsInGroup = 32
	IpsPrefix     = "["
	IpsSuffix     = "]"
	EmptyIP       = ""

	AddressMode IPMode
	CountMode
)
View Source
const (
	IPGroupTenantIDIndex  = "tenant_id"
	IPGroupNetworkIDIndex = "network_id"
)
View Source
const (
	NetworkNameIndex       = "name"
	NetworkTenantIDIndex   = "tenant_id"
	NetworkIsPublicIndex   = "is_public"
	NetworkIsExternalIndex = "is_external"
)
View Source
const (
	NetworkStatActive   = "ACTIVE"
	NetworkStatDown     = "DOWN"
	DefaultQuotaNoAdmin = 10
	DefaultQuotaAdmin   = 100
	MaxQuota            = 1000
	MAXIPSEG            = 4
	IPREG               = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +
		"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
		"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
		"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"
)
View Source
const (
	PortStatusActive = "ACTIVE"

	IPGroupKey = "IPGroup"
)
View Source
const (
	OpenStackOpsRetryTime      = 3
	OpenStackOpsRetryIntval    = 3
	CheckPortStatusIntval      = 5
	CheckPortStatusNerrumber   = 60
	CheckPortStatusIntvalShort = 3
	CheckPortStatusNumberShort = 3
)
View Source
const (
	PortTypeAttatched    = "AttatchedPort"
	PortTypeNonattatched = "NonattatchedPort"

	PortDetachOp = "NovaDetachPort"
	PortDeleteOp = "NeutronDeletePort"
)
View Source
const (
	NetworkIDIndex = "network_id"
	TenantIDIndex  = "tenant_id"
)
View Source
const (
	WaitCreating = iota
	Creating
	CreatedFailed
	CreatedOK
	WaitDestroy
	Destroyed
)

port life cycle status definition

View Source
const (
	CancelWaitPodsDeletedTimeout = 15 * 60
	CancelWaitPodsDeletedIntval  = 15
)
View Source
const CancelIntervalInSec = 20
View Source
const DefaultTTL int = 10
View Source
const KnitterManagerKeyRoot = "/knitter/manager"
View Source
const (
	SubnetNetworkIDIndex = "network_id"
)

Variables

View Source
var (
	QuotaNoAdmin int = DefaultQuotaNoAdmin
	QuotaAdmin   int = DefaultQuotaAdmin
)
View Source
var AnalyseCrtNets = func(cNets []*jason.Object) ([]*InitCNetwork, error) {
	var crtNets = make([]*InitCNetwork, 0)
	for _, net := range cNets {
		netName, err := net.GetString("name")
		if err != nil || netName == "" {
			klog.Errorf("AnalyseCrtNets name Error: %v ", err)
			return nil, errors.New("bad json[created_networks name]")
		}
		netCidr, err := net.GetString("cidr")
		if err != nil || netCidr == "" {
			klog.Errorf("AnalyseCrtNets[%v] Error: %v", netName, err)
			return nil, errors.New("bad json[cidr]")
		}
		netDesc, _ := net.GetString("desc")
		netPub, _ := net.GetBoolean("public")
		netGw, _ := net.GetString("gw")
		netAlcp := make([]subnets.AllocationPool, 0)
		netAllocation, errAlcp := net.GetObjectArray("allocation_pool")
		if errAlcp == nil {
			for _, alcp := range netAllocation {
				start, err := alcp.GetString("start")
				if err != nil || start == "" {
					klog.Errorf("GetString[start] Error: %v", err)
					return nil, errors.New("bad json[start]")
				}
				end, err := alcp.GetString("end")
				if err != nil || end == "" {
					klog.Errorf("GetString[end] Error: %v", err)
					return nil, errors.New("bad json[end]")
				}
				alcpObj := subnets.AllocationPool{
					Start: start,
					End:   end,
				}
				netAlcp = append(netAlcp, alcpObj)
			}
		}
		netType, _ := net.GetString("provider:network_type")
		phsicalNet, _ := net.GetString("provider:physical_network")
		netSegID, _ := net.GetString("provider:segmentation_id")
		netObj := &InitCNetwork{
			Name:            netName,
			Cidr:            netCidr,
			Desc:            netDesc,
			Public:          netPub,
			Gw:              netGw,
			AllocationPool:  netAlcp,
			NetworksType:    netType,
			PhysicalNetwork: phsicalNet,
			SegmentationID:  netSegID,
		}
		crtNets = append(crtNets, netObj)
	}

	return crtNets, nil
}
View Source
var AnalyseInitConfiguration = func(cfg *jason.Object) (*InitConfiguration, error) {
	edp, errEndpoint := cfg.GetString("endpoint")
	if errEndpoint != nil || edp == "" {
		klog.Errorf("GetObject[endpoint] Error: %v", errEndpoint)
		return nil, errors.New("bad json[endpoint]")
	}
	user, errUser := cfg.GetString("user")
	if errUser != nil || user == "" {
		klog.Errorf("GetObject[user] Error: %v", errUser)
		return nil, errors.New("bad json[user]")
	}
	paasword, errPaasword := cfg.GetString("password")
	if errPaasword != nil || paasword == "" {
		klog.Errorf("GetObject[password] Error: %v", errPaasword)
		return nil, errors.New("bad json[password]")
	}
	tenantName, _ := cfg.GetString("tenant_name")
	tenantID, _ := cfg.GetString("tenant_id")
	configurationObj := &InitConfiguration{
		EndPoint:   edp,
		User:       user,
		Password:   paasword,
		TenantName: tenantName,
		TenantID:   tenantID,
	}
	return configurationObj, nil
}
View Source
var AnalyseRegNets = func(rNets []*jason.Object) ([]*InitRNetwork, error) {
	var regNets []*InitRNetwork
	for _, net := range rNets {
		netName, _ := net.GetString("name")
		netID, err := net.GetString("uuid")
		if err != nil || netID == "" {
			klog.Errorf("AnalyseRegNets[%v] Error: %v", netName, err)
			return nil, errors.New("bad json[uuid]")
		}
		netDesc, _ := net.GetString("desc")
		netPub, _ := net.GetBoolean("public")
		netObj := &InitRNetwork{
			Name:   netName,
			UUID:   netID,
			Desc:   netDesc,
			Public: netPub,
		}
		regNets = append(regNets, netObj)
	}
	return regNets, nil
}
View Source
var AssembleResponse = func(iaasObj iaasaccessor.IaaS, port *iaasaccessor.Interface) (*mgragt.CreatePortResp, error) {
	subnet, err := getSubnetInfo(iaasObj, port.SubnetId)
	if err != nil {
		klog.Errorf("AssembleResponse: getSubnetInfo[subnetID: %s] failed, error: %v", port.SubnetId, err)
		delPortErr := iaasObj.DeletePort(port.Id)
		if delPortErr != nil {
			klog.Errorf(" assembleResponse: recyle port after attach->getport->failed failed, error: %v", delPortErr)
			klog.Errorf(" assembleResponse: EXCEPT-MARK->PORT[id:%s]", port.Id)

			SaveExceptPort(port.Id, PortTypeNonattatched, "", "create port failed, then delete it failed")
		}
		return nil, errors.New("AssembleResponse: GetSubnet error")
	}
	createPortRsp, err := makeResponse(port, subnet)
	if err != nil {
		klog.Errorf("AssembleResponse: makeResponse(port:[%v], subnet[%v]) failed, error: %v", port, subnet, err)
		delPortErr := iaasObj.DeletePort(port.Id)
		if delPortErr != nil {
			klog.Errorf(" assembleResponse: recyle port after attach->getport->failed failed, error: %v", delPortErr)
			klog.Errorf(" assembleResponse: EXCEPT-MARK->PORT[id:%s]", port.Id)

			SaveExceptPort(port.Id, PortTypeNonattatched, "", "create port failed, then delete it failed")
		}
		return nil, errors.New("AssembleResponse: makeResponse error")
	}
	return createPortRsp, nil
}
View Source
var AuthInitCfg = func(configurationObj *InitConfiguration) (*InitConfiguration, error) {
	opnCfg := openstack.OpenStackConf{
		Username:   configurationObj.User,
		Password:   configurationObj.Password,
		Url:        configurationObj.EndPoint,
		Tenantid:   configurationObj.TenantID,
		TenantName: configurationObj.TenantName,
	}
	client, errCheck := iaas.CheckOpenstackConfig(&opnCfg)
	if errCheck != nil {
		klog.Errorf("CheckOpenstackConfig Error: %v", errCheck)
		return nil, errobj.ErrAuth
	}
	configurationObj.TenantID = client.TenantID
	configurationObj.TenantName = client.TenantName
	return configurationObj, nil
}
View Source
var BeforeExecTenantCheck = func(ctx *context.Context) {
	userID := ctx.Input.Param(":user")
	if userID != constvalue.PaaSTenantAdminDefaultUUID {
		validUser := false
		tenantIds, err := GetAllNormalTenantIds()
		if err != nil {
			ctx.Redirect(http.StatusInternalServerError, ctx.Request.URL.RequestURI())
			ctx.Output.JSON(map[string]string{"ERROR": http.StatusText(http.StatusInternalServerError),
				"message": err.Error()}, false, false)
			return
		}
		for _, tenantID := range tenantIds {
			if userID == tenantID {
				validUser = true
				break
			}
		}

		if !validUser {
			ctx.Redirect(http.StatusNotFound, ctx.Request.URL.RequestURI())
			ctx.Output.JSON(map[string]string{"ERROR": "Bad Tenant Id",
				"message": "Bad Tenant Id[" + userID + "]"}, false, false)
		}
	}
}
View Source
var CancelTenant = func(tenantID string) error {
	klog.Infof("CancelTenant: delTenantAllNetworks for tenantID: %s START", tenantID)
	err := ClearTenantPods(tenantID)
	if err != nil {
		klog.Infof("CancelTenant: ClearTenantPods[tenantID: %s] error: %v", tenantID, err)
		return err
	}

	err = ClearIPGroups(tenantID)
	if err != nil {
		klog.Errorf("CancelTenant: ClearIPGroups for TenantID[%s] FAILED, error: %v", tenantID, err)
		return err
	}

	err = ClearLogicalPorts(tenantID)
	if err != nil {
		klog.Errorf("CancelTenant: ClearLogicalPorts for TenantID[%s] FAILED, error: %v", tenantID, err)
		return err
	}

	err = ClearPhysicalPorts(tenantID)
	if err != nil {
		klog.Errorf("CancelTenant: ClearPhysicalPorts for TenantID[%s] FAILED, error: %v", tenantID, err)
		return err
	}

	err = ClearNetworks(tenantID)
	if err != nil {
		klog.Errorf("CancelTenant: ClearNetworks TenantID[%s] FAILED, error: %v", tenantID, err)
		return err
	}

	err = deleteTenantDir(tenantID)
	if err != nil {
		klog.Errorf("CancelTenant: deleteTenantDir TenantID[%s] FAILED, error: %v", tenantID, err)
		return err
	}

	klog.Infof("CancelTenant: delTenantAllNetworks for tenantID: %s SUCC", tenantID)
	return nil
}
View Source
var CancelTenantLoop = func(tenantID string) {
	klog.Infof("CancelTenantLoop: goroutine cancel tenantID: %s START", tenantID)
	for {
		err := CancelTenant(tenantID)
		if err == nil {
			break
		}
		klog.Warningf("CancelTenantLoop: CancelTenant tenantID: %s error: %v, just wait and retry", err, tenantID)
		time.Sleep(time.Duration(CancelIntervalInSec) * time.Second)
	}
	klog.Infof("CancelTenantLoop: goroutine cancel tenantID: %s  SUCC", tenantID)
}
View Source
var CfgInit = func(cfgInput *jason.Object, ctx context.Context) error {
	RecyleInitConfFlag = false
	RecyleTmOutFlag = false
	DeferDelNetworks = make([]string, 0)
	opnCfg := openstack.OpenStackConf{
		Tenantid:   constvalue.DefaultIaasTenantID,
		TenantName: constvalue.DefaultIaasTenantName,
	}
	defer func() {
		if p := recover(); p != nil {
			klog.Errorf("CfgInitConf panic")
		}
		if RecyleInitConfFlag == true {
			RollBackInitConf(opnCfg.Tenantid)
		}
		if RecyleTmOutFlag == true {
			RollBackInitNets(DeferDelNetworks)
			RollBackInitConf(opnCfg.Tenantid)
		}
	}()
	select {
	case <-ctx.Done():
		RecyleTmOutFlag = true
		errBud := BuildErrWithCode(http.StatusRequestTimeout, errobj.ErrTmOut)
		return errBud
	default:
	}
	cfg, err := cfgInput.GetObject("init_configuration")
	if err != nil {
		klog.Errorf("GetObject[init_configuration] Error: %v", err)
		errBud := BuildErrWithCode(http.StatusUnsupportedMediaType, err)
		return errBud
	}

	klog.Infof("Scene is %v", Scene)
	if Scene == constvalue.TECS {
		initConfiguration, errGetCfg := GetInitConfiguraton(cfg)
		if errGetCfg != nil {
			klog.Errorf("GetInitConfiguraton Error: %v", errGetCfg)
			errBud := BuildErrWithCode(http.StatusUnauthorized, errGetCfg)
			return errBud
		}
		opnCfg = openstack.OpenStackConf{
			Username:   initConfiguration.User,
			Password:   initConfiguration.Password,
			Url:        initConfiguration.EndPoint,
			Tenantid:   initConfiguration.TenantID,
			TenantName: initConfiguration.TenantName,
		}
		value, _ := json.Marshal(opnCfg)
		errS := SaveOpenStackConfg(value)
		if errS != nil {
			klog.Errorf("SaveOpenStackConfg Error: %v", errS)
			errBud := BuildErrWithCode(http.StatusInternalServerError, err)
			return errBud
		}
		var req int = 0
		if iaas.GetIaaS(constvalue.PaaSTenantAdminDefaultUUID) != nil {
			req = iaas.GetIaaS(constvalue.PaaSTenantAdminDefaultUUID).GetAttachReq()
		}
		errI := iaas.InitIaaS()
		if errI != nil {
			klog.Errorf("InitIaaS Error: %v", errI)
			RecyleInitConfFlag = true
			errBud := BuildErrWithCode(http.StatusInternalServerError, errI)
			return errBud
		}
		if iaas.GetIaaS(constvalue.PaaSTenantAdminDefaultUUID) != nil {
			iaas.GetIaaS(constvalue.PaaSTenantAdminDefaultUUID).SetAttachReq(req)
		}
		err := iaas.SaveIaasTenantInfoToDB(&opnCfg)
		if err != nil {
			klog.Errorf("SaveIaasTenantInfoToDB err: %v", err)
			RecyleInitConfFlag = true
			return err
		}
	}
	if Scene == constvalue.VNM {
		defalutPhysnet, _ := GetDefaultProviderNetworkByInitConfig(cfg)
		err := UpdateDefaultPhysnet(defalutPhysnet)
		if err != nil {
			return err
		}
	}
	err = SaveAdminTenantInfoToDB(opnCfg.Tenantid, opnCfg.TenantName)
	if err != nil {
		klog.Errorf("SaveAdminTenantInfoToDB err: %v", err)
		RecyleInitConfFlag = true
		return err
	}
	errHandleInitNetworks := HandleInitNetworks(cfg)
	if errHandleInitNetworks != nil {
		klog.Errorf("HandleInitNetworks Error: %v", errHandleInitNetworks)
		RecyleInitConfFlag = true
		errBud := BuildErrWithCode(http.StatusInternalServerError, errHandleInitNetworks)
		return errBud
	}
	cfgByte, _ := cfgInput.Marshal()
	SaveInitConf(cfgByte)
	return nil
}
View Source
var CheckAllocationPools = func(allocationPools []subnets.AllocationPool, cidr string) error {
	if len(allocationPools) == 0 || cidr == "" {
		return errobj.ErrCheckAllocationPools
	}
	if IsAllocationPoolsInCidr(allocationPools, cidr) && !IsAllocationPoolsCoverd(allocationPools) {
		return nil
	}
	return errobj.ErrCheckAllocationPools
}
View Source
var CheckCreateNetInDefaultPhysnet = func(noAuthOpn iaasaccessor.IaaS) error {
	randNum := rand.Intn(100)
	testNetName := "test" + strconv.Itoa(randNum) + "physnet"
	net, err := noAuthOpn.CreateNetwork(testNetName)
	if err != nil {
		klog.Errorf("CheckPhysnet Err: CreateNetwork Err: %v", err)
		return err
	}
	errDel := noAuthOpn.DeleteNetwork(net.Id)
	if errDel != nil {
		klog.Errorf("CheckPhysnet Err: DeleteNetwork Err: %v", errDel)
		return errDel
	}
	return nil
}
View Source
var CheckCrtNets = func(crtNets []*InitCNetwork) ([]*InitCNetwork, error) {
	var cheInt int = 0
	netsFinal := make([]*InitCNetwork, 0)
	if Scene == constvalue.TECS {
		for _, net := range crtNets {
			net.SegmentationID = ""
			net.PhysicalNetwork = ""
			net.NetworksType = ""
			netsFinal = append(netsFinal, net)
		}
	} else if Scene == constvalue.VNM {
		for _, net := range crtNets {
			if net.NetworksType == "" {
				net.PhysicalNetwork = ""
				net.SegmentationID = ""
			}
			netsFinal = append(netsFinal, net)
		}
	} else if Scene == constvalue.EMBEDDED {
		for _, net := range crtNets {
			if net.Name == "net_api" {
				cheInt++
			}
			net.SegmentationID = ""
			net.PhysicalNetwork = ""
			net.NetworksType = ""
			netsFinal = append(netsFinal, net)
		}
		if cheInt != 1 {
			klog.Errorf("CheckCrtNets Error: control  media net_api not exist")
			return make([]*InitCNetwork, 0), errors.New("control media net_api is not exist")
		}
	} else {
		klog.Errorf("CheckCrtNets Error: unsupported scene")
		return make([]*InitCNetwork, 0), errors.New("unsupported scene")
	}
	return netsFinal, nil
}
View Source
var CheckPhysnet = func(opn iaasaccessor.IaaS) error {
	var errPhysnet error
	for i := 0; i < 3; i++ {
		errPhysnet = CheckCreateNetInDefaultPhysnet(opn)
		if errPhysnet != nil {
			klog.Errorf("InitNoauthOpenStack Err: CheckPhysnet Err: %v", errPhysnet)
			time.Sleep(5 * time.Second)
			continue
		}
		return nil
	}
	return errPhysnet
}
View Source
var CheckRegNets = func(regNets []*InitRNetwork) error {
	var cheInt int = 0
	for _, net := range regNets {
		if net.Name == "net_api" || net.Name == "net_mgt" {
			cheInt++
		}
	}
	if cheInt != 2 {
		klog.Errorf("CheckApiMgtNet Error: Api Mgt is not exist")
		return errors.New("api Mgt is not exist")
	}
	return nil
}
View Source
var CheckRestoreJobState = func(restoreJobStateMap map[string]*RestoreJobState) error {
	klog.Infof("CheckRestoreJobState: START")
	for _, v := range restoreJobStateMap {
		if v.State == -1 || v.State == 0 {
			RollBackEtcd(restoreJobStateMap)
			klog.Errorf("CheckRestoreJobState: restore job [%v]FAILED, job state is [%v]", v.JobDn, v.State)
			return errobj.ErrEtcdRestoreFromEtcdAdmToolFailed
		}
	}
	klog.Infof("CheckRestoreJobState: restore job SUCC")
	return nil
}
View Source
var ClearAllPortAndNetwork = func() error {
	klog.Info("ClearAllPodAndNetwork START")
	tenantIds, err := getAllTenantIds()
	if err != nil {
		if IsKeyNotFoundError(err) {
			klog.Infof("ClearAllPortAndNetwork: getAllTenantIds is nil, clear SUCC")
			return nil
		}
		klog.Errorf("ClearAllPortAndNetwork: gerAllTenantIds FAILED, ERROR: %v", err)
		return err
	}
	for _, tid := range tenantIds {
		err = ClearIPGroups(tid)
		if err != nil {
			klog.Errorf("ClearAllPortAndNetwork: ClearIPGroups(tenantId: %s) FAILED, error: %v",
				tid, err)
			return err
		}

		err = ClearLogicalPorts(tid)
		if err != nil {
			klog.Errorf("ClearAllPortAndNetwork: ClearLogicalPorts(tenantId: %s) FAILED, error: %v",
				tid, err)
			return err
		}
		err = ClearNetworks(tid)
		if err != nil {
			klog.Errorf("ClearAllPortAndNetwork: ClearPrivateNetworks(tenantId: %s) FAILED, error: %v", tid, err)
			return err
		}

	}
	klog.Info("ClearAllPortAndNetwork SUCC")
	return nil

}
View Source
var ClearDcs = func() error {
	dcsKey := dbaccessor.GetKeyOfDcs()
	err := common.GetDataBase().DeleteDir(dcsKey)
	if err != nil && !IsKeyNotFoundError(err) {
		klog.Errorf("ClearDcs: DeleteDir(key: %s)FAILED, error: %v", dcsKey, err)
		return err
	}
	return nil
}
View Source
var ClearIPGroups = func(tid string) error {
	igObjects, err := GetIPGroupObjRepoSingleton().ListByTenantID(tid)
	if err != nil {
		klog.Infof("ClearIPGroups:ListByTenantID(tenantID: %s) FAIL, error: %v", tid, err)
		return err
	}

	if len(igObjects) == 0 {
		klog.Info("ClearIPGroups: no ip groups left, omit it")
		return nil
	}

	for _, igObject := range igObjects {
		err = clearIPGroup(tid, igObject.ID)
		if err != nil {
			klog.Errorf("ClearIPGroups: clearIPGroup(ID: %s) FAILED, error: %v", igObject.ID, err)
			return err
		}
	}
	return nil
}
View Source
var ClearLogicalPorts = func(tid string) error {
	ports, err := GetPortObjRepoSingleton().ListByTenantID(tid)
	if err != nil {
		klog.Infof("ClearLogicalPorts:ListByTenantID(tenantID: %s) FAIL, error: %v", tid, err)
		return err
	}
	if len(ports) == 0 {
		klog.Info("ClearLogicalPorts: no ports left, omit it")
		return nil
	}

	for _, port := range ports {
		portID := port.ID
		err = clearLogicalPort(tid, portID)
		if err != nil {
			klog.Errorf("ClearLogicalPorts: clearLogicalPort(portID: %s) FAILED, error: %v", portID, err)
			return err
		}
	}
	return nil
}
View Source
var ClearNetworks = func(tenantID string) error {
	nets, err := GetNetObjRepoSingleton().ListByTenantID(tenantID)
	if err != nil {
		klog.Errorf("ClearNetworks: GetNetObjRepoSingleton().ListByTenantID(tenantID: %s) FAILED, error: %v",
			tenantID, err)
		return err
	}

	klog.Infof("ClearNetworks: start to clear tenantID: %s all networks: %v", tenantID, nets)
	for _, net := range nets {
		err := DeleteNetwork(net.ID)
		if err != nil {
			klog.Errorf("ClearNetworks: restorePrivNetwork: %s: %s FAILED, error: %v", tenantID, net.ID, err)
			return err
		}
	}
	klog.Infof("ClearNetworks: clear tenantID: %s all networks SUCC", tenantID)
	return nil
}
View Source
var ClearPhysicalPorts = func(tenantID string) error {
	ports, err := GetPhysPortObjRepoSingleton().ListByTenantID(tenantID)
	if err != nil {
		klog.Infof("ClearPhysicalPorts:ListByTenantID(tenantID: %s) FAIL, error: %v", tenantID, err)
		return err
	}
	if len(ports) == 0 {
		klog.Info("ClearPhysicalPorts: no ports left, omit it")
		return nil
	}

	for _, port := range ports {
		err = clearPhysicalPort(tenantID, port)
		if err != nil {
			klog.Errorf("ClearPhysicalPorts: clearPhysicalPort(%v) FAILED, error: %v", port, err)
			return err
		}
	}
	return nil
}
View Source
var ClearTenantPods = func(tenantID string) error {
	pods := waitTenantPodsDeleted(tenantID)
	if pods == nil || len(pods) == 0 {
		return nil
	}

	for _, pod := range pods {
		err := pod.Delete()
		if err != nil {
			klog.Errorf("ClearTenantPods: pod.Delete(podName: %s) FAIL, error: %v", pod.PodName, err)
			return err
		}
	}
	klog.Debugf("ClearTenantPods: delete all tenant: %s pods SUCC", tenantID)
	return nil
}
View Source
var CreateInitNetworks = func(crtNets []*InitCNetwork) error {
	var needCrtNets []*InitCNetwork
	netsAdmin, err := GetTenantOwnedNetworks(constvalue.PaaSTenantAdminDefaultUUID)
	if err != nil {
		klog.Errorf("CreateInitNetworks: GetTenantOwnedNetworks for tenantID: %s FAIL, error: %v",
			constvalue.PaaSTenantAdminDefaultUUID, err)
		return err
	}

	if netsAdmin == nil {
		needCrtNets = crtNets
	} else {
		needCrtNets = GetNeedCrtNets(crtNets, netsAdmin)
	}
	for _, crtNet := range needCrtNets {
		netID, err := CrtInitNetwork(*crtNet)
		if err != nil {
			klog.Errorf("Create init networks failed. error: %v", err)
			return err
		}
		DeferDelNetworks = append(DeferDelNetworks, netID)
	}
	return nil
}
View Source
var CreateNet = func(netObj *NetworkObject, subnet *SubnetObject) error {
	net := &Net{
		Network: iaasaccessor.Network{
			Name: netObj.Name,
			Id:   netObj.ID,
		},
		Subnet: iaasaccessor.Subnet{
			Id:        subnet.ID,
			NetworkId: subnet.NetworkID,
			Name:      subnet.Name,
			Cidr:      subnet.CIDR,
			GatewayIp: subnet.GatewayIP,
			TenantId:  subnet.TenantID,
		},
		Provider: iaasaccessor.NetworkExtenAttrs{
			Id:              netObj.ID,
			Name:            netObj.Name,
			NetworkType:     netObj.ExtAttrs.NetworkType,
			PhysicalNetwork: netObj.ExtAttrs.PhysicalNetwork,
			SegmentationID:  netObj.ExtAttrs.SegmentationID,
		},
		TenantUUID:  netObj.TenantID,
		Public:      netObj.IsPublic,
		ExternalNet: netObj.IsExternal,
		CreateTime:  netObj.CreateTime,
		Status:      netObj.Status,
		Description: netObj.Description,
	}

	if isProviderNetowrk(net) {
		err := createTenantProviderNet(net)
		klog.Errorf("CreateNet: createTenantProviderNet(net: %v) FAILED, error: %v", *net, err)
		return err
	}

	err := createTenantNet(net)
	if err != nil {
		klog.Errorf("CreateNet: createTenantNet(net: %v) FAILED, error: %v", *net, err)
		return err
	}
	return nil
}
View Source
var CrtInitNetwork = func(crtNet InitCNetwork) (string, error) {
	net := Net{}
	net.Network.Name = crtNet.Name
	net.Subnet.Cidr = crtNet.Cidr
	if crtNet.Gw != "" && !IsGatewayValid(crtNet.Gw, net.Subnet.Cidr) {
		klog.Errorf("CrtInitNetwork[%v] Error: invalid gateway[%v]", crtNet.Name, crtNet.Gw)
		return "", errors.New("invalid gateway")
	}
	net.Subnet.GatewayIp = crtNet.Gw
	if !IsLegalInitAllocationPools(crtNet.AllocationPool, net.Subnet.Cidr, net.Subnet.GatewayIp) {
		return "", errors.New("invalid allocation_pool")
	}
	net.Subnet.AllocationPools = crtNet.AllocationPool
	net.Public = crtNet.Public
	net.TenantUUID = constvalue.PaaSTenantAdminDefaultUUID
	net.Description = crtNet.Desc
	net.Provider.NetworkType = crtNet.NetworksType
	net.Provider.PhysicalNetwork = crtNet.PhysicalNetwork
	net.Provider.SegmentationID = crtNet.SegmentationID
	err := net.CheckQuota()
	if err != nil {
		return "", errors.New("check admin quota error")
	}
	err = net.Create()
	if err != nil {
		return "", err
	}
	net.SaveQuota()

	return net.Network.Id, nil
}
View Source
var DefaultCreateTenantTime string = time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC).Format("2006-01-02T15:04:05Z")
View Source
var DefaultPaaSNetwork string = constvalue.DefaultPaaSNetwork
View Source
var DeferDelNetworks []string = make([]string, 0)
View Source
var DelOpenStackConfg = func() error {
	key := dbaccessor.GetKeyOfOpenstack()
	err1 := common.GetDataBase().DeleteLeaf(key)
	if err1 != nil {
		klog.Error(err1)
		return err1
	}
	return nil
}
View Source
var DeleteNetwork = func(id string) error {
	netObj, err := GetNetObjRepoSingleton().Get(id)
	if err != nil {
		klog.Errorf("DelNetwork: Get NetworkObject [networkID: %s] from repo FAIL, error: %v", id, err)
		return err
	}

	if IsNetworkUsedByIPGroup(id, netObj.TenantID) {
		klog.Errorf("DelNetwork: network[id: %s] has ip group in use", netObj.ID)
		return errobj.ErrNetworkHasIGsInUse
	}

	if IsNetworkInUse(id) {
		klog.Errorf("DelNetwork: network[id: %s] has port in use", netObj.ID)
		return errobj.ErrNetworkHasPortsInUse
	}

	if !netObj.IsExternal {
		err = forceDeleteNetwork(netObj.TenantID, id)
		if err != nil && !isErrNetworkNotFound(err) {
			klog.Errorf("DelNetwork: delete forceDeleteNetwork(id: %s) from iaas FAIL, error: %v", id, err)
			return err
		}
		klog.Infof("DelNetwork: forceDeleteNetwork[id: %s] SUCC", netObj.ID)
	}

	subnets, err := GetSubnetObjRepoSingleton().ListByNetworID(id)
	if err != nil {
		klog.Errorf("DelNetwork: ListByNetworID [networkID: %s] from repo FAIL, error: %v", id, err)
		return err
	}

	for _, subnet := range subnets {
		err = DelSubnet(subnet.ID)
		if err != nil {
			klog.Errorf("DelNetwork: DelSubnet[id: %s] from DB FAIL, error: %v", subnet.ID, err)
			return err
		}
		err = GetSubnetObjRepoSingleton().Del(subnet.ID)
		if err != nil {
			klog.Errorf("DelNetwork: del subnetObject[id: %s] from repo FAIL, error: %v", subnet.ID, err)
			return err
		}
	}

	err = DelNetwork(id)
	if err != nil {
		klog.Errorf("DelNetwork: DelNetwork[id: %s] from DB FAIL, error: %v", id, err)
		return err
	}

	err = GetNetObjRepoSingleton().Del(id)
	if err != nil {
		klog.Errorf("DelNetwork: delete NetworkObject[id: %s] from repo FAIL, error: %v", id, err)
		return err
	}

	err = Net{TenantUUID: netObj.TenantID}.SaveQuota()
	if err != nil {
		klog.Errorf("DelNetwork: SaveQuota[tenantID: %s] FAIL, error: %v", netObj.TenantID, err)
		return err
	}

	klog.Tracef("DelNetwork: delete network[id: %s] SUCC", id)
	return nil
}
View Source
var GetAdminPublicNetIds = func() ([]string, error) {
	pubNetsKey := dbaccessor.GetKeyOfNetworkGroup(adminTenantID)
	nodes, err := common.GetDataBase().ReadDir(pubNetsKey)
	if err != nil {
		klog.Errorf("GetAdminPublicNetIds: ReadDir(key: %s) FAILED, error: %v", pubNetsKey, err)
		return nil, err
	}

	netIds := []string{}
	for _, node := range nodes {
		netID := strings.TrimPrefix(node.Key, pubNetsKey+"/")
		netKey := dbaccessor.GetKeyOfNetworkSelf(adminTenantID, netID)
		value, err := common.GetDataBase().ReadLeaf(netKey)
		if err != nil {
			klog.Errorf("GetAdminPublicNetIds: ReadLeaf[key: %s] FAILED, error: %v", netKey, err)
			return nil, err
		}
		if !isNetworkPublic(value) {
			continue
		}
		netIds = append(netIds, netID)
	}
	klog.Infof("GetAdminPublicNetIds: get all public network ids: %v SUCC", netIds)
	return netIds, nil
}
View Source
var GetAllocationPools = func(allocationPools []*jason.Object, cidr, gw string) ([]subnets.AllocationPool, error) {
	var pools []subnets.AllocationPool
	if len(allocationPools) == 0 {
		return []subnets.AllocationPool{}, nil
	}
	if !IsCidrLegal(cidr) {
		return []subnets.AllocationPool{}, errobj.ErrCheckAllocationPools
	}
	for _, pool := range allocationPools {
		startIP, _ := pool.GetString("start")
		endIP, _ := pool.GetString("end")
		allocationPool := subnets.AllocationPool{
			Start: startIP,
			End:   endIP,
		}
		if IsFixIPInIPRange(gw, allocationPool) {
			return []subnets.AllocationPool{}, errobj.ErrCheckAllocationPools
		}
		pools = append(pools, allocationPool)
	}
	if IsAllocationPoolsLegal(pools, cidr) {
		return pools, nil
	}
	return []subnets.AllocationPool{}, errobj.ErrCheckAllocationPools
}
View Source
var GetAllocationPoolsByCidr = func(cidr string) []subnets.AllocationPool {
	if !IsCidrLegal(cidr) {
		return []subnets.AllocationPool{}
	}
	MinIP, MaxIP := GetCidrIPRange(cidr)
	allocationPools := []subnets.AllocationPool{
		{
			Start: MinIP,
			End:   MaxIP,
		},
	}
	return allocationPools
}
View Source
var GetCancellingTenantsInfo = func() []string {
	klog.Infof("GetCancellingTenantsInfo: START")
	tids, err := getAllTenantIds()
	if err != nil {
		klog.Errorf("GetCancellingTenantsInfo: getAllTenantIds FAILED, error: %v", err)
		return nil
	}

	var cancellingTenantIDs []string
	for _, tid := range tids {
		if !isTenantCancellable(tid) {
			klog.Infof("GetCancellingTenantsInfo: isTenantCancellable(id: %s) FAILED, error: %v", tid, err)
			continue
		}

		tenantInfo, err := getTenantInfo(tid)
		if err != nil {
			klog.Errorf("GetCancellingTenantsInfo: getTenantInfo FAILED, error: %v", err)
			continue
		}
		if tenantInfo.IsCancelling {
			cancellingTenantIDs = append(cancellingTenantIDs, tenantInfo.TenantUUID)
		}
	}

	klog.Infof("GetCancellingTenantsInfo: SUCC, get all cancelling"+
		" tenantIDs : %v", cancellingTenantIDs)
	return cancellingTenantIDs
}
View Source
var GetCidrIPRange = func(cidr string) (string, string) {
	if cidr == "" {
		return "", ""
	}
	ip := strings.Split(cidr, "/")[0]
	ipSegs := strings.Split(ip, ".")
	maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1])
	seg2MinIP, seg2MaxIP := GetIPSeg2Range(ipSegs, maskLen)
	seg3MinIP, seg3MaxIP := GetIPSeg3Range(ipSegs, maskLen)
	seg4MinIP, seg4MaxIP := GetIPSeg4Range(ipSegs, maskLen)
	ipPrefix := ipSegs[0] + "."
	return ipPrefix + strconv.Itoa(seg2MinIP) + "." + strconv.Itoa(seg3MinIP) + "." + strconv.Itoa(seg4MinIP),
		ipPrefix + strconv.Itoa(seg2MaxIP) + "." + strconv.Itoa(seg3MaxIP) + "." + strconv.Itoa(seg4MaxIP)
}
View Source
var GetEtcdAdmToolRestoreURL = func(msbUrl string) string {
	return msbUrl + "/etcdat/v1/tenants/admin/restore"
}
View Source
var GetIPSeg2Range = func(ipSegs []string, maskLen int) (int, int) {
	if maskLen > 16 {
		segIP, _ := strconv.Atoi(ipSegs[1])
		return segIP, segIP
	}
	ipSeg, _ := strconv.Atoi(ipSegs[1])
	return GetIPSegRange(uint8(ipSeg), uint8(16-maskLen))
}
View Source
var GetIPSeg3Range = func(ipSegs []string, maskLen int) (int, int) {
	if maskLen > 24 {
		segIP, _ := strconv.Atoi(ipSegs[2])
		return segIP, segIP
	}
	ipSeg, _ := strconv.Atoi(ipSegs[2])
	return GetIPSegRange(uint8(ipSeg), uint8(24-maskLen))
}
View Source
var GetIPSeg4Range = func(ipSegs []string, maskLen int) (int, int) {
	ipSeg, _ := strconv.Atoi(ipSegs[3])
	segMinIP, segMaxIP := GetIPSegRange(uint8(ipSeg), uint8(32-maskLen))
	return segMinIP + 1, segMaxIP - 1
}
View Source
var GetIPSegRange = func(userSegIP, offset uint8) (int, int) {
	var ipSegMax uint8 = 255
	netSegIP := ipSegMax << offset
	segMinIP := netSegIP & userSegIP
	segMaxIP := userSegIP&(255<<offset) | ^(255 << offset)
	return int(segMinIP), int(segMaxIP)
}
View Source
var GetInitConfiguraton = func(cfg *jason.Object) (*InitConfiguration, error) {
	config, errConfiguration := cfg.GetObject("configuration")
	if errConfiguration != nil || config == nil {
		klog.Errorf("GetObject[configuration] Error: %v", errConfiguration)
		return nil, errors.New("get configuration error, bad json[configuration]")
	}
	configurationObj, errAna := AnalyseInitConfiguration(config)
	if errAna != nil {
		klog.Errorf("AnalyseConfiguration Error: %v", errAna)
		return nil, errors.New("analyse configuration error, " + errAna.Error())
	}
	confAfterAuth, errAuth := AuthInitCfg(configurationObj)
	if errAuth != nil {
		klog.Errorf("AuthInitCfg Error: %v", errAuth)
		return nil, errobj.ErrAuth
	}
	return confAfterAuth, nil
}
View Source
var GetMsbURL = func() (string, error) {
	managerKey := dbaccessor.GetKeyOfKnitterManagerUrl()
	managerStr, err := common.GetDataBase().ReadLeaf(managerKey)
	if err != nil {
		klog.Errorf("GetMsbUrl: read key : [%s] FAILED, ERROR: %v", managerKey, err)
		return "", err
	}
	return strings.Split(managerStr, "/nw")[0], err
}
View Source
var GetNeedCrtNets = func(crtNets []*InitCNetwork, netsAdmin []*PaasNetwork) []*InitCNetwork {
	needCrtNets := make([]*InitCNetwork, 0)
	for _, crtNet := range crtNets {
		flag := false
		for _, netAdmin := range netsAdmin {
			if !netAdmin.ExternalNet && crtNet.Name == netAdmin.Name && crtNet.Cidr == netAdmin.Cidr {
				flag = true
				break
			}
		}
		if !flag {
			needCrtNets = append(needCrtNets, crtNet)
		}
	}
	return needCrtNets
}
View Source
var GetNeedRegNets = func(regNets []*InitRNetwork, netsAdmin []*PaasNetwork) []*InitRNetwork {
	needRegNets := make([]*InitRNetwork, 0)
	for _, regNet := range regNets {
		flag := false
		for _, netAdmin := range netsAdmin {
			if regNet.UUID == netAdmin.ID && netAdmin.ExternalNet {
				flag = true
				break
			}
		}
		if !flag {
			needRegNets = append(needRegNets, regNet)
		}
	}
	return needRegNets
}
View Source
var GetNetNumOfTenant = func(tenantID string) int {
	netObjs, err := GetNetObjRepoSingleton().ListByTenantID(tenantID)
	if err != nil {
		klog.Warningf("GetNetNumOfTenant: ListByTenantID[tenantID: %s] FAIL, error:%v", tenantID, err)
		return 0
	}
	return len(netObjs)
}
View Source
var GetNetwork = func(net *Net) (*PaasNetwork, error) {
	return GetNetworkByName(net.TenantUUID, net.Network.Name)
}
View Source
var GetPodsOfTenant = func(tid string) []*Pod {
	pod := &Pod{}
	pod.SetTenantID(tid)
	return PodListAll(pod)
}

todo: will be replaced by upper GetTenantPods()

View Source
var GetPortServiceObj = func() PortServiceAPI {
	return PortServiceObj
}
View Source
var GetRestoreJobStates = func(etcdAdmToolRestoreUrl string, restoreJobStateMap map[string]*RestoreJobState) {
	klog.Infof("GetRestoreJobStates START")
	for i := 0; i < constvalue.GetRestoreStateRetryTimes; i++ {
		klog.Infof("GetRestoreJobStates: [%s] time ", i)
		for k, v := range restoreJobStateMap {
			url := etcdAdmToolRestoreUrl + "?jobDn=" + v.JobDn
			klog.Infof("GetRestoreJobStates:HTTPGet(%s)", url)
			resp, err := HTTPGet(url)
			if err != nil {
				klog.Errorf("GetRestoreJobState:HTTPGet(%s) FAILED, ERROR: %v", url, err)
				continue
			}
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				resp.Body.Close()
				klog.Errorf("GetRestoreJobState:ioutil.ReadAll(%s) FAILED, ERROR: %v", string(body), err)
				continue
			}
			resp.Body.Close()
			klog.Infof("GetRestoreJobState: jason.NewObjectFromBytes(%s)", string(body))
			jobStateBody, err := jason.NewObjectFromBytes(body)
			if err != nil {
				klog.Errorf("GetRestoreJobState:jason.NewObjectFromBytes(%s) FAILED, ERROR: %v", string(body), err)
				continue
			}
			jobStateTmp, err := jobStateBody.GetInt64("state")
			klog.Info("GetRestoreJobState:[jobStateTmp: %v]", jobStateTmp)
			if err != nil {
				klog.Errorf("GetRestoreJobState:jobStateBody.GetString(%s) ERROR:%v", err, jobStateTmp)
			}
			jobStateDetail, err := jobStateBody.GetString("detail")
			klog.Info("GetRestoreJobState:[jobStateDetail:%v]", jobStateDetail)
			if err != nil {
				klog.Errorf("Get:RestoreJobState:jobStateBody.GetString(detail) ERROR:%v", err)

			}
			jobState := int(jobStateTmp)
			klog.Infof("GetRestoreJobState:strings.Contains:[%v]", strings.Contains(jobStateDetail, "directory not exist"), jobState)
			if jobState == constvalue.RestoreProgressStatProcessFail && strings.Contains(jobStateDetail, "directory not exist") {
				jobState = constvalue.RestoreProgressStatProcessSucc
			}
			restoreJobStateMap[k].State = jobState
		}
		finishedJobTotalNum := 0
		for _, v := range restoreJobStateMap {
			if v.State == constvalue.RestoreProgressStatProcessSucc {
				finishedJobTotalNum++
			}
			if v.State == constvalue.RestoreProgressStatProcessFail {
				klog.Infof("GetRestoreJobState:[v.state = %v] return ", v.State)
				return
			}
		}
		if finishedJobTotalNum == len(restoreJobStateMap) {
			break
		}
		time.Sleep(5 * time.Second)
	}
	klog.Infof("GetRestoreJobStates END")

}
View Source
var HTTPGet = func(url string) (*http.Response, error) {
	klog.Infof("HttpGet: request url=%v", url)

	resp, err := HTTPGetFunc(url)

	if err != nil {
		klog.Errorf("HttpGet err: %v", err)
		return nil, err
	}
	if resp.StatusCode != 200 {
		klog.Errorf("HttpGet:status code: %d", resp.StatusCode)
		return nil, errobj.ErrHTTPPostStatusCode
	}
	return resp, nil
}
View Source
var HTTPGetFunc = func(url string) (resp *http.Response, err error) {
	return http.Get(url)
}
View Source
var HTTPPostFunc = func(url string, contentType string, body io.Reader) (resp *http.Response, err error) {
	return http.Post(url, contentType, body)
}
View Source
var HandleInitNetworks = func(cfg *jason.Object) error {
	DeferDelNetworks = make([]string, 0)
	RecyleInitNetsFlag = false
	defer func() {
		if p := recover(); p != nil {
			klog.Errorf("HandleInitNetworks panic")
		}
		if RecyleInitNetsFlag == true {
			RollBackInitNets(DeferDelNetworks)
		}
	}()
	var err error

	klog.Infof("Scene is %v", Scene)
	networks, errGetObject := cfg.GetObject("networks")
	if errGetObject != nil || networks == nil {
		klog.Errorf("GetObject[networks] Error: %v", errGetObject)
		return errors.New("bad json[networks]")
	}
	err = InitCNetworks(networks)
	if err != nil {
		klog.Errorf("Init register network error: %v", err)
		RecyleInitNetsFlag = true
		return err
	}
	return nil
}
View Source
var InitCNetworks = func(networks *jason.Object) error {
	cNetworks, err := networks.GetObjectArray("created_networks")
	if err != nil || len(cNetworks) == 0 {
		klog.Warningf("Networks for created are nil")
		return nil
	}
	crtNets, err := AnalyseCrtNets(cNetworks)
	if err != nil {
		klog.Errorf("Analyse create networks failed! error: %v", err)
		return err
	}
	netsCrtFinal, err := CheckCrtNets(crtNets)
	if err != nil {
		klog.Errorf("Analyse register networks failed! error: %v", err)
		return err
	}
	err = CreateInitNetworks(netsCrtFinal)
	if err != nil {
		klog.Errorf("Create networks failed! error: %v", err)
		return err
	}
	return nil
}
View Source
var InitRNetworks = func(networks *jason.Object) error {
	rNetworks, err := networks.GetObjectArray("registered_networks")
	if err != nil || len(rNetworks) == 0 {
		klog.Errorf("GetObject[registered_networks] Error: %v", err)
		return errors.New("bad json[registered_networks]")
	}
	regNets, err := AnalyseRegNets(rNetworks)
	if err != nil {
		klog.Errorf("Analyse register networks failed! error: %v", err)
		return err
	}
	err = CheckRegNets(regNets)
	if err != nil {
		klog.Errorf("Check register networks failed! error: %v", err)
		return err
	}
	err = RegisterInitNetworks(regNets)
	if err != nil {
		klog.Errorf("Register networks failed! error: %v", err)
		return err
	}
	return nil
}
View Source
var IsAllocationPoolsCoverd = func(allocationPools []subnets.AllocationPool) bool {
	if len(allocationPools) == 0 {
		return true
	}
	for i := 0; i < len(allocationPools); i++ {
		for j := 0; j < len(allocationPools); j++ {
			if i == j {
				continue
			}
			if IsFixIPInIPRange(allocationPools[i].Start, allocationPools[j]) {
				return true
			}
		}
	}
	return false
}
View Source
var IsAllocationPoolsInCidr = func(allocationPools []subnets.AllocationPool, cidr string) bool {
	for _, pool := range allocationPools {
		if !IsFixIPInCidr(pool.Start, cidr) || !IsFixIPInCidr(pool.End, cidr) {
			return false
		}
	}
	return true
}
View Source
var IsAllocationPoolsLegal = func(allocationPools []subnets.AllocationPool, cidr string) bool {
	if len(allocationPools) == 0 || cidr == "" {
		return false
	}
	for _, pool := range allocationPools {
		startIPByte := net.ParseIP(pool.Start)
		endIPByte := net.ParseIP(pool.End)
		if bytes.Compare(startIPByte, endIPByte) > 0 {
			return false
		}
	}
	err := CheckAllocationPools(allocationPools, cidr)
	if err != nil {
		return false
	}
	return true
}
View Source
var IsCidrLegal = func(cidr string) bool {
	cidrInfo := strings.Split(cidr, "/")
	if len(cidrInfo) != 2 {
		return false
	}
	bl, _ := isIPLegitimate(cidrInfo[0])
	maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1])
	if maskLen < 8 || !bl {
		return false
	}
	return true
}
View Source
var IsFixIPInCidr = func(ip, cidr string) bool {
	_, ipNet, _ := net.ParseCIDR(cidr)
	tmpIP := net.ParseIP(ip)
	if ipNet.Contains(tmpIP) {
		return true
	}
	return false
}
View Source
var IsFixIPInIPRange = func(ip string, allocationPool subnets.AllocationPool) bool {
	if ip == "" || allocationPool.Start == "" || allocationPool.End == "" {
		return false
	}

	startIPByte := net.ParseIP(allocationPool.Start)
	endIPByte := net.ParseIP(allocationPool.End)
	ipByte := net.ParseIP(ip)
	if bytes.Compare(ipByte, startIPByte) >= 0 && bytes.Compare(ipByte, endIPByte) <= 0 {
		return true
	}

	return false
}
View Source
var IsGatewayValid = func(gwip, cidr string) bool {
	ipad := net.ParseIP(gwip)
	if ipad == nil {
		return false
	}
	ip, network, err := net.ParseCIDR(cidr)
	if err != nil {
		return false
	}
	return ip.Equal(ipad.Mask(network.Mask))
}
View Source
var IsLegalInitAllocationPools = func(allocationPools []subnets.AllocationPool, cidr, gw string) bool {
	if len(allocationPools) == 0 {
		klog.Warningf("IsLegalInitAllocationPools Warning: len allocationPools is 0")
		return true
	}
	if !IsCidrLegal(cidr) {
		klog.Errorf("IsLegalInitAllocationPools Error: cidr is not right")
		return false
	}
	for _, pool := range allocationPools {
		if IsFixIPInIPRange(gw, pool) {
			klog.Errorf("IsLegalInitAllocationPools Error: gw is in IP range")
			return false
		}
	}
	if !IsAllocationPoolsLegal(allocationPools, cidr) {
		klog.Errorf("IsLegalInitAllocationPools Error: pools[start or end] is not right")
		return false
	}
	return true
}
View Source
var MakeRestoreStateMap = func(etcdRestorejob RestoreReq) map[string]*RestoreJobState {
	var restoreJobStateMap = make(map[string]*RestoreJobState)
	restoreJobStateMap["tenants"] = &RestoreJobState{JobDn: etcdRestorejob.JobID + "_tenants", State: 0}
	restoreJobStateMap["public"] = &RestoreJobState{JobDn: etcdRestorejob.JobID + "_public", State: 0}
	restoreJobStateMap["dcs"] = &RestoreJobState{JobDn: etcdRestorejob.JobID + "_dcs", State: 0}
	return restoreJobStateMap
}
View Source
var NwRestore = func(RestoreReq RestoreReq) error {
	jobDn := RestoreReq.JobID
	klog.Infof("NwRestore: restore jobDn: %s START", jobDn)
	klog.Infof("NwRestore: jobDn: %s start to judge pod not exist", jobDn)
	err := ShouldNotPodExist()
	if err != nil {
		klog.Errorf("NwRestore: ShouldNotPodExist FAILED, error: %v", err)
		return err
	}

	klog.Infof("NwRestore: jobDn: %s start to clear pod and network", jobDn)
	err = ClearAllPortAndNetwork()
	if err != nil {
		klog.Errorf("NwRestore: ClearPodAndNetwork FAILED, error: %v", err)
	}

	klog.Infof("NwRestore: jobDn: %s start to restore from etcd-admtool", jobDn)
	err = RestoreFromEtcd(RestoreReq)
	if err != nil {
		klog.Errorf("NwRestore: RestoreFromETcd FAILED, error: %v", err)
		return err
	}
	err = RestoreTenants()
	if err != nil {
		klog.Errorf("NwRestore: RestoreTenants FAILED, error: %v", err)
		return err
	}

	klog.Infof("NwRestore: jobDn: %s start to RestorePublic", jobDn)
	err = RestorePublic()
	if err != nil && !IsKeyNotFoundError(err) {
		klog.Errorf("NwRestore: RestorePublic FAILED, error: %v", err)
		return err
	}

	klog.Infof("NwRestore: jobDn: %s start to ClearDcs", jobDn)
	err = ClearDcs()
	if err != nil {
		klog.Errorf("NwRestore: ClearDcs FAILED, error: %v", err)
		return err
	}
	err = RecoverInitNetwork()
	if err != nil {
		klog.Errorf("NwRestore: RecoverInitNetwork() FAILED, error : %v", err)
		return err
	}
	klog.Infof("NwRestore: restore jobDn: %s SUCC", jobDn)
	return nil

}
View Source
var PodListAll = func(pod *Pod) []*Pod {
	return pod.ListAll()
}
View Source
var ReadInitConf = func() (string, error) {
	key := dbaccessor.GetKeyOfInitConf()
	value, err := common.GetDataBase().ReadLeaf(key)
	if err != nil {
		klog.Errorf("ReadInitConf Error: %v", err)
		return "", err
	}
	return value, nil
}
View Source
var RecoverInitNetwork = func() error {
	value, err := ReadInitConf()
	if err != nil {
		klog.Errorf("RecoverInitNetwork Error: ReadInitConf err[%v]", err)
		return err
	}
	cfg, err := jason.NewObjectFromBytes([]byte(value))
	if err != nil {
		klog.Errorf("RecoverInitNetwork Error: NewObjectFromBytes err[%v]", err)
		return err
	}
	cfgNet, err := cfg.GetObject("init_configuration")
	if err != nil {
		klog.Errorf("GetObject[init_configuration] Error: %v", err)
		return err
	}
	errHandle := HandleInitNetworks(cfgNet)
	if errHandle != nil {
		klog.Errorf("RecoverInitNetwork Error: HandleInitNetworks err[%v]", errHandle)
		return errHandle
	}
	return nil
}
View Source
var RecyleInitConfFlag bool = false
View Source
var RecyleInitNetsFlag bool = false
View Source
var RecyleTmOutFlag bool = false
View Source
var RegInitNetwork = func(regNet InitRNetwork) (string, error) {
	var net *Net = &Net{}
	net.TenantUUID = constvalue.PaaSTenantAdminDefaultUUID
	net.Network.Id = regNet.UUID
	net.Public = regNet.Public
	net.ExternalNet = true
	err := net.CheckQuota()
	if err != nil {
		klog.Errorf("CheckQuota Error: %v", err)
		return "", errors.New("check admin quota error")
	}
	subidFromIaas, err := iaas.GetIaaS(constvalue.PaaSTenantAdminDefaultUUID).GetSubnetID(regNet.UUID)
	if err != nil {
		klog.Errorf("Get subnetwork ID error: %v", err)
		return "", err
	}
	net.Subnet.Id = subidFromIaas
	err = net.getNetWorkInfoFromIaas(net.Subnet.Id)
	if err != nil {
		klog.Errorf("Get subnetwork by ID error:%v", err)
		return "", err
	}
	net.Status = NetworkStatActive
	net.CreateTime = time.Now().UTC().Format("2006-01-02T15:04:05Z")

	err = saveNetwork(net, &net.Network, &net.Subnet, &net.Provider)
	if err != nil {
		klog.Errorf("Save network info error: %v", err)
		return "", errors.New("save network[" + net.Network.Name + "] error")
	}
	net.SaveQuota()
	return regNet.UUID, nil
}
View Source
var RegisterInitNetworks = func(regNets []*InitRNetwork) error {
	var needRegNets []*InitRNetwork
	netsAdmin, err := GetTenantOwnedNetworks(constvalue.PaaSTenantAdminDefaultUUID)
	if err != nil {
		klog.Errorf("RegisterInitNetworks: GetTenantOwnedNetworks for tenantID: %s FAIL, error: %v",
			constvalue.PaaSTenantAdminDefaultUUID, err)
		return err
	}

	if netsAdmin == nil {
		needRegNets = regNets
	} else {
		needRegNets = GetNeedRegNets(regNets, netsAdmin)
	}
	for _, regNet := range needRegNets {
		netID, err := RegInitNetwork(*regNet)
		if err != nil {
			klog.Errorf("Register init networks failed. error: %v", err)
			return err
		}
		DeferDelNetworks = append(DeferDelNetworks, netID)
	}
	return nil
}
View Source
var RestoreFromEtcd = func(etcdRestorejob RestoreReq) error {
	klog.Infof("RestoreFromEtcd: RestoreFromEtcd START")

	klog.Infof("Preparing to send restore Post ")

	msbURL, err := GetMsbURL()
	if err != nil {
		klog.Errorf("RestoreFromEtcd: getMsbUrl() FAILED, ERROR: %v", err)
		return err
	}
	etcdAdmToolRestoreURL := GetEtcdAdmToolRestoreURL(msbURL)
	restoreJobStateMap := MakeRestoreStateMap(etcdRestorejob)
	klog.Info("Send restore jobs to etcdAdmTool")
	SendRestoreJobs(etcdAdmToolRestoreURL, etcdRestorejob, restoreJobStateMap)

	time.Sleep(1 * time.Second)
	klog.Info("Get restore jobs states")
	GetRestoreJobStates(etcdAdmToolRestoreURL, restoreJobStateMap)

	err = CheckRestoreJobState(restoreJobStateMap)
	if err != nil {
		klog.Errorf("RestoreFromEtcd : RestoreFromEtcd FAILED,error: %v", err)
		return err
	}
	klog.Infof("RestoreFromEtcd: RestoreFromEtcd SUCC")
	return nil

}
View Source
var RestoreNetworks = func(tenantId string) error {
	klog.Infof("RestoreNetworks: clear tenantID: %s all networks START", tenantId)
	nets, err := GetNetObjRepoSingleton().ListByTenantID(tenantId)
	if err != nil {
		klog.Errorf("RestoreNetworks: ListByTenantID[tenantID: %s} FAILED, error: %v", tenantId, err)
		return err
	}

	for _, net := range nets {
		err := restorePrivNetwork(tenantId, net.ID)
		if err != nil {
			klog.Errorf("RestoreNetworks: restorePrivNetwork: %s: %s FAILED, error: %v", tenantId, net.ID, err)
			return err
		}
	}
	klog.Infof("RestoreNetworks: clear tenantID: %s all networks SUCC", tenantId)
	return nil
}
View Source
var RestorePublic = func() error {
	err := clearPublic()
	if err != nil {
		klog.Errorf("RestorePublic: clearPublic FAILED, error: %v", err)
		return err
	}

	netIds, err := GetAdminPublicNetIds()
	if err != nil {
		klog.Errorf("RestorePublic: GetAdminPublicNetIds() FAILED, error: %v", err)
		return err
	}

	klog.Infof("RestorePublic: find all public networks[%v]", netIds)
	err = rebuildPublicNetworks(adminTenantID, netIds)
	if err != nil {
		klog.Errorf("RestorePublic: rebuild PublicNetworks[%v] FAILED, error: %v", netIds, err)
		return err
	}

	klog.Infof("RestorePublic: restore all public networks[%v] SUCC", netIds)
	return nil
}
View Source
var RestoreTenantResource = func(tid string) error {
	klog.Infof("RestoreTenantResource: tenantID: %s START", tid)
	klog.Infof("RestoreTenants: start to clearPods for tenantId: %s", tid)
	err := clearPods(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: clearPods(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}
	err = clearRouters(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: clearRouters(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}

	klog.Infof("RestoreTenants: start to RestoreNetworks for tenantId: %s", tid)
	err = RestoreNetworks(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: RestoreNetworks(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}

	klog.Infof("RestoreTenants: start to ClearIPGroups for tenantId: %s", tid)
	err = ClearIPGroups(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: ClearIPGroups(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}

	klog.Infof("RestoreTenants: start to ClearLogicalPorts for tenantId: %s", tid)
	err = ClearLogicalPorts(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: ClearLogicalPorts(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}

	err = ClearPhysicalPorts(tid)
	if err != nil {
		klog.Errorf("RestoreTenantResource: clearPhysicalPorts(tenantId: %s) FAILED, error: %v",
			tid, err)
		return err
	}

	klog.Infof("RestoreTenantResource: tenantID: %s SUCC", tid)
	return nil
}
View Source
var RestoreTenants = func() error {
	klog.Info("RestoreTenants: START")
	tenantIds, err := getAllTenantIds()
	if err != nil {
		klog.Errorf("RestoreTenants: getAllTenantIds FAILED, error: %v", err)
		return err
	}
	klog.Info("RestoreTenants: start to RestoreTenantResource")
	for _, tid := range tenantIds {
		err := RestoreTenantResource(tid)
		if err != nil {
			klog.Errorf("RestoreTenants: RestoreTenantResource(tenantId: %s) FAILED, error: %v",
				tid, err)
			return err
		}
		klog.Infof("RestoreTenants: end to RestoreTenantResource for tenantId: %s", tid)
	}
	klog.Info("RestoreTenants: SUCC")
	return nil
}
View Source
var RollBackEtcd = func(restoreJobStateMap map[string]*RestoreJobState) {
	for k, v := range restoreJobStateMap {
		if v.State == constvalue.RestoreProgressStatProcessSucc {
			key := dbaccessor.GetKeyOfRoot() + "/" + k
			err := common.GetDataBase().DeleteDir(key)
			if err != nil && !IsKeyNotFoundError(err) {
				klog.Errorf("RollBackEtcd: DeleteDir(key: %s)FAILED, error: %v", key, err)
			}
		}
	}

}
View Source
var RollBackInitConf = func(tenantID string) error {
	DelAdminTenantInfoFromDB()
	iaas.DelIaasTenantInfoFromDB(tenantID)
	DelOpenStackConfg()
	iaas.SetIaaS(tenantID, nil)
	return nil
}
View Source
var RollBackInitNets = func(netList []string) error {
	for _, id := range netList {
		net := iaasaccessor.Network{Id: id}
		nw := Net{Network: net}
		nw.TenantUUID = constvalue.PaaSTenantAdminDefaultUUID
		DeleteNetwork(id)
	}
	return nil
}
View Source
var SaveInitConf = func(value []byte) error {
	key := dbaccessor.GetKeyOfInitConf()
	err := common.GetDataBase().SaveLeaf(key, string(value))
	if err != nil {
		klog.Errorf("SaveInitConf Error: %v", err)
		return err
	}
	return nil
}
View Source
var SaveVnfmConfg = func(value []byte) error {
	key := dbaccessor.GetKeyOfVnfm()
	err1 := common.GetDataBase().SaveLeaf(key, string(value))
	if err1 != nil {
		klog.Error(err1)
		return err1
	}
	WaitForEtcdClusterSync(2)
	return nil
}
View Source
var Scene string = ""
View Source
var SendRestoreJob = func(etcdAdmToolRestoreUrl string, etcdRestoreJob RestoreReq) error {
	klog.Info("SendRestorePost START")
	body, err := json.Marshal(etcdRestoreJob)
	if err != nil {
		klog.Errorf("SendRestorePost: json.Marshal(createNetParam: %v) SUCC", err)
		return err
	}
	err = HTTPPost(etcdAdmToolRestoreUrl, body)
	if err != nil {
		klog.Errorf("SendRestorePost: HttpPost(url: %s, body: %v) SUCC", etcdAdmToolRestoreUrl, string(body))
		return err
	}
	klog.Info("SendRestorePost SUCC")

	return nil
}
View Source
var SendRestoreJobs = func(etcdAdmToolRestoreUrl string, etcdRestorejob RestoreReq, restoreJobStateMap map[string]*RestoreJobState) {
	klog.Infof("SendRestorePosts START")
	for k := range restoreJobStateMap {
		var postBody = etcdRestorejob
		postBody.DirectoryName = "/paasnet/" + k
		postBody.JobID = postBody.JobID + "_" + k
		klog.Infof("SendRestorePosts :etcdAdmToolRestoreUrl[%v],postBody[%v]", etcdAdmToolRestoreUrl, postBody)
		err := SendRestoreJob(etcdAdmToolRestoreUrl, postBody)
		if err != nil {
			restoreJobStateMap[k].State = constvalue.RestoreProgressStatProcessFail
			klog.Errorf("SendRestoreJobs: SendRestoreJob fail %v", err)
		}

	}
	klog.Infof("SendRestorePosts END")
}
View Source
var ShouldNotPodExist = func() error {
	klog.Infof("shouldNotPodExist: START")
	tenantIds, err := getAllTenantIds()
	if err != nil && !IsKeyNotFoundError(err) {
		klog.Errorf("ShouldPodNotExist: getAllTenantIds FAILED, error: %v", err)
		return err
	}
	for _, tid := range tenantIds {
		pod := &Pod{}
		pod.SetTenantID(tid)
		pods := PodListAll(pod)
		if len(pods) > 0 {
			return errobj.ErrTenantHasPodsInUse
		}
	}

	klog.Infof("shouldNotPodExist SUCC")
	return nil
}
View Source
var UnmarshalIPGroup = func(value []byte) (*IPGroupInDB, error) {
	var ig IPGroupInDB
	err := json.Unmarshal([]byte(value), &ig)
	if err != nil {
		klog.Errorf("UnmarshalIPGroup: json.Unmarshal(%s) FAILED, error: %v", string(value), err)
		return nil, errobj.ErrUnmarshalFailed
	}

	klog.Infof("UnmarshalIPGroup: ip group[%v] SUCC", ig)
	return &ig, nil
}
View Source
var UnmarshalLogicPort = func(value []byte) (*LogicalPort, error) {
	var port LogicalPort
	err := json.Unmarshal([]byte(value), &port)
	if err != nil {
		klog.Errorf("UnmarshalLogicPort: json.Unmarshal(%s) FAILED, error: %v", string(value), err)
		return nil, errobj.ErrUnmarshalFailed
	}

	klog.Infof("UnmarshalLogicPort: logical port[%+v] SUCC", port)
	return &port, nil
}
View Source
var UnmarshalNetwork = func(value []byte) (*Network, error) {
	var net Network
	err := json.Unmarshal([]byte(value), &net)
	if err != nil {
		klog.Errorf("UnmarshalNetwork: json.Unmarshal(%s) FAILED, error: %v", string(value), err)
		return nil, errobj.ErrUnmarshalFailed
	}

	klog.Infof("UnmarshalNetwork: net[%v] SUCC", net)
	return &net, nil
}
View Source
var UnmarshalPhysPort = func(value []byte) (*PhysicalPort, error) {
	var port PhysicalPort
	err := json.Unmarshal([]byte(value), &port)
	if err != nil {
		klog.Errorf("UnmarshalPhysPort: json.Unmarshal(%v) FAILED, error: %v", value, err)
		return nil, errobj.ErrUnmarshalFailed
	}

	klog.Infof("UnmarshalPhysPort: physical port[%v] SUCC", port)
	return &port, nil
}
View Source
var UnmarshalSubnet = func(value []byte) (*Subnet, error) {
	var subnet Subnet
	err := json.Unmarshal([]byte(value), &subnet)
	if err != nil {
		klog.Errorf("UnmarshalSubnet: json.Unmarshal(%s) FAILED, error: %v", string(value), err)
		return nil, errobj.ErrUnmarshalFailed
	}

	klog.Infof("UnmarshalSubnet: subnet[%v] SUCC", subnet)
	return &subnet, nil
}
View Source
var UpdateDefaultPhysnet = func(phy string) error {
	value := iaas.GetIaaS(constvalue.DefaultIaasTenantID)
	actValue, ok := value.(*noauth_openstack.NoauthOpenStack)
	if !ok {
		klog.Errorf("UpdateDefaultPhysnet Err: GetIaaS Err")
		return BuildErrWithCode(http.StatusUnauthorized, errors.New("getIaaS error"))
	}
	actValue.NeutronConf.ProviderConf.PhyscialNetwork = phy
	errChechk := CheckPhysnet(actValue)
	if errChechk != nil {
		klog.Errorf("UpdateDefaultPhysnet Err: CheckPhysnet[%v] Err[%v]", phy, errChechk)
		return BuildErrWithCode(http.StatusBadRequest, errors.New("check physnet failed"))
	}
	iaas.SetIaaS(constvalue.DefaultIaasTenantID, actValue)
	iaas.SaveDefaultPhysnet(actValue.NeutronConf.ProviderConf.PhyscialNetwork)
	return nil
}

Functions

func BuildErrWithCode

func BuildErrWithCode(code int, err error) error

func CancelResidualTenants

func CancelResidualTenants()

func ClearRuntime

func ClearRuntime() error

func ConvertAttachReqMax

func ConvertAttachReqMax(maxReqAttach string) int

func ConvertQuota

func ConvertQuota(quota string, defaultValue int) (int, bool)

func CreateAndAttach

func CreateAndAttach(body []byte, tenantID string) (*mgragt.CreatePortResp, error)

physical port ops

func CreateBulkPorts

func CreateBulkPorts(req *mgriaas.MgrBulkPortsReq) (*mgragt.CreatePortsResp, error)

func CreateLogicalPort

func CreateLogicalPort(reqObj *CreatePortReq) (*mgragt.CreatePortResp, error)

func CreateNetworkLan

func CreateNetworkLan(tenantID string) (string, error)

func DelAdminTenantInfoFromDB

func DelAdminTenantInfoFromDB() error

func DelNetwork

func DelNetwork(netID string) error

func DelSubnet

func DelSubnet(subnetID string) error

func DeleteLogicalPort

func DeleteLogicalPort(portID string) error

func DeletePhysicalPort

func DeletePhysicalPort(portID string) error

func DestroyLogicalPort

func DestroyLogicalPort(portID string) error

func DetachAndDelete

func DetachAndDelete(tranID TranID, vmID, portID, paasTenantID string) error

func GetAllNormalTenantIds

func GetAllNormalTenantIds() ([]string, error)

func GetDefaultNetworkName

func GetDefaultNetworkName() string

func GetDefaultProviderNetworkByInitConfig

func GetDefaultProviderNetworkByInitConfig(cfg *jason.Object) (string, error)

func HTTPPost

func HTTPPost(url string, bodyContent []byte) (err error)

func HandleOpenStackConfg

func HandleOpenStackConfg(conf *openstack.OpenStackConf) (*openstack.OpenStackConf, error)

func HandleRegularCheckConfg

func HandleRegularCheckConfg(timeInterval string) error

func IPGroupNetworkIDIndexFunc

func IPGroupNetworkIDIndexFunc(obj interface{}) ([]string, error)

func IPGroupObjKeyFunc

func IPGroupObjKeyFunc(obj interface{}) (string, error)

func IPGroupTenantIDIndexFunc

func IPGroupTenantIDIndexFunc(obj interface{}) ([]string, error)

func InSliceString

func InSliceString(v string, sl []string) bool

InSliceString checks given string in string slice.

func InitEnv4Manger

func InitEnv4Manger(confObj *jason.Object) error

func IsAdminTenant

func IsAdminTenant(tenantID string) bool

func IsKeyNotFoundError

func IsKeyNotFoundError(err error) bool

func IsNetworkExist

func IsNetworkExist(id string) bool

func IsNetworkInUse

func IsNetworkInUse(id string) bool

func IsNetworkUsedByIPGroup

func IsNetworkUsedByIPGroup(networkID, tenantID string) bool

func IsTenantExistInDB

func IsTenantExistInDB(tenantID string) bool

func ListAllUser

func ListAllUser() ([]string, error)

func LoadAllIPGroupObjects

func LoadAllIPGroupObjects() error

func LoadAllNetworkObjects

func LoadAllNetworkObjects() error

func LoadAllPortObjs

func LoadAllPortObjs() error

func LoadAllResourcesToCache

func LoadAllResourcesToCache()

func LoadAllSubnetObjects

func LoadAllSubnetObjects() error

func LoadPhysicalPortObjects

func LoadPhysicalPortObjects() error

func LoadResouceObjectsLoop

func LoadResouceObjectsLoop(lroFunc LoadResouceObjectFunc)

func NetworkIDIndexFunc

func NetworkIDIndexFunc(obj interface{}) ([]string, error)

func NetworkIsExternalIndexFunc

func NetworkIsExternalIndexFunc(obj interface{}) ([]string, error)

func NetworkIsPlublicIndexFunc

func NetworkIsPlublicIndexFunc(obj interface{}) ([]string, error)

func NetworkNameIndexFunc

func NetworkNameIndexFunc(obj interface{}) ([]string, error)

func NetworkObjKeyFunc

func NetworkObjKeyFunc(obj interface{}) (string, error)

func NetworkTenantIDIndexFunc

func NetworkTenantIDIndexFunc(obj interface{}) ([]string, error)

func PhysPortNetworkIDIndexFunc

func PhysPortNetworkIDIndexFunc(obj interface{}) ([]string, error)

func PhysPortObjKeyFunc

func PhysPortObjKeyFunc(obj interface{}) (string, error)

func PhysPortTenantIDIndexFunc

func PhysPortTenantIDIndexFunc(obj interface{}) ([]string, error)

func PortObjKeyFunc

func PortObjKeyFunc(obj interface{}) (string, error)

func RegisterNetwork

func RegisterNetwork(user, id, subid string, public bool) error

func RemoveIPFromSlice

func RemoveIPFromSlice(s *[]IPInDB, ipAddr string)

func SaveAdminTenantInfoToDB

func SaveAdminTenantInfoToDB(iaasID, iaasName string) error

func SaveExceptPort

func SaveExceptPort(portID, portType, hostID, exceptReason string) error

func SaveLogicalPort

func SaveLogicalPort(port *LogicalPort) error

func SaveNetwork

func SaveNetwork(net *Network) error

func SaveOpenStackConfg

func SaveOpenStackConfg(value []byte) error

func SavePhysicalPort

func SavePhysicalPort(port *PhysicalPort) error

func SaveSubnet

func SaveSubnet(subnet *Subnet) error

func SetNetQuota

func SetNetQuota(cfg *jason.Object)

func StringSliceDiff

func StringSliceDiff(slice1, slice2 []string) (diffslice []string)

SliceDiff returns diff slice of slice1 - slice2.

func StringSliceUnique

func StringSliceUnique(slice []string) (uniqueslice []string)

SliceUnique cleans repeated values in slice.

func SubnetNetworkIDIndexFunc

func SubnetNetworkIDIndexFunc(obj interface{}) ([]string, error)

func SubnetObjKeyFunc

func SubnetObjKeyFunc(obj interface{}) (string, error)

func TenantIDIndexFunc

func TenantIDIndexFunc(obj interface{}) ([]string, error)

func TransNetToNetwork

func TransNetToNetwork(net *Net) (*Network, *Subnet)

func UpdateEtcd4NetQuota

func UpdateEtcd4NetQuota() error

func WaitForEtcdClusterSync

func WaitForEtcdClusterSync(second int)

Types

type AllocationPool

type AllocationPool struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

type CreatePortReq

type CreatePortReq struct {
	agtmgr.AgtPortReq
}

interface between knitter_master and knitter type define start

type CreateProviderNetwork

type CreateProviderNetwork struct {
	Name            string                   `json:"name"`
	ID              string                   `json:"network_id"`
	GateWay         string                   `json:"gateway"`
	Cidr            string                   `json:"cidr"`
	NetworkType     string                   `json:"provider:network_type"`
	PhysicalNetwork string                   `json:"provider:physical_network"`
	SegmentationID  string                   `json:"provider:segmentation_id"`
	VlanTransparent bool                     `json:"vlan_transparent"`
	AllocationPools []subnets.AllocationPool `json:"allocation_pools"`
}

type EncapCreateProviderNetwork

type EncapCreateProviderNetwork struct {
	Network *CreateProviderNetwork `json:"provider_network"`
}

type EncapNetworkExten

type EncapNetworkExten struct {
	Network *iaasaccessor.NetworkExtenAttrs `json:"network_exten"`
}

type EncapNoauthOpenStackConf

type EncapNoauthOpenStackConf struct {
	NoauthOpenStack noauth_openstack.NoauthOpenStackConf `json:"noauth_openstack"`
}

type EncapOpenStack

type EncapOpenStack struct {
	Config *openstack.OpenStackConf `json:"openstack"`
}

type EncapPaasNetwork

type EncapPaasNetwork struct {
	Network *PaasNetwork `json:"network"`
}

type EncapPaasNetworks

type EncapPaasNetworks struct {
	Networks []*PaasNetwork `json:"networks"`
}

type EncapPod

type EncapPod struct {
	Pod *Pod `json:"pod"`
}

type EncapPodForResponse

type EncapPodForResponse struct {
	Pod *PodForResponse `json:"pod"`
}

type EncapPods

type EncapPods struct {
	Pods []*Pod `json:"pods"`
}

type EncapPodsForResponse

type EncapPodsForResponse struct {
	Pods []*PodForResponse `json:"pods"`
}

type EncapRouter

type EncapRouter struct {
	Router *iaasaccessor.Router `json:"router"`
}

type EncapRouters

type EncapRouters struct {
	Routers []*iaasaccessor.Router `json:"routers"`
}

type ExceptPort

type ExceptPort struct {
	ID string `json:"id"`

	PortType string `json:"port_type"`
	HostID   string `json:"host_id"`

	ExceptTime   string `json:"except_time"`
	ExceptReason string `json:"except_reason"`
	ExceptStat   string `json:"except_stat"`

	ExpectProcOps []string `json:"expect_proc_ops"`
}

type ExclusiveTenant

type ExclusiveTenant struct {
	PaasName       string `json:"paas_name"`
	PassID         string `json:"pass_id"`
	IaasEndpoint   string `json:"iaas_endpoint"`
	IaasTenantName string `json:"iaas_tenant_name"`
	IaasUserName   string `json:"iaas_user_name"`
	IaasPaasword   string `json:"iaas_paasword"`
	IaasTenantID   string `json:"iaas_tenant_id"`
	Networks       string `json:"networks"`
	Interfaces     string `json:"interfaces"`
	Quota          int    `json:"net_quota"`
	NetNum         int    `json:"net_number"`
	IsCancelling   bool   `json:"is_cancelling"`
	CreateTime     string `json:"create_time"`
}

func (*ExclusiveTenant) Create

func (self *ExclusiveTenant) Create() error

func (*ExclusiveTenant) SaveIaasAndPaasInfoToDB

func (self *ExclusiveTenant) SaveIaasAndPaasInfoToDB() error

type ExtenAttrs

type ExtenAttrs struct {
	// Specifies the nature of the physical network mapped to this network
	// resource. Examples are flat, vlan, vxlan, or gre.
	NetworkType string `json:"provider:network_type"`

	// Identifies the physical network on top of which this network object is
	// being implemented. The OpenStack Networking API does not expose any facility
	// for retrieving the list of available physical networks. As an example, in
	// the Open vSwitch plug-in this is a symbolic name which is then mapped to
	// specific bridges on each compute host through the Open vSwitch plug-in
	// configuration file.
	PhysicalNetwork string `json:"provider:physical_network"`

	// Identifies an isolated segment on the physical network; the nature of the
	// segment depends on the segmentation model defined by network_type. For
	// instance, if network_type is vlan, then this is a vlan identifier;
	// otherwise, if network_type is gre, then this will be a gre key.
	SegmentationID string `json:"provider:segmentation_id"`

	VlanTransparent bool `json:"vlan_transparent"`
}

type HealthObj

type HealthObj struct {
	Level int64  `json:"health_level"`
	State string `json:"state"`
}

func (*HealthObj) GetHealthLevel

func (self *HealthObj) GetHealthLevel() int64

func (*HealthObj) GetHealthState

func (self *HealthObj) GetHealthState() string

type IPGroup

type IPGroup struct {
	TenantID    string
	NetworkID   string
	SubnetID    string
	SubnetCidr  string
	SubnetPools []AllocationPool
	Name        string
	ID          string
	IPs         string
	IPsSlice    []string
	AddIPs      []string
	DelIPs      map[string]string
	SizeStr     string
	Size        int
	AddSize     int
	Mode        IPMode
}

func (*IPGroup) AnalyzeIPs

func (self *IPGroup) AnalyzeIPs(igInDb *IPGroupInDB) error

func (*IPGroup) CheckNet

func (self *IPGroup) CheckNet() error

func (*IPGroup) Create

func (self *IPGroup) Create() (*IPGroupObject, error)

func (*IPGroup) Delete

func (self *IPGroup) Delete() error

func (*IPGroup) Get

func (self *IPGroup) Get() (*IPGroupObject, error)

func (*IPGroup) GetIGWithCheck

func (self *IPGroup) GetIGWithCheck() (*IPGroupInDB, error)

func (*IPGroup) GetIGs

func (self *IPGroup) GetIGs() ([]*IPGroupObject, error)

func (*IPGroup) GetIGsByNet

func (self *IPGroup) GetIGsByNet() ([]*IPGroupObject, error)

func (*IPGroup) GetIPGroupByName

func (self *IPGroup) GetIPGroupByName() (*IPGroupObject, error)

func (*IPGroup) IsDuplicateName

func (self *IPGroup) IsDuplicateName(igInDb *IPGroupInDB) bool

func (*IPGroup) IsValidIPs

func (self *IPGroup) IsValidIPs() bool

func (*IPGroup) ObtainIP

func (self *IPGroup) ObtainIP() (*iaasaccessor.Interface, error)

func (*IPGroup) Operate

func (self *IPGroup) Operate(igInDb *IPGroupInDB) error

func (*IPGroup) ReleaseIP

func (self *IPGroup) ReleaseIP(portID string) error

func (*IPGroup) Update

func (self *IPGroup) Update() (*IPGroupObject, error)

type IPGroupInDB

type IPGroupInDB struct {
	ID        string   `json:"id"`
	TenantID  string   `json:"tenant_id"`
	Name      string   `json:"name"`
	NetworkID string   `json:"network_id"`
	IPs       []IPInDB `json:"ips"`
}

func GetAllIPGroups

func GetAllIPGroups() ([]*IPGroupInDB, error)

func TransIGObjectToIGInDB

func TransIGObjectToIGInDB(igObject *IPGroupObject) *IPGroupInDB

type IPGroupObject

type IPGroupObject struct {
	ID        string
	Name      string
	NetworkID string
	IPs       []IPInDB
	TenantID  string
}

func TransIGInDBToIGObject

func TransIGInDBToIGObject(igInDB *IPGroupInDB) *IPGroupObject

type IPGroupObjectRepo

type IPGroupObjectRepo struct {
	// contains filtered or unexported fields
}

func GetIPGroupObjRepoSingleton

func GetIPGroupObjRepoSingleton() *IPGroupObjectRepo

func (*IPGroupObjectRepo) Add

func (p *IPGroupObjectRepo) Add(igObj *IPGroupObject) error

func (*IPGroupObjectRepo) Del

func (p *IPGroupObjectRepo) Del(ID string) error

func (*IPGroupObjectRepo) Get

func (*IPGroupObjectRepo) Init

func (p *IPGroupObjectRepo) Init()

func (*IPGroupObjectRepo) List

func (p *IPGroupObjectRepo) List() []*IPGroupObject

func (*IPGroupObjectRepo) ListByNetworkID

func (p *IPGroupObjectRepo) ListByNetworkID(networkName string) ([]*IPGroupObject, error)

func (*IPGroupObjectRepo) ListByTenantID

func (p *IPGroupObjectRepo) ListByTenantID(tenantID string) ([]*IPGroupObject, error)

func (*IPGroupObjectRepo) Update

func (p *IPGroupObjectRepo) Update(igObj *IPGroupObject) error

type IPInDB

type IPInDB struct {
	IPAddr  string `json:"ip_addr"`
	Used    bool   `json:"used"`
	PortID  string `json:"port_id"`
	MacAddr string `json:"mac_addr"`
}

type IPMode

type IPMode int

type InitCNetwork

type InitCNetwork struct {
	Name            string                   `json:"name"`
	Cidr            string                   `json:"cidr"`
	Desc            string                   `json:"desc"`
	Public          bool                     `json:"public"`
	Gw              string                   `json:"gw"`
	AllocationPool  []subnets.AllocationPool `json:"allocation_pool"`
	NetworksType    string                   `json:"provider:network_type"`
	PhysicalNetwork string                   `json:"provider:physical_network"`
	SegmentationID  string                   `json:"provider:segmentation_id"`
}

type InitCfg

type InitCfg struct {
	Configuration InitConfiguration `json:"configuration"`
	Networks      InitNetworks      `json:"networks"`
}

type InitConfiguration

type InitConfiguration struct {
	EndPoint   string `json:"endpoint"`
	User       string `json:"user"`
	Password   string `json:"password"`
	TenantName string `json:"tenant_name"`
	TenantID   string `json:"tenant_id"`
}

type InitNetworks

type InitNetworks struct {
	InitRegNetworks    []*InitRNetwork `json:"registered_networks"`
	InitCreateNetworks []*InitCNetwork `json:"created_networks"`
}

type InitRNetwork

type InitRNetwork struct {
	Name   string `json:"name"`
	UUID   string `json:"uuid"`
	Desc   string `json:"desc"`
	Public bool   `json:"public"`
}

type Intf

type Intf struct {
	Interface  iaasaccessor.Interface
	TenantUUID string
	DcID       string
}

type LoadResouceObjectFunc

type LoadResouceObjectFunc func() error

type LogicPod

type LogicPod struct {
	PodName  string     `json:"pod_name"`
	PodNs    string     `json:"pod_ns"`
	TenantID string     `json:"tenant_id"`
	Ports    []PortInfo `json:"ports"`
}

func (*LogicPod) Delete

func (self *LogicPod) Delete() error

func (*LogicPod) Get

func (self *LogicPod) Get() error

func (*LogicPod) GetEncapPodForResponse

func (self *LogicPod) GetEncapPodForResponse() (*EncapPodForResponse, error)

func (*LogicPod) Save

func (self *LogicPod) Save() error

func (*LogicPod) TransformToPodForResponse

func (self *LogicPod) TransformToPodForResponse() *PodForResponse

type LogicPodManager

type LogicPodManager struct {
}

func (*LogicPodManager) GetAll

func (self *LogicPodManager) GetAll(tenantID string) ([]*LogicPod, error)

func (*LogicPodManager) GetEncapPodsForResponse

func (self *LogicPodManager) GetEncapPodsForResponse(tenantID string) (*EncapPodsForResponse, error)

type LogicalPort

type LogicalPort struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status int    `json:"status"` // life cycle status, not IaaS layer status

	IP         string `json:"ip"`
	MACAddress string `json:"mac_address"`

	NetworkID string `json:"network_id"`
	SubnetID  string `json:"subnet_id"`
	IPGroupID string `json:"ipgroup_id"`

	NodeID    string `json:"node_id"`
	ClusterID string `json:"cluster_id"`

	OwnerType string `json:"owner_type"` // node or pod(ms), agent...
	TenantID  string `json:"tenant_id"`
	PodName   string `json:"pod_name"`
	PodNs     string `json:"pod_ns"`
}

logical port lifecycle management structure, should only contains least members

func GetAllLogicalPorts

func GetAllLogicalPorts() ([]*LogicalPort, error)

func GetLogicalPort

func GetLogicalPort(portID string) (*LogicalPort, error)

func MakeLogicalPort

func MakeLogicalPort(portObj *PortObj) *LogicalPort

func TransCreatePortToLogicalPort

func TransCreatePortToLogicalPort(port *iaasaccessor.Interface, req *CreatePortReq) *LogicalPort

func TransCreatePortsToLogicalPorts

func TransCreatePortsToLogicalPorts(ports []*iaasaccessor.Interface, req *CreatePortReq) []*LogicalPort

type Net

type Net struct {
	Network         iaasaccessor.Network
	Subnet          iaasaccessor.Subnet
	VlanTransparent bool
	Provider        iaasaccessor.NetworkExtenAttrs
	TenantUUID      string
	Public          bool
	ExternalNet     bool
	CreateTime      string `json:"create_time"`
	Status          string `json:"state"`
	Description     string `json:"description"`
}

func (*Net) CheckQuota

func (self *Net) CheckQuota() error

func (*Net) Create

func (self *Net) Create() error

func (*Net) GetByID

func (self *Net) GetByID() (*iaasaccessor.Network, error)

func (*Net) GetExtenByID

func (self *Net) GetExtenByID() (*iaasaccessor.NetworkExtenAttrs, error)

func (*Net) GetSubnetByID

func (self *Net) GetSubnetByID(id string) (*iaasaccessor.Subnet, error)

func (Net) SaveQuota

func (self Net) SaveQuota() error

type Network

type Network struct {
	Name string `json:"name"`
	ID   string `json:"id"`

	//SubnetIDs []string
	SubnetID string

	ExtAttrs ExtenAttrs

	TenantID    string `json:"tenant_id"`
	IsPublic    bool   `json:"is_public"`
	IsExternal  bool   `json:"is_external"`
	CreateTime  string `json:"create_time"`
	Description string `json:"description"`
}

func GetAllNetworks

func GetAllNetworks() ([]*Network, error)

func GetNetwork2

func GetNetwork2(netID string) (*Network, error)

type NetworkObject

type NetworkObject struct {
	Name   string `json:"name"`
	ID     string `json:"id"`
	Status string `json:"state"`

	//SubnetIDs []string
	SubnetID string
	ExtAttrs ExtenAttrs

	TenantID    string `json:"tenant_id"`
	IsPublic    bool   `json:"is_public"`
	IsExternal  bool   `json:"is_external"`
	CreateTime  string `json:"create_time"`
	Description string `json:"description"`
}

func TransNetworkToNetworkObject

func TransNetworkToNetworkObject(net *Network) *NetworkObject

type NetworkObjectRepo

type NetworkObjectRepo struct {
	// contains filtered or unexported fields
}

func GetNetObjRepoSingleton

func GetNetObjRepoSingleton() *NetworkObjectRepo

func (*NetworkObjectRepo) Add

func (p *NetworkObjectRepo) Add(netObj *NetworkObject) error

func (*NetworkObjectRepo) Del

func (p *NetworkObjectRepo) Del(ID string) error

func (*NetworkObjectRepo) Get

func (*NetworkObjectRepo) Init

func (p *NetworkObjectRepo) Init()

func (*NetworkObjectRepo) List

func (p *NetworkObjectRepo) List() []*NetworkObject

func (*NetworkObjectRepo) ListByIsExternal

func (p *NetworkObjectRepo) ListByIsExternal(isExternal string) ([]*NetworkObject, error)

func (*NetworkObjectRepo) ListByIsPublic

func (p *NetworkObjectRepo) ListByIsPublic(isPublic string) ([]*NetworkObject, error)

func (*NetworkObjectRepo) ListByNetworkName

func (p *NetworkObjectRepo) ListByNetworkName(networkName string) ([]*NetworkObject, error)

func (*NetworkObjectRepo) ListByTenantID

func (p *NetworkObjectRepo) ListByTenantID(tenantID string) ([]*NetworkObject, error)

func (*NetworkObjectRepo) Update

func (p *NetworkObjectRepo) Update(netObj *NetworkObject) error

type PaasNetwork

type PaasNetwork struct {
	Name            string                         `json:"name"`
	ID              string                         `json:"network_id"`
	GateWay         string                         `json:"gateway"`
	Cidr            string                         `json:"cidr"`
	CreateTime      string                         `json:"create_time"`
	Status          string                         `json:"state"`
	Public          bool                           `json:"public"`
	ExternalNet     bool                           `json:"external"`
	Owner           string                         `json:"owner"`
	Description     string                         `json:"description"`
	SubnetID        string                         `json:"subnet_id"`
	Provider        iaasaccessor.NetworkExtenAttrs `json:"provider"`
	AllocationPools []subnets.AllocationPool       `json:"allocation_pools"`
}

func GetAllPublicNetworks

func GetAllPublicNetworks() ([]*PaasNetwork, error)

func GetNetworkByName

func GetNetworkByName(tenantID, netName string) (*PaasNetwork, error)

func GetNetworkInfo

func GetNetworkInfo(user, networkName string, needProvider bool) (*PaasNetwork, error)

todo

func GetTenantAllNetworks

func GetTenantAllNetworks(tenantID string) ([]*PaasNetwork, error)

func GetTenantOwnedNetworks

func GetTenantOwnedNetworks(tenantID string) ([]*PaasNetwork, error)

type PaasQuotas

type PaasQuotas struct {
	Network int `json:"network"`
}

type PaasTenant

type PaasTenant struct {
	TenantName string     `json:"name"`
	TenantUUID string     `json:"id"`
	NetNum     int        `json:"net_number"`
	CreateTime string     `json:"created_at"`
	Quotas     PaasQuotas `json:"quotas"`
	Status     string     `json:"status"`
}

type PhysPortObj

type PhysPortObj struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status"`

	// layer 2-3 info
	VnicType   string `json:"vnic_type"`
	IP         string `json:"ip"`
	MacAddress string `json:"mac_address"`
	NetworkID  string `json:"network_id"`
	SubnetID   string `json:"subnet_id"`

	// owner info
	NodeID    string `json:"node_id"`
	ClusterID string `json:"cluster_id"`
	OwnerType string `json:"owner_type"`
	TenantID  string `json:"tenant_id"`
}

physical port table start

func TransPhysicalPortToPhysPortObj

func TransPhysicalPortToPhysPortObj(physPort *PhysicalPort) *PhysPortObj

type PhysPortObjRepo

type PhysPortObjRepo struct {
	Lock sync.RWMutex
	// contains filtered or unexported fields
}

func GetPhysPortObjRepoSingleton

func GetPhysPortObjRepoSingleton() *PhysPortObjRepo

func (*PhysPortObjRepo) Add

func (p *PhysPortObjRepo) Add(port *PhysPortObj) error

func (*PhysPortObjRepo) Del

func (p *PhysPortObjRepo) Del(portID string) error

func (*PhysPortObjRepo) Get

func (p *PhysPortObjRepo) Get(portID string) (*PhysPortObj, error)

func (*PhysPortObjRepo) Init

func (p *PhysPortObjRepo) Init()

func (*PhysPortObjRepo) ListByNetworkID

func (p *PhysPortObjRepo) ListByNetworkID(networkID string) ([]*PhysPortObj, error)

func (*PhysPortObjRepo) ListByTenantID

func (p *PhysPortObjRepo) ListByTenantID(tenantID string) ([]*PhysPortObj, error)

func (*PhysPortObjRepo) Update

func (p *PhysPortObjRepo) Update(port *PhysPortObj) error

type PhysicalPort

type PhysicalPort struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status"`

	// layer 2-3 info
	VnicType   string `json:"vnic_type"`
	IP         string `json:"ip"`
	MacAddress string `json:"mac_address"`
	NetworkID  string `json:"network_id"`
	SubnetID   string `json:"subnet_id"`

	// owner info
	NodeID    string `json:"node_id"`
	ClusterID string `json:"cluster_id"`
	OwnerType string `json:"owner_type"`
	TenantID  string `json:"tenant_id"`
}

physical port object persistence functions

func GetAllPhysicalPorts

func GetAllPhysicalPorts() ([]*PhysicalPort, error)

func GetPhysicalPort

func GetPhysicalPort(portID string) (*PhysicalPort, error)

func MakePhysicalPort

func MakePhysicalPort(portObj *PortObj, vnicType string) *PhysicalPort

type Physnet

type Physnet struct {
	DefaultPhysnet string `json:"default_physnet"`
}

type Pod

type Pod struct {
	Name   string   `json:"name"`
	PodIps []*PodIP `json:"ips"`
	// contains filtered or unexported fields
}

func (*Pod) GetFromEtcd

func (self *Pod) GetFromEtcd(ns, name string) (*Pod, error)

func (*Pod) ListAll

func (self *Pod) ListAll() []*Pod

func (*Pod) SetTenantID

func (self *Pod) SetTenantID(id string) error

type PodForResponse

type PodForResponse struct {
	Name   string             `json:"name"`
	PodIps []*PortForResponse `json:"ips"`
	// contains filtered or unexported fields
}

struct for restful

type PodIP

type PodIP struct {
	NetworkPlane      string `json:"network_plane"`
	NewtworkPlaneName string `json:"network_plane_name"`
	IPAddress         string `json:"ip_address"`
}

type PortArray

type PortArray struct {
	Lock sync.RWMutex
	// contains filtered or unexported fields
}

type PortForResponse

type PortForResponse struct {
	NetworkPlane      string `json:"network_plane"`
	NewtworkPlaneName string `json:"network_plane_name"`
	IPAddress         string `json:"ip_address"`
}

type PortInfo

type PortInfo struct {
	PortID       string `json:"port_id"`
	NetworkName  string `json:"network_name"`
	NetworkPlane string `json:"network_plane"`
	FixIP        string `json:"fix_ip"`
}

type PortObj

type PortObj struct {
	// key definition info
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status int    `json:"status"` // life cycle status, not IaaS layer status

	// layer 2-3 info
	IP         string `json:"ip"`
	MACAddress string `json:"mac_address"`

	NetworkID string `json:"network_id"`
	SubnetID  string `json:"subnet_id"`
	IPGroupID string `json:"ipgroup_id"`

	// owner info
	NodeID    string `json:"node_id"`
	ClusterID string `json:"cluster_id"`
	OwnerType string `json:"owner_type"` // node or pod(ms), agent...
	TenantID  string `json:"tenant_id"`
	PodName   string `json:"pod_name"`
	PodNs     string `json:"pod_ns"`
}

port table start

func MakePortObj

func MakePortObj(port *iaasaccessor.Interface, req *CreatePortReq) *PortObj

func TransLogicalPortToPortObj

func TransLogicalPortToPortObj(port *LogicalPort) *PortObj

type PortObjRepo

type PortObjRepo struct {
	Lock sync.RWMutex
	// contains filtered or unexported fields
}

func GetPortObjRepoSingleton

func GetPortObjRepoSingleton() *PortObjRepo

func (*PortObjRepo) Add

func (p *PortObjRepo) Add(portObj *PortObj) error

func (*PortObjRepo) Del

func (p *PortObjRepo) Del(portID string) error

func (*PortObjRepo) Get

func (p *PortObjRepo) Get(portID string) (*PortObj, error)

func (*PortObjRepo) Init

func (p *PortObjRepo) Init()

func (*PortObjRepo) ListByNetworkID

func (p *PortObjRepo) ListByNetworkID(networkID string) ([]*PortObj, error)

func (*PortObjRepo) ListByTenantID

func (p *PortObjRepo) ListByTenantID(tenantID string) ([]*PortObj, error)

func (*PortObjRepo) Update

func (p *PortObjRepo) Update(portObj *PortObj) error

type PortOps

type PortOps struct{}

func (*PortOps) AttachPortToVM

func (self *PortOps) AttachPortToVM(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *PortVMOpsReq) (*iaasaccessor.Interface, error)

func (*PortOps) CheckNicStatus

func (self *PortOps) CheckNicStatus(tranID TranID, status string, checkNum, intval int, iaasObj iaasaccessor.IaaS, portID string) error

func (*PortOps) CreateBulkPorts

func (self *PortOps) CreateBulkPorts(mgrBulkPortsReq *mgriaas.MgrBulkPortsReq) ([]*iaasaccessor.Interface, error)

func (*PortOps) CreatePort

func (self *PortOps) CreatePort(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *CreatePortReq) (*iaasaccessor.Interface, error)

func (*PortOps) DeletePort

func (self *PortOps) DeletePort(iaasObj iaasaccessor.IaaS, tranID TranID, portID string) error

func (*PortOps) DetachPortFromVM

func (self *PortOps) DetachPortFromVM(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *PortVMOpsReq) error

type PortOpsAPI

type PortOpsAPI interface {
	CreatePort(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *CreatePortReq) (*iaasaccessor.Interface, error)
	CreateBulkPorts(mgrBulkPortsReq *mgriaas.MgrBulkPortsReq) ([]*iaasaccessor.Interface, error)
	DeletePort(iaasObj iaasaccessor.IaaS, tranID TranID, portID string) error

	AttachPortToVM(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *PortVMOpsReq) (*iaasaccessor.Interface, error)
	DetachPortFromVM(tranID TranID, iaasObj iaasaccessor.IaaS, reqObj *PortVMOpsReq) error

	CheckNicStatus(tranID TranID, status string, checkNum, intval int, iaasObj iaasaccessor.IaaS, portID string) error
}

port operations abstract

type PortService

type PortService struct{}

func (*PortService) AttachPortToVM

func (self *PortService) AttachPortToVM(tranID TranID, tenantID string, reqObj *PortVMOpsReq) error

func (*PortService) CreateBulkPorts

func (self *PortService) CreateBulkPorts(mgrBulkPortsReq *mgriaas.MgrBulkPortsReq) ([]*iaasaccessor.Interface, error)

func (*PortService) CreatePort

func (self *PortService) CreatePort(tranID TranID, reqObj *CreatePortReq) (*PortObj, *mgragt.CreatePortResp, error)

create port entry function

func (*PortService) DeletePort

func (self *PortService) DeletePort(tranID TranID, portID, tenantID string) error

func (*PortService) DetachPortFromVM

func (self *PortService) DetachPortFromVM(tranID TranID, tenantID string, reqObj *PortVMOpsReq) error

type PortServiceAPI

type PortServiceAPI interface {
	CreatePort(tranID TranID, reqObj *CreatePortReq) (*PortObj, *mgragt.CreatePortResp, error)
	CreateBulkPorts(mgrBulkPortsReq *mgriaas.MgrBulkPortsReq) ([]*iaasaccessor.Interface, error)
	DeletePort(tranID TranID, portID, tenantID string) error

	AttachPortToVM(tranID TranID, tenantID string, reqObj *PortVMOpsReq) error
	DetachPortFromVM(tranID TranID, tenantID string, reqObj *PortVMOpsReq) error
}
var PortServiceObj PortServiceAPI = &PortService{}

type PortVMOpsReq

type PortVMOpsReq struct {
	VMID   string
	PortID string
}

type RestoreJobState

type RestoreJobState struct {
	JobDn string
	State int
}

type RestoreReq

type RestoreReq struct {
	JobID         string       `json:"jobDn"` // backup request ID
	Type          int          `json:"type"`  // 1: fullsize backup, 2: minisize backup
	StorConf      StorDestConf `json:"storage"`
	DirectoryName string       `json:"directoryName"`
}

type Rt

type Rt struct {
	Router     *iaasaccessor.Router
	TenantUUID string
}

func (*Rt) Attach

func (self *Rt) Attach(netID string) error

func (*Rt) Create

func (self *Rt) Create(router iaasaccessor.Router) error

func (*Rt) DelByID

func (self *Rt) DelByID() error

func (*Rt) Detach

func (self *Rt) Detach(netID string) error

func (*Rt) GetFromEtcd

func (self *Rt) GetFromEtcd() (*iaasaccessor.Router, error)

func (*Rt) ListAll

func (self *Rt) ListAll() []*iaasaccessor.Router

func (*Rt) Update

func (self *Rt) Update(router iaasaccessor.Router) error

type StorDestConf

type StorDestConf struct {
	StorType string `json:"storageType"`
	IP       string `json:"ip"`
	Port     int    `json:"port"`
	UserNm   string `json:"user"`
	Passwd   string `json:"password"`
	Path     string `json:"path"`
}

type Subnet

type Subnet struct {
	ID         string           `json:"id"`
	NetworkID  string           `json:"network_id"`
	Name       string           `json:"name"`
	CIDR       string           `json:"cidr"`
	GatewayIP  string           `json:"gateway_ip"`
	TenantID   string           `json:"tenant_id"`
	AllocPools []AllocationPool `json:"allocation_pools"`
}

func GetAllSubnets

func GetAllSubnets() ([]*Subnet, error)

func GetSubnet

func GetSubnet(subnetID string) (*Subnet, error)

type SubnetObject

type SubnetObject struct {
	ID         string           `json:"id"`
	NetworkID  string           `json:"network_id"`
	Name       string           `json:"name"`
	CIDR       string           `json:"cidr"`
	GatewayIP  string           `json:"gateway_ip"`
	TenantID   string           `json:"tenant_id"`
	AllocPools []AllocationPool `json:"allocation_pools"`
}

func TransSubnetToSubnetObject

func TransSubnetToSubnetObject(subnet *Subnet) *SubnetObject

type SubnetObjectRepo

type SubnetObjectRepo struct {
	// contains filtered or unexported fields
}

func GetSubnetObjRepoSingleton

func GetSubnetObjRepoSingleton() *SubnetObjectRepo

func (*SubnetObjectRepo) Add

func (p *SubnetObjectRepo) Add(subnetObj *SubnetObject) error

func (*SubnetObjectRepo) Del

func (p *SubnetObjectRepo) Del(ID string) error

func (*SubnetObjectRepo) Get

func (p *SubnetObjectRepo) Get(ID string) (*SubnetObject, error)

func (*SubnetObjectRepo) Init

func (p *SubnetObjectRepo) Init()

func (*SubnetObjectRepo) ListByNetworID

func (p *SubnetObjectRepo) ListByNetworID(networkID string) ([]*SubnetObject, error)

func (*SubnetObjectRepo) Update

func (p *SubnetObjectRepo) Update(subnetObj *SubnetObject) error

type SyncMgt

type SyncMgt struct {
	Active bool
	Data   dbaccessor.Sync
	// contains filtered or unexported fields
}

func GetSyncMgt

func GetSyncMgt() *SyncMgt

func (*SyncMgt) FlushTTL

func (self *SyncMgt) FlushTTL(reqIP string) error

func (*SyncMgt) SetInterval

func (self *SyncMgt) SetInterval(interval string) error

func (*SyncMgt) Sync

func (self *SyncMgt) Sync(reqIP string) *dbaccessor.SyncRsp

type Tenant

type Tenant struct {
	TenantName     string `json:"tenant_name"`
	TenantUUID     string `json:"tenant_uuid"`
	Networks       string `json:"networks"`
	Interfaces     string `json:"interfaces"`
	Quota          int    `json:"net_quota"`
	NetNum         int    `json:"net_number"`
	IsCancelling   bool   `json:"is_cancelling"`
	CreateTime     string `json:"create_time"`
	IaasTenantID   string `json:"iaas_tenant_id"`
	IaasTenantName string `json:"iaas_tenant_name"`
}

func GetAllTenants

func GetAllTenants() []*Tenant

func GetPaasTenantInfoFromDB

func GetPaasTenantInfoFromDB(tenentID string) (*Tenant, error)

func (*Tenant) Cancel

func (self *Tenant) Cancel() error

func (*Tenant) GetTenantInfo

func (self *Tenant) GetTenantInfo() (*Tenant, error)

func (*Tenant) SaveTenantToEtcd

func (self *Tenant) SaveTenantToEtcd() error

func (*Tenant) UpdateQuota

func (self *Tenant) UpdateQuota(quota int) error

type TranID

type TranID string

type VnpmConf

type VnpmConf struct {
	URL string `json:"url"`
}

type VxLanNetWork

type VxLanNetWork struct {
	NetworkType string `json:"network_type"`
	NetworkID   string `json:"network_id"`
	Vni         string `json:"vni"`
}

func GetNetworkVni

func GetNetworkVni(paasTenantID, networkID string) (*VxLanNetWork, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL