Ejemplo n.º 1
0
 def __init__(self, os_tenant_name, os_project_name, os_username,
              os_password):
     self._authTool = AuthTool()
     self._os_tenant_name = os_tenant_name
     self._os_project_name = os_project_name
     self._os_username = os_username
     self._os_password = os_password
class OpenstackClient:
    def __init__(self,os_tenant_name,os_project_name,os_username,os_password):
        self._authTool=AuthTool()
        self._os_tenant_name=os_tenant_name
        self._os_project_name=os_project_name
        self._os_username=os_username
        self._os_password=os_password

    def _openstackInsertAuth(self,command):
        return self._authTool.openstackInsertAuth(command,self._os_project_name,self._os_username,self._os_password)

    def getSecGroupId(self,secGroup_name):
        """
        得到安全组的id
        :param secGroup_name:
        :return:secGroup_id
        """
        command="openstack security group list |grep -i "+secGroup_name+"|awk -F '|' '{print $2}'"
        command=self._openstackInsertAuth(command)
        secGroup_id=subprocess.check_output(command,shell=True)
        secGroup_id=secGroup_id.strip()
        if not secGroup_id:
            return None
        return secGroup_id

    def addAllowTcpRule(self,secGroupId):
        """
        放开tcp 1-65535
        :param secGroupId:
        :return:
        """
        #检测是否有已开放tcp的1-65535端口
        check_command="openstack security group show "+secGroupId+"|grep -i \"direction='ingress'\"|grep -i \"port_range_max='65535', port_range_min='1', protocol='tcp', remote_ip_prefix='0.0.0.0/0'\"|awk {'print $0'}"
        check_command=self._openstackInsertAuth(check_command)
        has_tcp_65535=subprocess.check_output(check_command,shell=True)
        if has_tcp_65535:
            return True
        #放开安全组的tcp的1-65535端口
        command="openstack security group rule create --protocol tcp --ingress --remote-ip 0.0.0.0/0 --dst-port 1:65535 "+secGroupId
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def addAllowIcmpRule(self,secGroupId):
        """
        放开icmp
        :param secGroupId:
        :return:
        """
        #检测是否有已开放icmp端口
        check_command="openstack security group show "+secGroupId+"|grep -i \"direction='ingress'\"|grep -i \"protocol='icmp'\"|awk {'print $0'}"
        check_command=self._openstackInsertAuth(check_command)
        has_icmp=subprocess.check_output(check_command,shell=True)
        if has_icmp:
            return True
        #放开安全组的icmp的所有端口
        command="openstack security group rule create --protocol icmp --ingress --remote-ip 0.0.0.0/0 "+secGroupId
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def createNetwork(self,net_name,sub_net_cidr):
        """
        创建一个网络,并设置子网
        :param net_name:
        :param sub_net_cidr:
        :return:net_id
        """
        command="openstack network create "+net_name+"|grep -i \"| id\"|awk -F '|' '{print $3}'"
        command = self._openstackInsertAuth(command)
        net_id=subprocess.check_output(command,shell=True)
        net_id=net_id.strip()
        if not net_id:
            return None
        self._createSubnetForNet(net_id,sub_net_cidr)
        return net_id

    def _createSubnetForNet(self,net_id,sub_net_cidr):
        """
        为网络创建子网
        :param net_id:
        :param sub_net_cidr:
        :return:
        """
        command="openstack subnet create --subnet-range "+sub_net_cidr+" --network "+net_id+" mysubnet"
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def getNetId(self,net_name):
        """
        得到网络的id
        :param net_name:
        :return:net_id
        """
        command="openstack network list|grep -i "+net_name+"|awk -F '|' '{print $2}'"
        command=self._openstackInsertAuth(command)
        net_id=subprocess.check_output(command,shell=True)
        net_id=net_id.strip()
        if not net_id:
            return None
        return  net_id

    def getSubNetId(self,net_id):
        """
        获得网络的子网id
        :param net_id: 
        :return:subnet_id
        """
        command="openstack network list "+"|grep -i "+net_id+"|awk -F '|' '{print $4}'"
        command=self._openstackInsertAuth(command)
        subnet_id=subprocess.check_output(command,shell=True)
        subnet_id=subnet_id.strip()
        if not subnet_id:
            return None
        return subnet_id

    def getSubnetPortIds(self,subnet_id):
        """
        获得子网的端口id
        :param subnet_id:
        :return:
        """
        command="openstack port list|grep -i "+subnet_id+"|awk -F '|' '{print $2}'"
        command=self._openstackInsertAuth(command)
        subnetPort_ids=subprocess.check_output(command,shell=True)
        subnetPort_ids=subnetPort_ids.strip()
        subnetPort_ids=subnetPort_ids.split('\n')
        return subnetPort_ids

    def deleteSubnetPorts(self,subnetPort_ids):
        """
        删除子网的端口
        :param subnetPort_ids:
        :return:
        """
        if len(subnetPort_ids) != 0:
            del_subnetPorts_command = "openstack port delete "
            for subnetPort_id in subnetPort_ids:
                del_subnetPorts_command=del_subnetPorts_command+subnetPort_id+' '
            del_subnetPorts_command = self._openstackInsertAuth(del_subnetPorts_command)
            subprocess.check_output(del_subnetPorts_command, shell=True)
        return True

    def getRouterId(self,router_name):
        """
        获得路由id
        :param router_name:
        :return:router_id
        """
        command = "openstack router list|grep -i " + router_name +"|awk -F '|' '{print $2}'"
        command = self._openstackInsertAuth(command)
        router_id = subprocess.check_output(command, shell=True)
        router_id = router_id.strip()
        if not router_id:
            return None
        return router_id

    def setRouterGW(self,router_id,admin_float_net_id):
        """
        设置路由器的网关
        :param router_id:
        :param admin_float_net_id:
        :return:
        """
        command="openstack router set --external-gateway "+admin_float_net_id+" "+router_id
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def createRouter(self,router_name,admin_float_net_id):
        """
        创建一个路由并设置网关
        :param router_name:
        :param admin_float_net_id:
        :return:route_id
        """
        command="openstack router create "+router_name+"|grep -i \"| id\"|awk -F '|' '{print $3}'"
        command=self._openstackInsertAuth(command)
        route_id=subprocess.check_output(command,shell=True)
        route_id=route_id.strip()
        if not route_id:
            return None
        self.setRouterGW(route_id, admin_float_net_id)
        return route_id

    def addRouterInterface(self,router_id,sub_net_id):
        """
        将接口绑定到路由器
        :param router_id:
        :param sub_net_id:
        :return:
        """
        command="openstack router add subnet "+router_id+" "+sub_net_id
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def removeRouterInterface(self,router_id,sub_net_id):
        """
        将接口从路由器上解绑
        :param router_id:
        :param sub_net_id:
        :return:
        """
        command="openstack router remove subnet "+router_id+" "+sub_net_id
        command=self._openstackInsertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def getFloatIp(self,admin_float_net_id):
        """
        申请一个浮动ip
        :param admin_float_net_id:
        :return: ip_address
        """
        command="openstack floating ip create " +admin_float_net_id+"|grep -i floating_ip_address|awk -F '|' '{print $3}'"
        command=self._openstackInsertAuth(command)
        ip_address=subprocess.check_output(command,shell=True)
        ip_address=ip_address.strip()
        if not ip_address:
            return None
        return ip_address

    def getFloatId(self,float_ip_address):
        """
        :param float_ip_address:
        :return:
        """
        command="openstack floating ip list |grep -i "+float_ip_address+"|awk -F '|' '{print $2}'"
        command=self._openstackInsertAuth(command)
        ip_id=subprocess.check_output(command,shell=True)
        ip_id=ip_id.strip()
        return ip_id

    def getAccountfloatingipIds(self,project_id):
        """
        :param project_id:
        :return:
        """
        command="openstack floating ip list |grep -i " + project_id + "|awk -F '|' '{print $2}'"
        command = self._openstackInsertAuth(command)
        floatingip_ids = subprocess.check_output(command, shell=True)
        floatingip_ids = floatingip_ids.split('\n')
        return floatingip_ids

    def deleteAllNet(self,net_ids):
        """
        删除所有的网络
        :param net_ids:
        :return:
        """
        if len(net_ids) != 0:
            del_command = "openstack network delete "
            for net_id in net_ids:
                del_command = del_command+net_id+' '
            del_command = self._openstackInsertAuth(del_command)
            subprocess.check_output(del_command, shell=True)
        return True

    def _clearRouterGW(self, router_id):
        """
        清除路由器网关
        :param router_id:
        :return:
        """
        command = 'openstack router unset --external-gateway ' + router_id
        command = self._openstackInsertAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def deleteAllRouter(self,router_ids):
        """
        删除路由器
        :param router_ids:
        :return:
        """
        if len(router_ids) != 0:
            del_router_command = "openstack router delete "
            for router_id in router_ids:
                del_router_command=del_router_command+router_id+' '
            del_router_command = self._openstackInsertAuth(del_router_command)
            subprocess.check_output(del_router_command, shell=True)
        return True

    def deleteAllFloatIp(self,floatIp_ids):
        """
        删除浮动ip
        :param floatIp_ids:
        :return:
        """
        if len(floatIp_ids) != 0:
            del_floatIp_command = "openstack floating ip delete "
            for floatIp_id in floatIp_ids:
                del_floatIp_command = del_floatIp_command+floatIp_id+' '
            del_floatIp_command = self._openstackInsertAuth(del_floatIp_command)
            subprocess.check_output(del_floatIp_command, shell=True)
        return True
Ejemplo n.º 3
0
class HeatClient:
    def __init__(self, os_tenant_name, os_project_name, os_username,
                 os_password):
        self._authTool = AuthTool()
        self._os_tenant_name = os_tenant_name
        self._os_project_name = os_project_name
        self._os_username = os_username
        self._os_password = os_password

    def _heatInsertAuth(self, commad):
        return self._authTool.heatInsertAuth(commad, self._os_tenant_name,
                                             self._os_project_name,
                                             self._os_username,
                                             self._os_password)

    @staticmethod
    def _dealTemplateFiles(net_id, net_CIDR, image_id, image_name, flavor_id,
                           flavor_type_name, passwd, secGroup_id, max_computes,
                           min_computes, alarm_type, max_alarmvalue,
                           min_alarmvalue):
        """
        处理伸缩组2个模板
        :param net_id:
        :param net_CIDR:
        :param image_id:
        :param image_name:
        :param flavor_id:
        :param flavor_type_name:
        :param passwd:
        :param secGroup_id:
        :param max_computes:
        :param min_computes:
        :param alarm_type: 可选值有cpu_util和memory.usage
        :param max_alarmvalue: 范围为(1,100)
        :param min_alarmvalue: 范围为(1,100)
        :return:
        """
        with open('heat_template/heat_old.yaml',
                  'r+') as heat_f, open('heat_template/lb_server_old.yaml',
                                        'r+') as lb_f:
            heat_new_f = open('heat_template/heat_new.yaml', 'w+')
            lb_new_f = open('heat_template/lb_server.yaml', 'w+')
            soure_heat_text = heat_f.read()
            soure_lb_text = lb_f.read()
            #替换字符串
            resulte_heat_text = soure_heat_text.replace("net_id",net_id).replace('net_CIDR',net_CIDR).replace("image_id",image_id).replace('images_name',image_name).replace("flavorid",flavor_id).\
                     replace('passwd',passwd).replace('secGroup_id',secGroup_id).replace('flavor_type',flavor_type_name).replace('max_computes',max_computes).replace('min_computes',min_computes).\
                replace('alarm_type',alarm_type).replace('max_alarmvalue',max_alarmvalue).replace('min_alarmvalue',min_alarmvalue)

            resulte_lb_text = soure_lb_text.replace("net_id", net_id).replace("image_id", image_id).replace("flavorid", flavor_id).\
                             replace('passwd', passwd).replace('secGroup_id',secGroup_id)
            heat_f.seek(0, 0)
            lb_f.seek(0, 0)

            heat_new_f.write(resulte_heat_text)
            lb_new_f.write(resulte_lb_text)

            heat_f.close()
            heat_new_f.close()
            lb_f.close()
            lb_new_f.close()

    def creatHeat(self, net_id, net_CIDR, image_id, image_name, flavor_id,
                  flavor_type, passwd, secGroup_id, max_computes, min_computes,
                  alarm_type, max_alarmvalue, min_alarmvalue,
                  heat_templatepath, heat_name):
        """
        创建伸缩组
        :param net_id:
        :param net_CIDR:
        :param image_id:
        :param image_name:
        :param flavor_id:
        :param flavor_type:
        :param passwd:
        :param secGroup_id:
        :param max_computes:
        :param min_computes:
        :param alarm_type: 可选值有cpu_util和memory.usage
        :param max_alarmvalue: 范围为(1,100)
        :param min_alarmvalue: 范围为(1,100)
        :param heat_templatepath:新模板的路径
        :param heat_name:
        :return:
        """
        self._dealTemplateFiles(net_id, net_CIDR, image_id, image_name,
                                flavor_id, flavor_type, passwd, secGroup_id,
                                max_computes, min_computes, alarm_type,
                                max_alarmvalue, min_alarmvalue)
        commad = "heat stack-create -f" + heat_templatepath + " " + heat_name + "| grep -i " + heat_name + "| awk -F '|' '{print$2}'"
        commad = self._heatInsertAuth(commad)
        try:
            heat_id = subprocess.check_output(commad, shell=True)
            heat_id = heat_id.strip()
            if not heat_id:
                return None
            self._is_heat_run_succ(heat_id)
            return heat_id
        except Exception:
            return None

    def _is_heat_run_succ(self, heat_id):
        """
        伸缩组创建60s后是否处于运行状态
        :param heat_id:
        :return:
        """
        commad = "heat stack-list| grep -i " + heat_id + "| awk -F '|' '{print $4}'"
        commad = self._heatInsertAuth(commad)
        checkHeatRunSucc = CheckAllHeatRunSucc(heat_id, commad)
        checkHeatRunSucc.start()
        checkHeatRunSucc.join(60)
        is_succ = checkHeatRunSucc.getIsSucc()
        if not is_succ:
            checkHeatRunSucc.setIsSucc(True)
        elif is_succ:
            return True

    def deleteAllHeat(self, heat_ids):
        """
        删除伸缩组
        :param heat_ids:
        :return:
        """
        if len(heat_ids) != 0:
            del_commad = "heat stack-delete "
            for id in heat_ids:
                del_commad = del_commad + id + ' '
            del_commad = self._heatInsertAuth(del_commad)
            try:
                subprocess.check_output(del_commad, shell=True)
                self._is_del_all_heat(heat_ids)
                return True
            except Exception:
                return False

    def _is_del_all_heat(self, heat_ids):
        """
        检测账号下伸缩组是否全部删除
        :param heat_ids:
        :return:
        """
        num = len(heat_ids)
        if num != 0:
            has_heat_command = "heat stack-list |grep -E '"
            for i, heat_id in enumerate(heat_ids):
                if i != num - 1:
                    has_heat_command = has_heat_command + heat_id + "|"
                else:
                    has_heat_command = has_heat_command + heat_id
            has_heat_command = has_heat_command + "'|awk '{print $0}'"
            has_heat_command = self._heatInsertAuth(has_heat_command)
            checkHeatDel = CheckAllHeatDel(heat_ids, command=has_heat_command)
            checkHeatDel.start()
            checkHeatDel.join(1800)
            is_succ = checkHeatDel.getIsSucc()
            if not is_succ:
                checkHeatDel.setIsSucc(True)
                return False
            elif is_succ:
                return True
Ejemplo n.º 4
0
class KeystoneClient:
    def __init__(self):
        self._authTool = AuthTool()

    def createAccount(self,
                      project_name,
                      user_name,
                      password,
                      role_name='_member_'):
        """
        创建一个账户(创建项目、用户),并关联角色
        :param project_name:
        :param user_name:
        :param password:
        :param role_name: 角色,可选admin、TenantAdmin(二级账户)、_member_(三级账户),默认TenantAdmin
        :return: project_id, user_id
        """
        project_id = self._createProjectForAccount(project_name)
        user_id = self._createUserForAccount(user_name, password)
        command = "openstack role add " + "--user " + user_name + " --project " + project_name + " " + role_name
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        self._createUserForObjectStore(project_id, project_name)
        self._ActivateAccountQuota(project_id)
        return project_id, user_id

    def _createProjectForAccount(self, project_name):
        """
        创建项目
        :param project_name:
        :return: project_id
        """
        command = "openstack project create " + project_name + " -f json"
        command = self._authTool.insertAdminAuth(command)
        tmp_project_id = subprocess.check_output(command, shell=True)
        project_id = StrTool.getStringWithDic(tmp_project_id, "id")
        if not project_id:
            return None
        return project_id

    def getProjectId(self, project_name):
        """
        获取项目id
        :param project_name:
        :return: project_id
        """
        command = "openstack project list|grep -i " + project_name + "|awk '{print $2}'"
        command = self._authTool.insertAdminAuth(command)
        project_id = subprocess.check_output(command, shell=True)
        project_id = project_id.strip()
        if not project_id:
            return None
        return project_id

    def _createUserForAccount(self, user_name, password):
        """
        创建用户
        :param user_name:
        :param password:
        :return: user_id
        """
        command = "openstack user create " + user_name + " --password " + password + " -f json"
        command = self._authTool.insertAdminAuth(command)
        tmp_user_id = subprocess.check_output(command, shell=True)
        user_id = StrTool.getStringWithDic(tmp_user_id, "id")
        if not user_id:
            return None
        return user_id

    def getUserId(self, user_name):
        """
        获取用户id
        :param user_name:
        :return:
        """
        command = "openstack user list|grep -i " + user_name + "|awk '{print $2}'"
        command = self._authTool.insertAdminAuth(command)
        user_id = subprocess.check_output(command, shell=True)
        user_id = user_id.strip()
        if not user_id:
            return None
        return user_id

    @staticmethod
    def _createUserForObjectStore(project_id, project_name):
        """
        创建对象存储用户,并且生成keys
        :param project_id:
        :param project_name:
        :return:
        """
        command = "radosgw-admin user create --uid=" + project_id + " --display-name=" + project_name + " --gen-access-key --gen-secret"
        subprocess.check_output(command, shell=True)
        return True

    @staticmethod
    def _ActivateAccountQuota(project_id):
        """
        激活账户配额功能
        :param project_id:
        :return:
        """
        command = "radosgw-admin quota enable --quota-scope=user --uid=" + project_id
        subprocess.check_output(command, shell=True)
        return True

    @staticmethod
    def setObjectStoreQuota(objects_size, project_id):
        """
        更新账户对象存储大小
        :param objects_size: 文件总大小,单位字节,范围1-5497558138880
        :param project_id:
        :return:
        """
        command = "radosgw-admin quota set --quota-scope=user --max-size " + str(
            objects_size) + " --uid=" + project_id
        subprocess.check_output(command, shell=True)
        return True

    @staticmethod
    def setAccountBucketsQuota(bucket_size, project_id):
        """
        更新账户桶大小
        :param bucket_size: 桶大小,范围1-500
        :param project_id:
        :return:
        """
        command = "radosgw-admin user modify --max-buckets " + str(
            bucket_size) + " --uid=" + project_id
        subprocess.check_output(command, shell=True)
        return True

    def setInstanceStorageQuota(self, project_id, cores_size, instances_size,
                                ram_size, volumes_size, snapshots_size,
                                volumes_snapshots_size):
        """
        更新账户云主机\存储相关配额
        :param project_id:
        :param cores_size: 虚拟内核,范围1-65535
        :param instances_size: 云主机数,范围1-65535
        :param ram_size: 内存,范围1024-4194304
        :param volumes_size: 云硬盘,范围1-65535
        :param snapshots_size: 云硬盘快照,范围1-65535
        :param volumes_snapshots_size: 云硬盘和快照总大小,范围1-327675
        :return:
        """
        command = "openstack quota set " + project_id + " --cores " + str(cores_size) + " --instances " + str(instances_size) + " --ram " + str(ram_size) \
                  + " --volumes " + str(volumes_size) + " --snapshots " + str(snapshots_size) + " --gigabytes " + str(volumes_snapshots_size)
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def setAccountNetworkQuota(self, project_id, floatingip_size,
                               loadbalancer_size, router_size, network_size,
                               security_group_size):
        """
        更新账户网络相关配额
        :param project_id:
        :param floatingip_size: 浮动ip,范围1-65535
        :param loadbalancer_size: 负载均衡器,范围1-65535
        :param router_size: 路由器,范围1-65535
        :param network_size: 网络,范围1-65535
        :param security_group_size: 安全组,范围1-65535
        :return:
        """
        command = "openstack quota set " + "--floating-ips " + str(floatingip_size) + \
                  " --routers " + str(router_size) + " --networks  " + str(network_size) + " --secgroups " + str(security_group_size)+" "+project_id
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def setAccountImageQuota(self, snapshot_quota_size, image_quotas_size,
                             project_id):
        """
        更新账户镜像相关配额
        :param snapshot_quota_size: 云主机快照,范围1-500
        :param image_quotas_size: 私有镜像,范围1-100
        :param project_id:
        :return:
        """
        command = "glance image-quota-set --snapshot_quota " + str(
            snapshot_quota_size) + " --image_quotas " + str(
                image_quotas_size) + " " + project_id
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def deleteAccount(self, user_id, project_id):
        """
        删除用户
        :param user_id:
        :param project_id:
        :return:
        """
        self._deleteUser(user_id)
        self._deleteProject(project_id)
        return True

    def _deleteUser(self, user_id):
        """
        删除用户
        :param user_id:
        :return
        """
        command = "openstack user delete " + user_id
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def _deleteProject(self, project_id):
        """
        删除项目
        :param project_id:
        :return:
        """
        command = "openstack project delete " + project_id
        command = self._authTool.insertAdminAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def delAccount(self, project_ids):
        """
        删除用户
        :param project_ids:
        :return:
        """
        if len(project_ids) != 0:
            for project_id in project_ids:
                command = "openstack role assignment list|grep -i " + project_id + "|awk -F '|' '{print $3}'"
                command = self._authTool.insertAdminAuth(command)
                tmp_user_ids = subprocess.check_output(command, shell=True)
                if tmp_user_ids:
                    user_ids = tmp_user_ids.split()
                    for user_id in user_ids:
                        self._deleteUser(user_id)
                self._deleteProject(project_id)
        return True
Ejemplo n.º 5
0
 def __init__(self):
     self._authTool = AuthTool()
Ejemplo n.º 6
0
class LoadbalancerClient:
    def __init__(self, os_tenant_name, os_project_name, os_username,
                 os_password):
        self._authTool = AuthTool()
        self._os_tenant_name = os_tenant_name
        self._os_project_name = os_project_name
        self._os_username = os_username
        self._os_password = os_password

    def _neutronInsertAuth(self, command):
        return self._authTool.neutronInsertAuth(command, self._os_tenant_name,
                                                self._os_username,
                                                self._os_password)

    def createLoadbalancer(self, lb_name, floatingip_id, subnet_id,
                           connection_limit, protocol, protocol_port,
                           lb_algorithmt, delay_time, max_retries, timeout,
                           protocol_type, instance_ips_weight):
        """
        创建负载均衡器
        :param lb_name:
        :param floatingip_id:
        :param subnet_id:
        :param connection_limit: 最大连接数,可选5000,10000,20000
        :param protocol: 协议,可选HTTP、TCP
        :param protocol_port: 端口,范围1-65535
        :param lb_algorithmt: 负载均衡方式,可选ROUND_ROBIN,LEAST_CONNECTIONS,SOURCE_IP
        :param delay_time: 间隔时间,范围2-60
        :param max_retries: 尝试次数,范围1-10
        :param timeout: 超时时间,范围5-300
        :param protocol_type: 健康检查方式,可选PING、HTTP
        :param instance_ips_weight: 数组[[云主机ip,weight],[云主机ip,weight]],weight范围1-10
        :return: loadbalancer_id
        """
        command = "neutron lbaas-loadbalancer-create --name " + lb_name + " --floatingip_id " + floatingip_id + " -f json"
        command = self._neutronInsertAuth(command)
        loadbalancer_id = subprocess.check_output(command, shell=True)
        loadbalancer_id = StrTool.getStringWithLBRB(
            loadbalancer_id, '{"Field": "id", "Value": "', '"}')
        loadbalancer_id = loadbalancer_id.strip()
        if not loadbalancer_id:
            return None
        self._addInterfaceForLoadbalancer(loadbalancer_id, subnet_id)
        listener_id = self._addListenerForLoadbalancer(lb_name,
                                                       loadbalancer_id,
                                                       connection_limit,
                                                       protocol, protocol_port)
        pool_id = self._addPoolForLoadbalancer(lb_name, listener_id, protocol,
                                               lb_algorithmt)
        self._addHealthmonitorForLoadbalancer(delay_time, max_retries, timeout,
                                              protocol_type, pool_id)
        for instance_ip_weight in instance_ips_weight:
            self.addMemberForLoadbalancer(subnet_id, instance_ip_weight[0],
                                          protocol_port, instance_ip_weight[1],
                                          pool_id)
        return loadbalancer_id

    def _addInterfaceForLoadbalancer(self, loadbalancer_id, subnet_id):
        """
        为负载均衡器添加内网接口
        :param loadbalancer_id:
        :param subnet_id:
        :return:
        """
        command = "neutron lbaas-loadbalancer-interface-add " + loadbalancer_id + " " + subnet_id + " -f json"
        command = self._neutronInsertAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def _addListenerForLoadbalancer(self, listener_name, loadbalancer_id,
                                    connection_limit, protocol, protocol_port):
        """
        为负载均衡器创建监听器
        :param listener_name:
        :param loadbalancer_id:
        :param connection_limit:
        :param protocol:
        :param protocol_port:
        :return: listener_id
        """
        command = "neutron lbaas-listener-create --name " + listener_name + " --loadbalancer " + loadbalancer_id + " --connection_limit "\
                  + connection_limit + " --protocol " + protocol + " --protocol-port " + protocol_port + " -f json"
        command = self._neutronInsertAuth(command)
        listener_id = subprocess.check_output(command, shell=True)
        listener_id = StrTool.getStringWithLBRB(listener_id,
                                                '{"Field": "id", "Value": "',
                                                '"}')
        listener_id = listener_id.strip()
        if not listener_id:
            return None
        return listener_id

    def _addPoolForLoadbalancer(self, pool_name, listener_id, protocol,
                                lb_algorithmt):
        """
        为负载均衡器创建pool
        :param pool_name:
        :param listener_id:
        :param protocol:
        :param lb_algorithmt:
        :return: pool_id
        """
        command = "neutron lbaas-pool-create --name " + pool_name + " --listener " + listener_id + " --protocol " + protocol\
                  + " --lb-algorithm " + lb_algorithmt + " -f json"
        command = self._neutronInsertAuth(command)
        pool_id = subprocess.check_output(command, shell=True)
        pool_id = StrTool.getStringWithLBRB(pool_id,
                                            '{"Field": "id", "Value": "', '"}')
        pool_id = pool_id.strip()
        if not pool_id:
            return None
        return pool_id

    def _addHealthmonitorForLoadbalancer(self, delay_time, max_retries,
                                         timeout, protocol_type, pool_id):
        """
        为负载均衡器创建健康检测器
        :param delay_time:
        :param max_retries:
        :param timeout:
        :param protocol_type:
        :param pool_id:
        :return: healthmonitor_id
        """
        command = "neutron lbaas-healthmonitor-create --delay " + delay_time + " --max-retries " + max_retries + " --timeout " + timeout\
                  + " --type " + protocol_type + " --pool  " + pool_id  + " -f json"
        command = self._neutronInsertAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def addMemberForLoadbalancer(self, subnet_id, instance_ip, protocol_port,
                                 weight, pool_id):
        """
        为负载均衡器添加后端服务器
        :param subnet_id:
        :param instance_ip:
        :param protocol_port:
        :param weight:
        :param pool_id:
        :return:
        """
        command = "neutron lbaas-member-create --subnet " + subnet_id + " --address " + str(instance_ip) + " --protocol-port " + str(protocol_port)\
                  + " --weight " + str(weight) + " " + pool_id + " -f json"
        command = self._neutronInsertAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def _getListenerId(self, loadbalancer_id):
        """
        获取负载均衡器listenerid
        :param loadbalancer_id:
        :return: listener_id
        """
        command = "neutron lbaas-loadbalancer-show " + loadbalancer_id + " -f json"
        command = self._neutronInsertAuth(command)
        tmp_listener_id = subprocess.check_output(command, shell=True)
        tmp_listener_id = StrTool.getStringWithLBRB(
            tmp_listener_id,
            '{"Field": "listeners", "Value": "{\\\\"id\\\\": \\\\"', '\\\\"}')
        listener_id = tmp_listener_id.strip()
        if not listener_id:
            return None
        return listener_id

    def _getPoolId(self, listener_id):
        """
        获取所有负载均衡器池id
        :param listener_id:
        :return: pool_id
        """
        command = "neutron lbaas-listener-show " + listener_id + " -f json"
        command = self._neutronInsertAuth(command)
        tmp_pool_id = subprocess.check_output(command, shell=True)
        tmp_pool_id = StrTool.getStringWithLBRB(
            tmp_pool_id, '{"Field": "default_pool_id", "Value": "', '"}')
        pool_id = tmp_pool_id.strip()
        if not pool_id:
            return None
        return pool_id

    def _getHealthmonitorId(self, pool_id):
        """
        获取所有负载均衡器健康检测器id
        :param pool_id:
        :return: healthmonitor_id
        """
        command = "neutron lbaas-pool-show " + pool_id + " -f json"
        command = self._neutronInsertAuth(command)
        tmp_healthmonitor_id = subprocess.check_output(command, shell=True)
        tmp_healthmonitor_id = StrTool.getStringWithLBRB(
            tmp_healthmonitor_id, '{"Field": "healthmonitor_id", "Value": "',
            '"}')
        healthmonitor_id = tmp_healthmonitor_id.strip()
        if not healthmonitor_id:
            return None
        return healthmonitor_id

    def _getMemberId(self, pool_id):
        """
        获取所有负载均衡器后端服务器id
        :param pool_id:
        :return: member_ids
        """
        command = "neutron lbaas-pool-show " + pool_id + " -f json"
        command = self._neutronInsertAuth(command)
        tmp_member_ids = subprocess.check_output(command, shell=True)
        tmp_member_ids = StrTool.getStringWithLBRB(
            tmp_member_ids, '{"Field": "members", "Value": "', '"}')
        member_ids = []
        if not tmp_member_ids.strip():
            return member_ids
        member_ids = tmp_member_ids.split('\\n')
        return member_ids

    def _deleteMember(self, pool_id):
        """
        删除负载均衡器中的后端服务器
        :param pool_id:
        :return:
        """
        member_ids = self._getMemberId(pool_id)
        if len(member_ids[0]) != 0:
            for member_id in member_ids:
                del_member_command = "neutron lbaas-member-delete " + member_id + " " + pool_id
                del_member_command = self._neutronInsertAuth(
                    del_member_command)
                subprocess.check_output(del_member_command, shell=True)
                return True

    def _deleteHealthmonitor(self, healthmonitor_id):
        """
        删除负载均衡器中的healthmonitor
        :param healthmonitor_id:
        :return:
        """
        del_healthmonitor_command = "neutron lbaas-healthmonitor-delete " + healthmonitor_id
        del_healthmonitor_command = self._neutronInsertAuth(
            del_healthmonitor_command)
        subprocess.check_output(del_healthmonitor_command, shell=True)
        return True

    def _deletePool(self, pool_id):
        """
        删除负载均衡器中的pool
        :param pool_id:
        :return:
        """
        del_pool_command = "neutron lbaas-pool-delete " + pool_id
        del_pool_command = self._neutronInsertAuth(del_pool_command)
        subprocess.check_output(del_pool_command, shell=True)
        return True

    def _deleteListener(self, listener_id):
        """
        删除负载均衡器中的listener
        :param listener_id:
        :return:
        """
        del_listener_command = "neutron lbaas-listener-delete " + listener_id
        del_listener_command = self._neutronInsertAuth(del_listener_command)
        subprocess.check_output(del_listener_command, shell=True)
        return True

    def deleteLoadbalancer(self, loadbalancer_ids):
        """
        删除账号下所有负载均衡器
        :param loadbalancer_ids:
        :return:
        """
        if len(loadbalancer_ids) != 0:
            for loadbalancer_id in loadbalancer_ids:
                loadbalancer_id = loadbalancer_id.encode('utf-8')
                del_loadbalancer_command = "neutron lbaas-loadbalancer-delete " + loadbalancer_id
                del_loadbalancer_command = self._neutronInsertAuth(
                    del_loadbalancer_command)
                # 先删除member、healthmonitor、pool、listener再来删除负载均衡器
                listener_id = self._getListenerId(loadbalancer_id)
                pool_id = self._getPoolId(listener_id)
                healthmonitor_id = self._getHealthmonitorId(pool_id)
                self._deleteMember(pool_id)
                self._deleteHealthmonitor(healthmonitor_id)
                self._deletePool(pool_id)
                self._deleteListener(listener_id)
                subprocess.check_output(del_loadbalancer_command, shell=True)
            return True
Ejemplo n.º 7
0
class CinderClient:
    def __init__(self, os_tenant_name, os_project_name, os_username,
                 os_password):
        self._authTool = AuthTool()
        self._os_tenant_name = os_tenant_name
        self._os_project_name = os_project_name
        self._os_username = os_username
        self._os_password = os_password

    def _cinderInertAuth(self, command):
        """
        cinder命令加入授权信息
        :param command:
        :return:
        """
        return self._authTool.cinderInsertAuth(command, self._os_tenant_name,
                                               self._os_project_name,
                                               self._os_username,
                                               self._os_password)

    def getVolumeTypeId(self, volume_type_name):
        """
        获得磁盘类型的id
        :param volume_type_name:
        :return:volume_type_id
        """
        command = "cinder type-list |grep -i " + volume_type_name + "|awk -F '|' '{print $2}'"
        command = self._cinderInertAuth(command)
        volume_type_id = subprocess.check_output(command, shell=True)
        volume_type_id = volume_type_id.strip()
        if not volume_type_id:
            return None
        return volume_type_id

    def getVolumeId(self, volume_name):
        """
        获得磁盘id
        :param volume_name:
        :return:volume_id
        """
        command = "cinder list --all-tenant 1|grep -i " + volume_name + "|awk -F '|' '{print $2}'"
        command = self._cinderInertAuth(command)
        volume_id = subprocess.check_output(command, shell=True)
        volume_id = volume_id.strip()
        if not volume_id:
            return None
        return volume_id

    def createVolume(self, volume_name, volume_type_id, volume_size):
        """
        volume_size:
        :param volume_name:
        :param volume_type_id:
        :param volume_size:单位为GB
        :return:volume_id
        """
        command = "cinder create --name " + volume_name + " --volume-type " + volume_type_id + " " + str(
            volume_size) + "|grep -w id|awk -F '|' '{print $3}'"
        command = self._cinderInertAuth(command)
        volume_id = subprocess.check_output(command, shell=True)
        volume_id = volume_id.strip()
        self._is_volume_create_succ(volume_id)
        return volume_id

    def _is_volume_create_succ(self, volume_id):
        """
        每0.5秒判断一次云硬盘是否创建成功,30秒超时
        :param volume_id:
        :return:
        """
        command = "cinder list|grep -i " + volume_id.strip(
        ) + " |grep -i 'available'|awk '{print $0}'"
        command = self._cinderInertAuth(command)
        checkVolumeCreateSucc = CheckVolumeCreateSucc(volume_id, command)
        checkVolumeCreateSucc.start()
        checkVolumeCreateSucc.join(30)
        is_succ = checkVolumeCreateSucc.getIsSucc()
        if not is_succ:
            checkVolumeCreateSucc.setIsSucc(True)
            return False
        elif is_succ:
            return True

    def deleteAllVolume(self, volume_ids):
        """
        每0.5秒判断一次云硬盘是否创建成功,30秒超时
        :param volume_ids:
        :return:
        """
        if len(volume_ids) != 0:
            del_command = "cinder delete "
            for volume_id in volume_ids:
                del_command = del_command + volume_id + ' '
            del_command = self._cinderInertAuth(del_command)
            subprocess.check_output(del_command, shell=True)
            self._is_all_volume_del(volume_ids)
            return True

    def _is_all_volume_del(self, volume_ids):
        """
        检测账号云硬盘是否全部删除
        :param volume_ids:
        :return:
        """
        num = len(volume_ids)
        if num != 0:
            has_volume_command = "cinder list|grep -E '"
            for i, volume_id in enumerate(volume_ids):
                if i != num - 1:
                    has_volume_command = has_volume_command + volume_id + '|'
                else:
                    has_volume_command = has_volume_command + volume_id
            has_volume_command = has_volume_command + "'|awk '{print $0}'"
            has_volume_command = self._cinderInertAuth(has_volume_command)
            checkAllVolumeDel = CheckAllVolumeDel(volume_ids,
                                                  has_volume_command)
            checkAllVolumeDel.start()
            checkAllVolumeDel.join(1800)
            is_succ = checkAllVolumeDel.getIsSucc()
            if not is_succ:
                checkAllVolumeDel.setIsSucc(True)
                return False
            elif is_succ:
                return True
Ejemplo n.º 8
0
class TroveClient:
    def __init__(self, os_tenant_name, os_project_name, os_username,
                 os_password):
        self._authTool = AuthTool()
        self._os_tenant_name = os_tenant_name
        self._os_project_name = os_project_name
        self._os_username = os_username
        self._os_password = os_password

    def _troveInertAuth(self, command):
        """
        trove相关命令行加入授权信息
        :param command:
        :return:
        """
        return self._authTool.troveInsertAuth(command, self._os_tenant_name,
                                              self._os_project_name,
                                              self._os_username,
                                              self._os_password)

    def createtrove(self, trove_name, flavor_id, trove_volume_size,
                    database_name, user_name, user_password, net_id, zone_name,
                    datastore_name, datastore_version_name):
        """
         创建数据库实例
        :param trove_name:
        :param flavor_id:
        :param trove_volume_size:
        :param database_name:
        :param user_name:
        :param user_password:
        :param net_id:
        :param zone_name:
        :param datastore_name:
        :param datastore_version_name:
        :return: trove_id
        """
        command = "trove create " + trove_name + " " + flavor_id + " --size " + trove_volume_size + " --databases " + database_name + " --users " + user_name + ":" + user_password + " --nic net-id=" + net_id + " --availability_zone " + zone_name + "  --datastore " + datastore_name + " --datastore_version " + datastore_version_name + "|grep -w id|awk -F '|' '{print $3}'"
        command = self._troveInertAuth(command)
        try:
            trove_id = subprocess.check_output(command, shell=True)
            trove_id = trove_id.strip()
            if not trove_id:
                return None
            self._is_trove_run_succ(trove_id)
            return trove_id
        except Exception:
            return None

    def _is_trove_run_succ(self, trove_id):
        """
        数据库实例创建60秒后是否处于运行中
        :param trove_id:
        :return:
        """
        command = "trove list|grep -i " + trove_id + "|awk -F '|' '{print $6}'"
        command = self._troveInertAuth(command)
        checkTroveRunSucc = CheckTroveRunSucc(trove_id, command)
        checkTroveRunSucc.start()
        checkTroveRunSucc.join(300)
        is_succ = checkTroveRunSucc.getIsSucc()
        if not is_succ:
            checkTroveRunSucc.setIsSucc(True)
            return False
        elif is_succ:
            return True

    def deleteAllTrove(self, trove_ids):
        """
        删除所有数据库实例
        :param trove_ids:
        :return:
        """
        if len(trove_ids) != 0:
            #不支持批量,一个一个删除
            for trove_id in trove_ids:
                del_command = "trove delete " + trove_id + ' '
                del_command = self._troveInertAuth(del_command)
                subprocess.check_output(del_command, shell=True)
                self._is_trove_del(trove_id)

    def _is_trove_del(self, trove_id):
        """
        检测账号下数据库实例是否全部删除
        :param trove_id:
        :return:
        """
        has_trove_command = "trove list |grep -E '" + trove_id + "'|awk '{print $0}'"
        has_trove_command = self._troveInertAuth(has_trove_command)
        checkTroveDel = CheckTroveDel(trove_id, has_trove_command)
        checkTroveDel.start()
        checkTroveDel.join(60)
        is_succ = checkTroveDel.getIsSucc()
        if not is_succ:
            checkTroveDel.setIsSucc(True)
            return False
        elif is_succ:
            return True
Ejemplo n.º 9
0
class ObjectStoreClient:
    def __init__(self):
        self._authTool = AuthTool()

    @staticmethod
    def getKeys(project_id):
        """
        获取存储密钥
        :param project_id:
        :return:
        """
        getKeys_commad = 'radosgw-admin user info --uid=' + project_id + ' --format=json'
        try:
            tmp_keys = subprocess.check_output(getKeys_commad, shell=True)
            keys = ujson.loads(tmp_keys)
            keys = keys['keys'][0]
            access_key = keys['access_key']
            secret_key = keys['secret_key']
            access_key.strip()
            secret_key.strip()
            if not access_key or not secret_key:
                return None
            return access_key, secret_key
        except Exception:
            return None

    def getIp(self):
        """
        获取存储地址
        :return:
        """
        commad = "openstack endpoint show -f json `openstack  endpoint list | grep swift_s3 | grep public | awk {'print $2'}`"
        commad = self._authTool.insertAdminAuth(commad)
        try:
            tmp_ip = subprocess.check_output(commad, shell=True)
            tmp_ip = ujson.dumps(tmp_ip)
            ip = StrTool.getStringWithLBRB(tmp_ip, 'url\\\\": \\\\"http://',
                                           '\\\\",', 'all')
            ip = ip[0].strip()
            if not ip:
                return None
            return ip
        except Exception:
            return None

    @staticmethod
    def deleteAllBuckets(project_id):
        """
        删除某账户下所有桶和文件
        :param project_id:
        :return:
        """
        command = "radosgw-admin bucket stats --uid=" + project_id + " -f json"
        tmp_buckets_name = subprocess.check_output(command, shell=True)
        tmp_buckets_name = ujson.loads(tmp_buckets_name)
        for bucketname in tmp_buckets_name:
            bucket_name = bucketname["bucket"]
            del_commad = "radosgw-admin bucket rm --bucket=" + bucket_name + " --purge-objects"
            subprocess.check_output(del_commad, shell=True)
        return True

    @staticmethod
    def deleteAccountBuckets(bucket_name):
        """
        删除符合搜索名称的桶和文件
        :param bucket_name:
        :return:
        """
        command = "radosgw-admin metadata list bucket|grep -i " + bucket_name
        try:
            tmp_buckets_name = subprocess.check_output(command, shell=True)
            pattern = re.compile('"(.*)"')
            buckets_name = pattern.findall(tmp_buckets_name)
            fbsArr = [
                "$", "(", ")", "*", "+", "[", "]", "?", "^", "{", "}", "|"
            ]
            for bucket_name in buckets_name:
                command = "radosgw-admin  bucket check --bucket=" + bucket_name
                tmp_files_name = subprocess.check_output(command, shell=True)
                files_name = pattern.findall(tmp_files_name)
                for file_name in files_name:
                    for key in fbsArr:
                        if file_name.find(key) >= 0:
                            file_name = file_name.replace(key, "\\" + key)
                    del_file_command = "radosgw-admin object rm --bucket=" + bucket_name + " --object=" + file_name
                    subprocess.check_output(del_file_command, shell=True)
                del_bucket_command = "radosgw-admin bucket rm --bucket=" + bucket_name + " --purge-objects"
                subprocess.check_output(del_bucket_command, shell=True)
        except subprocess.CalledProcessError as err:
            print("Command Error:", err)
        return True
Ejemplo n.º 10
0
class NovaClient:
    def __init__(self,os_project_name,os_username,os_password):
        self._authTool=AuthTool()
        self._os_project_name=os_project_name
        self._os_username=os_username
        self._os_password=os_password

    def _novaInertAuth(self,command):
        """
        nova相关命令行加入授权信息
        :param command:
        :return:
        """
        return self._authTool.novaInsertAuth(command,self._os_project_name,self._os_username,self._os_password)

    def getImageId(self,image_name):
        """
        获得镜像id
        :param image_name:
        :return:image_id
        """
        command="nova image-list |grep -i "+image_name+"|awk -F '|' '{print$2}'"
        command=self._novaInertAuth(command)
        image_id=subprocess.check_output(command,shell=True)
        image_id = image_id.strip()
        if not image_id:
            return None
        return image_id

    def getFlavorId(self,flavor_name):
        """
        获得云主机规格id
        :param flavor_name:
        :return:flavor_id
        """
        command="nova flavor-list |grep -i "+flavor_name+"|awk -F '|' '{print $2}'"
        command=self._novaInertAuth(command)
        flavor_id=subprocess.check_output(command,shell=True)
        flavor_id=flavor_id.strip()
        if not flavor_id:
            return None
        return flavor_id

    def bootCompute(self,compute_name,flavor_id,image_id,net_id,secgroup_id,zone_name,user_data_file_path):
        """
        启动一台云主机,并绑定浮动ip
        :param compute_name:
        :param flavor_id:
        :param image_id:
        :param net_id:
        :param secgroup_id:
        :param zone_name:
        :param user_data_file_path:
        :return:compute_id
        """
        command="nova boot --flavor "+flavor_id+" --image "+image_id+" --security-groups "+secgroup_id+" --nic net-id="+net_id+" --availability-zone "+zone_name+"  --user-data "+user_data_file_path+" "+compute_name+"|grep -w id|awk -F '|' '{print $3}'"
        command=self._novaInertAuth(command)
        compute_id=subprocess.check_output(command,shell=True)
        compute_id = compute_id.strip()
        if not compute_id:
            return None
        self._is_compute_run_succ(compute_id)
        return compute_id

    def _is_compute_run_succ(self,compute_id):
        """
        云主机创建60秒后是否处于运行中
        :param compute_id:
        :return:
        """
        command = "nova list|grep -i "+compute_id+"|awk -F '|' '{print $4}'"
        command = self._novaInertAuth(command)
        checkComputeRunSucc=CheckComputeRunSucc(compute_id,command)
        checkComputeRunSucc.start()
        checkComputeRunSucc.join(120)
        is_succ=checkComputeRunSucc.getIsSucc()
        if not is_succ:
            checkComputeRunSucc.setIsSucc(True)
            return False
        elif is_succ:
            return True

    def getComputeId(self,compute_name):
        """
        获取云主机id
        :param compute_name:
        :return:compute_id
        """
        command = "nova list|grep -i "+compute_name+"|awk -F '|' '{print $2}'"
        command =self._novaInertAuth(command)
        compute_id = subprocess.check_output(command, shell=True)
        compute_id = compute_id.strip()
        if not compute_id:
            return None
        return compute_id

    def getTenantsComputeId(self,compute_name):
        """
        获取所有账户云主机id
        :param compute_name:
        :return:compute_id
        """
        command = "nova list --all-tenant|grep -i "+compute_name+"|awk -F '|' '{print $2}'"
        command =self._novaInertAuth(command)
        compute_id = subprocess.check_output(command, shell=True)
        compute_id = compute_id.strip()
        if not compute_id:
            return None
        return compute_id

    def getComputeFloatIp(self,compute_name):
        """
        获取云主机浮动ip
        :param compute_name:
        :return:float_ip
        """
        compute_id=self.getComputeId(compute_name)
        command="nova list |grep -i "+compute_id+"|awk -F '|' '{print $7}'|awk -F '=' '{print $2}'"
        command=self._novaInertAuth(command)
        float_ip=subprocess.check_output(command,shell=True)
        float_ip=float_ip.split(',')[-1]
        float_ip=float_ip.strip()
        if not float_ip:
            return None
        return float_ip

    def getComputeIp(self,compute_name):
        """
        获取云主机ip
        :param compute_name:
        :return:ip
        """
        compute_id=self.getComputeId(compute_name)
        command="nova list |grep -i "+compute_id+"|awk -F '|' '{print $7}'|awk -F '=' '{print $2}'"
        command=self._novaInertAuth(command)
        ip=subprocess.check_output(command,shell=True)
        ip=ip.split(',')[0]
        ip=ip.strip()
        if not ip:
            return None
        return ip

    def addFloatForCompute(self,compute_id,float_ip_address):
        """
        绑定浮动ip
        :param compute_id:
        :param float_ip_address:
        :return:
        """
        command = "nova floating-ip-associate "+compute_id+" "+float_ip_address
        command =self._novaInertAuth(command)
        subprocess.check_output(command, shell=True)
        return True

    def attachVolume(self,compute_id,volume_id,device_name):
        """
        挂载云硬盘
        :param compute_id:
        :param volume_id:
        :param device_name:
        :return:
        """
        command="nova volume-attach "+compute_id+' '+volume_id+' '+device_name
        command=self._novaInertAuth(command)
        subprocess.check_output(command,shell=True)
        return True

    def deleteAllCompute(self,compute_ids):
        """
        删除所有云主机
        :param compute_ids:
        :return:
        """
        if len(compute_ids)!=0:
            del_command="nova delete "
            for compute_id in compute_ids:
                del_command=del_command+compute_id+' '
            del_command=self._novaInertAuth(del_command)
            subprocess.check_output(del_command,shell=True)
            self._is_all_compute_del(compute_ids)
        return True

    def _is_all_compute_del(self,compute_ids):
        """
        检测云主机是否全部删除
        :param compute_ids:
        :return:
        """
        num=len(compute_ids)
        if num!=0:
            has_compute_command = "nova list |grep -E '"
            for i,compute_id in enumerate(compute_ids):
                if i!=num-1:
                    has_compute_command=has_compute_command+compute_id+"|"
                else:
                    has_compute_command=has_compute_command+compute_id
            has_compute_command=has_compute_command+"'|awk '{print $0}'"
            has_compute_command =self._novaInertAuth(has_compute_command)
            checkAllComputeDel=CheckAllComputeDel(compute_ids,has_compute_command)
            checkAllComputeDel.start()
            checkAllComputeDel.join(1800)
            is_succ=checkAllComputeDel.getIsSucc()
            if not is_succ:
                checkAllComputeDel.setIsSucc(True)
                return False
            elif is_succ:
                return True