def applySecurityGroupsToLoadBalancer(self, farmNo, loadBalancerNo, groupmap, subnets) :
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        # ロードバランサ名
        loadBalancerName = awsLoadBalancer["NAME"]

        # サブネットIDが設定されていなければリターン
        subnetIds = []
        if (isNotEmpty(awsLoadBalancer["SUBNET_ID"])):
            subnetIds = awsLoadBalancer["SUBNET_ID"].split(",")
        else:
            return

        #セキュリティグループ
        securityGroups = []
        if (isNotEmpty(awsLoadBalancer["SECURITY_GROUPS"])):
            securityGroups = awsLoadBalancer["SECURITY_GROUPS"].split(",")
        #IDへ変換
        securityGroupIds = []
        for subnet in subnets:
            if subnetIds[0] == subnet.subnetId:
                #セキュリティグループID
                for group in securityGroups:
                    key = group+subnet.vpcId
                    securityGroupIds.append(groupmap[key])

        # セキュリティグループ設定を変更
        self.client.applySecurityGroupsToLoadBalancer(securityGroupIds, loadBalancerName);

        #実行ログ
        self.logger.info(None ,"IPROCESS-200225", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbSecurityGroupsConfig", ["EC2", loadBalancerName,] )
Esempio n. 2
0
    def startInstance(self, instanceNo):
        #VAPPロック
        self.doWaitingExecution(self.getVappName(instanceNo=instanceNo))

        #仮想マシンを(作成)起動
        self.instancecontroller.startInstance(instanceNo)

        # ボリュームに関する処理
        table = self.conn.getTable("VCLOUD_DISK")
        volumes = self.conn.select(table.select(table.c.INSTANCE_NO==instanceNo))
        for disk in volumes:
            if isNotEmpty(disk["COMPONENT_NO"]):
                # コンポーネント番号がある場合はスキップ
                continue

            if isNotEmpty(disk["DISK_ID"]):
                # アタッチされている場合はスキップ
                continue

            #Volumeスタート
            self.volumecontroller.startVolume(instanceNo, disk["DISK_NO"])

        #VAPPロック解除
        self.doWaitingExecutionEnd()
        self.conn.commit()
        return True
    def applySecurityGroupsToLoadBalancer(self, farmNo, loadBalancerNo, groupmap, subnets) :
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        # ロードバランサ名
        loadBalancerName = awsLoadBalancer["NAME"]

        # サブネットIDが設定されていなければリターン
        subnetIds = []
        if (isNotEmpty(awsLoadBalancer["SUBNET_ID"])):
            subnetIds = awsLoadBalancer["SUBNET_ID"].split(",")
        else:
            return

        #セキュリティグループ
        securityGroups = []
        if (isNotEmpty(awsLoadBalancer["SECURITY_GROUPS"])):
            securityGroups = awsLoadBalancer["SECURITY_GROUPS"].split(",")
        #IDへ変換
        securityGroupIds = []
        for subnet in subnets:
            if subnetIds[0] == subnet.subnetId:
                #セキュリティグループID
                for group in securityGroups:
                    key = group+subnet.vpcId
                    securityGroupIds.append(groupmap[key])

        # セキュリティグループ設定を変更
        self.client.applySecurityGroupsToLoadBalancer(securityGroupIds, loadBalancerName);

        #実行ログ
        self.logger.info(None ,"IPROCESS-200225", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbSecurityGroupsConfig", ["EC2", loadBalancerName,] )
    def createLoadBalancer(self, farmNo, loadBalancerNo, availabilityZones, subnets, groupmap) :
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))

        # ロードバランサ作成情報
        loadBalancerName = awsLoadBalancer["NAME"]

        # デフォルトゾーンの特定 デフォルト1件目
        availabilityZone = None
        for zone in availabilityZones:
            availabilityZone = zone.name

        #セキュリティグループ
        securityGroups = []
        if (isNotEmpty(awsLoadBalancer["SECURITY_GROUPS"])):
            securityGroups = awsLoadBalancer["SECURITY_GROUPS"].split(",")

        #サブネットID
        subnetIds = []
        if (isNotEmpty(awsLoadBalancer["SUBNET_ID"])):
            subnetIds = awsLoadBalancer["SUBNET_ID"].split(",")

        # サブネット(VPC)との関係からセキュリティグループIDを取得
        securityGroupIds = []
        if len(subnetIds) != 0:
            for subnet in subnets:
                if subnetIds[0] == subnet.subnetId:
                    #セキュリティグループID
                    for group in securityGroups:
                        key = group+subnet.vpcId
                        securityGroupIds.append(groupmap[key])


        # ダミーのリスナーの設定  instancePort, instanceProtocol, loadBalancerPort, protocol, sslCertificateId
        listener = Listener("65535", None, "65535","TCP",None)
        listeners = [listener]

        # ロードバランサの作成
        dnsName = self.client.createLoadBalancer(availabilityZone, listeners, loadBalancerName, subnetIds, securityGroupIds)

        #実行ログ
        self.logger.info(None ,"IPROCESS-200111", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbCreate", ["EC2", loadBalancerName] )

        # ダミーのリスナーの削除
        self.client.deleteLoadBalancerListeners(["65535",], loadBalancerName)

        # データベース更新
        updateDict = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        updateDict["DNS_NAME"] = dnsName
        sql = tableAWSLB.update(tableAWSLB.c.LOAD_BALANCER_NO ==updateDict["LOAD_BALANCER_NO"], values=updateDict)
        self.conn.execute(sql)

        return dnsName;
    def run(self, instanceNo, awsInstance, pccInstance, image):
        #UserDataを作成
        userData = self.createUserData(instanceNo, pccInstance, awsInstance)
        userData = self.makeUserData(userData)

        self.logger.info("userData:"+userData)

        #サブネット
        subnet = None
        if (isNotEmpty(awsInstance["SUBNET_ID"])):
            subnet = self.client.describeSubnets(awsInstance["SUBNET_ID"])[0]

        groupmap = {}
        groups = self.client.describeSecurityGroups()
        for group in groups:
            #サブネット入力時はVPCIDが一致する物をマッピング
            if subnet is not None:
                if subnet.vpcId == group.vpcId:
                    groupmap.update({group.groupName:group.groupId})

        #SecurityGroup
        securityGroups = []
        if (isNotEmpty(awsInstance["SECURITY_GROUPS"])):
            securityGroups = awsInstance["SECURITY_GROUPS"].split(",")

        availabilityZone = None
        if (isNotEmpty(awsInstance["AVAILABILITY_ZONE"])):
            availabilityZone = awsInstance["AVAILABILITY_ZONE"]

        blockDeviceMappings = self.createBlockDeviceMappings(image["imageId"], awsInstance["INSTANCE_TYPE"])

        #イベントログ出力
        self.conn.debug(pccInstance["FARM_NO"], None, None, instanceNo, pccInstance["INSTANCE_NAME"], "AwsInstanceCreate",["EC2"])

        #インスタンスの作成
        instance2 = self.client.runInstances(groupmap = groupmap,
                                            imageId = image["imageId"],
                                            kernelId = image["kernelId"],
                                            ramdiskId = image["ramdiskId"],
                                            keyName = awsInstance["KEY_NAME"],
                                            instanceType =awsInstance["INSTANCE_TYPE"],
                                            securityGroup = securityGroups,
                                            location = availabilityZone,
                                            userData = userData,
                                            subnetId = awsInstance["SUBNET_ID"],
                                            privateIpAddress = awsInstance["PRIVATE_IP_ADDRESS"],
                                            blockDeviceMapping = blockDeviceMappings)

        #データベース更新
        table = self.conn.getTable("AWS_INSTANCE")
        updateDict = self.conn.selectOne(table.select(table.c.INSTANCE_NO==instanceNo))
        updateDict["INSTANCE_ID"] = instance2.id
        updateDict["STATUS"] = instance2.extra['status']
        sql = table.update(table.c.INSTANCE_NO ==updateDict["INSTANCE_NO"], values=updateDict)
        self.conn.execute(sql)
Esempio n. 6
0
    def createUserNetwork(self):
        # UserDataを作成
        userData = {}
        zabbixserver = getOtherProperty("zabbix.server")
        if (isNotEmpty(zabbixserver)):
            #Zabbixサーバー(ルーティング用)
            userData.update({"zabbixserver": zabbixserver})

        routeAddserver = getOtherProperty("vCloud.routeAddserver")
        if (isNotEmpty(routeAddserver)):
            #ユーザー指定ルーティングサーバ
            userData.update({"routeAddserver": routeAddserver})

        return userData
    def createUserNetwork(self):
        # UserDataを作成
        userData = {}
        zabbixserver = getOtherProperty("zabbix.server")
        if isNotEmpty(zabbixserver):
            # Zabbixサーバー(ルーティング用)
            userData.update({"zabbixserver": zabbixserver})

        routeAddserver = getOtherProperty("vCloud.routeAddserver")
        if isNotEmpty(routeAddserver):
            # ユーザー指定ルーティングサーバ
            userData.update({"routeAddserver": routeAddserver})

        return userData
    def attachVolume(self, vcInstance, disk):
        #FARM 取得
        tableFarm = self.conn.getTable("FARM")
        farm = self.conn.selectOne(tableFarm.select(tableFarm.c.FARM_NO==disk["FARM_NO"]))

        #組織
        vdc = self.client.getUseVdc()
        #マイクラウド
        vApp = self.client.describeMyCloud(vdc, farm["FARM_NAME"])
        #既存VM検索
        vm = self.client.describeInstance(vApp, vcInstance["VM_NAME"])
        # DISKNAMEがある場合は編集確認
        if (isNotEmpty(disk["DISK_ID"])):
            oldDisk = self.client.describeVolume(vm, disk["DISK_ID"])
            #ディスクの実態が確認できない(矛盾発生)場合はそのまま返す
            if oldDisk is None:
                self.logger.info("VOLUME IS NONE")
                return

            #何らかの影響でクラウド側の容量の方が大きい場合はDBを更新し合わせる
            if int(oldDisk.size) > (int(disk["SIZE"]) * 1024) :
                table = self.conn.getTable("VCLOUD_DISK")
                updateDict = self.conn.selectOne(table.select(table.c.DISK_NO==disk["DISK_NO"]))
                updateDict["SIZE"] = int(oldDisk.size)/1024
                sql = table.update(table.c.DISK_NO ==updateDict["DISK_NO"], values=updateDict)
                self.conn.execute(sql)

            #サイズ増
            if (int(disk["SIZE"]) * 1024) > int(oldDisk.size):
                #変更が有れば更新
                self.client.editVolume(vm, disk)
            #いずれにしても処理終了
            return

        #イベントログ出力
        tableCPNT = self.conn.getTable("COMPONENT")
        component = self.conn.selectOne(tableCPNT.select(tableCPNT.c.COMPONENT_NO==disk["COMPONENT_NO"]))
        componentName = None
        if component:
            componentName = component["COMPONENT_NAME"]
        tableINS = self.conn.getTable("INSTANCE")
        instance = self.conn.selectOne(tableINS.select(tableINS.c.INSTANCE_NO==vcInstance["INSTANCE_NO"]))
        self.conn.debug(instance["FARM_NO"], disk["COMPONENT_NO"], componentName, vcInstance["INSTANCE_NO"], instance["INSTANCE_NAME"],
                         "VCloudDiskAttach",[instance["INSTANCE_NAME"], disk["DISK_ID"], disk["SIZE"]])

        # ボリュームのアタッチ
        pccdisk = self.client.attachVolume(vm, disk)

        #イベントログ出力
        self.conn.debug(instance["FARM_NO"], disk["COMPONENT_NO"], componentName, vcInstance["INSTANCE_NO"], instance["INSTANCE_NAME"],
                         "VCloudDiskAttachFinish",[instance["INSTANCE_NAME"], disk["DISK_ID"], disk["SIZE"]])

        # データベースの更新
        table = self.conn.getTable("VCLOUD_DISK")
        updateDict = self.conn.selectOne(table.select(table.c.DISK_NO==disk["DISK_NO"]))
        updateDict["DISK_ID"] = pccdisk.name
        updateDict["ATTACHED"] = True
        updateDict["UNIT_NO"] = pccdisk.unitNo
        sql = table.update(table.c.DISK_NO ==updateDict["DISK_NO"], values=updateDict)
        self.conn.execute(sql)
    def checkAvailableAddress(self, instanceNo, addressNo) :
        table = self.conn.getTable("AWS_ADDRESS")
        awsAddress = self.conn.selectOne(table.select(table.c.ADDRESS_NO==addressNo))
        publicIp = awsAddress["PUBLIC_IP"]

        address = self.client.describeAddress(publicIp);
        if isNotEmpty(address.instanceId):
            # アドレスが何らかのインスタンスに関連付けられている場合
            raise IaasException("EPROCESS-000119", [publicIp, address.instanceId,])
    def stopInstance(self, instanceNo):

        try :
            # アドレスに関する処理
            self.addresscontroller.stopAddress(instanceNo)
        except Exception:
            self.logger.error(traceback.format_exc())

        try :
            # インスタンスに関する処理
            self.instancecontroller.stopInstance(instanceNo);
        except Exception:
            self.logger.error(traceback.format_exc())

        try :
            # ボリュームに関する処理
            tableAWSVOL = self.conn.getTable("AWS_VOLUME")
            volumes = self.conn.select(tableAWSVOL.select(tableAWSVOL.c.INSTANCE_NO==instanceNo))

            #PCC_INSTANCE 取得
            tableINS = self.conn.getTable("INSTANCE")
            pccInstance = self.conn.selectOne(tableINS.select(tableINS.c.INSTANCE_NO==instanceNo))

            #イメージの取得  再考の余地あり
            image = getImage(pccInstance["IMAGE_NO"])

            for awsVolume in volumes:
                if (image["ebsImage"]=="true"):
                    self.volumecontroller.stopVolume(instanceNo, awsVolume["VOLUME_NO"])
                else:
                    if (isNotEmpty(awsVolume["VOLUME_ID"]) and isNotEmpty(awsVolume["INSTANCE_ID"])):
                        updateDict = self.conn.selectOne(tableAWSVOL.select(tableAWSVOL.c.VOLUME_NO==awsVolume["VOLUME_NO"]))
                        updateDict["STATUS"] = None
                        updateDict["INSTANCE_ID"] = None
                        sql = tableAWSVOL.update(tableAWSVOL.c.VOLUME_NO ==updateDict["VOLUME_NO"], values=updateDict)
                        self.conn.execute(sql)
        except Exception:
            self.logger.error(traceback.format_exc())

        self.conn.commit()
        return "RESULT:TRUE"
Esempio n. 11
0
    def checkAvailableAddress(self, instanceNo, addressNo):
        table = self.conn.getTable("AWS_ADDRESS")
        awsAddress = self.conn.selectOne(
            table.select(table.c.ADDRESS_NO == addressNo))
        publicIp = awsAddress["PUBLIC_IP"]

        address = self.client.describeAddress(publicIp)
        if isNotEmpty(address.instanceId):
            # アドレスが何らかのインスタンスに関連付けられている場合
            raise IaasException("EPROCESS-000119", [
                publicIp,
                address.instanceId,
            ])
Esempio n. 12
0
    def makeUserData(self, map):
        if not map or len(map) == 0:
            return None

        userdata = ''
        for key in map.keys():
            value = map[key]
            if isNotEmpty(value):
                if userdata != '':
                    userdata = userdata + ';'

                userdata = userdata + key + "=" + value

        return userdata
    def configureHealthCheck(self, farmNo, loadBalancerNo) :
        tableLBHC = self.conn.getTable("LOAD_BALANCER_HEALTH_CHECK")
        healthCheck = self.conn.selectOne(tableLBHC.select(tableLBHC.c.LOAD_BALANCER_NO==loadBalancerNo))

        # ヘルスチェック情報がない場合はスキップ
        if not healthCheck :
            return

        # 現在のヘルスチェック設定を取得
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        # ロードバランサ名
        loadBalancerName = awsLoadBalancer["NAME"]

        #loadBalancerDescriptions = self.client.describeLoadBalancer(loadBalancerName)
        #description = loadBalancerDescriptions[0]

        description =LoadBalancerDescription(None, None , None, None, None, None, HealthCheck(None, 1, 2, 3, 4), None, None, None, None, None )

        # ヘルスチェック設定を作成
        target = str(healthCheck["CHECK_PROTOCOL"]) + ":" + str(healthCheck["CHECK_PORT"])
        if (isNotEmpty(healthCheck["CHECK_PATH"])) :
            if healthCheck["CHECK_PATH"].startswith('/') == False:
                target = target + "/"

            target = target + healthCheck["CHECK_PATH"]

        healthCheck2 = HealthCheck(
                    healthCheck["HEALTHY_THRESHOLD"],
                    healthCheck["CHECK_INTERVAL"],
                    target,
                    healthCheck["CHECK_TIMEOUT"],
                    healthCheck["UNHEALTHY_THRESHOLD"])

        # ヘルスチェック設定に変更がない場合はスキップ
        if ((healthCheck2.target == description.healthCheck.target)
            and (healthCheck2.timeout == description.healthCheck.timeout)
            and (healthCheck2.interval == description.healthCheck.interval)
            and (healthCheck2.healthyThreshold == description.healthCheck.healthyThreshold)
            and (healthCheck2.unhealthyThreshold == description.healthCheck.unhealthyThreshold)) :
            return

        # ヘルスチェック設定を変更
        self.client.configureHealthCheck(healthCheck2, loadBalancerName);

        #実行ログ
        self.logger.info(None ,"IPROCESS-200131", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbHealthCheckConfig", ["EC2", loadBalancerName,] )
    def configureHealthCheck(self, farmNo, loadBalancerNo) :
        tableLBHC = self.conn.getTable("LOAD_BALANCER_HEALTH_CHECK")
        healthCheck = self.conn.selectOne(tableLBHC.select(tableLBHC.c.LOAD_BALANCER_NO==loadBalancerNo))

        # ヘルスチェック情報がない場合はスキップ
        if not healthCheck :
            return

        # 現在のヘルスチェック設定を取得
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        # ロードバランサ名
        loadBalancerName = awsLoadBalancer["NAME"]

        #loadBalancerDescriptions = self.client.describeLoadBalancer(loadBalancerName)
        #description = loadBalancerDescriptions[0]

        description =LoadBalancerDescription(None, None , None, None, None, None, HealthCheck(None, 1, 2, 3, 4), None, None, None, None, None )

        # ヘルスチェック設定を作成
        target = str(healthCheck["CHECK_PROTOCOL"]) + ":" + str(healthCheck["CHECK_PORT"])
        if (isNotEmpty(healthCheck["CHECK_PATH"])) :
            if healthCheck["CHECK_PATH"].startswith('/') == False:
                target = target + "/"

            target = target + healthCheck["CHECK_PATH"]

        healthCheck2 = HealthCheck(
                    healthCheck["HEALTHY_THRESHOLD"],
                    healthCheck["CHECK_INTERVAL"],
                    target,
                    healthCheck["CHECK_TIMEOUT"],
                    healthCheck["UNHEALTHY_THRESHOLD"])

        # ヘルスチェック設定に変更がない場合はスキップ
        if ((healthCheck2.target == description.healthCheck.target)
            and (healthCheck2.timeout == description.healthCheck.timeout)
            and (healthCheck2.interval == description.healthCheck.interval)
            and (healthCheck2.healthyThreshold == description.healthCheck.healthyThreshold)
            and (healthCheck2.unhealthyThreshold == description.healthCheck.unhealthyThreshold)) :
            return

        # ヘルスチェック設定を変更
        self.client.configureHealthCheck(healthCheck2, loadBalancerName);

        #実行ログ
        self.logger.info(None ,"IPROCESS-200131", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbHealthCheckConfig", ["EC2", loadBalancerName,] )
    def makeUserData(self, map):
        if not map or len(map) == 0:
            return None

        userdata = ''
        for key in map.keys():
            value = map[key]
            if isNotEmpty(value):
                if userdata != '':
                    userdata = userdata + ';'

                userdata = userdata + key + "=" + value

        return userdata
    def startListener(self, farmNo, loadBalancerNo, loadBalancerPort) :
        table = self.conn.getTable("LOAD_BALANCER_LISTENER")
        listener = self.conn.selectOne(table.select(and_(table.c.LOAD_BALANCER_NO==loadBalancerNo, table.c.LOAD_BALANCER_PORT ==loadBalancerPort)))

        try :
            # リスナー作成情報
            tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
            awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))

            sslKey = None

            if (isNotEmpty(listener["SSL_KEY_NO"])):
                # リスナー作成情報
                tableAWSSSL = self.conn.getTable("AWS_SSL_KEY")
                awsSslKey = self.conn.selectOne(tableAWSSSL.select(tableAWSSSL.c.KEY_NO==listener["SSL_KEY_NO"]))
                sslKey = awsSslKey["SSLCERTIFICATEID"]

            # ロードバランサ名
            loadBalancerName = awsLoadBalancer["NAME"]

            # リスナーの設定  instancePort, instanceProtocol, loadBalancerPort, protocol, sslCertificateId
            listeners = [ Listener(listener["SERVICE_PORT"], None, listener["LOAD_BALANCER_PORT"], listener["PROTOCOL"], sslKey),]

            # リスナーの作成
            self.client.createLoadBalancerListeners(listeners, loadBalancerName)

            #実行ログ
            self.logger.info(None ,"IPROCESS-200121", [awsLoadBalancer["NAME"], listener["LOAD_BALANCER_PORT"]])

            # イベントログ出力
            self.conn.debug(farmNo, None, None, None, None, "AwsElbListenerCreate", ["EC2", loadBalancerName, listener["LOAD_BALANCER_PORT"]] )

        except Exception:
            self.logger.error(traceback.format_exc())
            # ステータスを更新
            tableLBL = self.conn.getTable("LOAD_BALANCER_LISTENER")
            updateDict = self.conn.selectOne(tableLBL.select(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort)))
            updateDict["STATUS"] = self.WARNING
            sql = tableLBL.update(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort), values=updateDict)
            self.conn.execute(sql)
            raise


        # ステータスを更新
        tableLBL = self.conn.getTable("LOAD_BALANCER_LISTENER")
        updateDict = self.conn.selectOne(table.select(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort)))
        updateDict["STATUS"] = self.RUNNING
        sql = tableLBL.update(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort), values=updateDict)
        self.conn.execute(sql)
    def startListener(self, farmNo, loadBalancerNo, loadBalancerPort) :
        table = self.conn.getTable("LOAD_BALANCER_LISTENER")
        listener = self.conn.selectOne(table.select(and_(table.c.LOAD_BALANCER_NO==loadBalancerNo, table.c.LOAD_BALANCER_PORT ==loadBalancerPort)))

        try :
            # リスナー作成情報
            tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
            awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))

            sslKey = None

            if (isNotEmpty(listener["SSL_KEY_NO"])):
                # リスナー作成情報
                tableAWSSSL = self.conn.getTable("AWS_SSL_KEY")
                awsSslKey = self.conn.selectOne(tableAWSSSL.select(tableAWSSSL.c.KEY_NO==listener["SSL_KEY_NO"]))
                sslKey = awsSslKey["SSLCERTIFICATEID"]

            # ロードバランサ名
            loadBalancerName = awsLoadBalancer["NAME"]

            # リスナーの設定  instancePort, instanceProtocol, loadBalancerPort, protocol, sslCertificateId
            listeners = [ Listener(listener["SERVICE_PORT"], None, listener["LOAD_BALANCER_PORT"], listener["PROTOCOL"], sslKey),]

            # リスナーの作成
            self.client.createLoadBalancerListeners(listeners, loadBalancerName)

            # 実行ログ
            self.logger.info(None ,"IPROCESS-200121", [awsLoadBalancer["NAME"], listener["LOAD_BALANCER_PORT"]])

            # イベントログ出力
            self.conn.debug(farmNo, None, None, None, None, "AwsElbListenerCreate", ["EC2", loadBalancerName, listener["LOAD_BALANCER_PORT"]] )

        except Exception:
            self.logger.error(traceback.format_exc())
            # ステータスを更新
            tableLBL = self.conn.getTable("LOAD_BALANCER_LISTENER")
            updateDict = self.conn.selectOne(tableLBL.select(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort)))
            updateDict["STATUS"] = self.WARNING
            sql = tableLBL.update(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort), values=updateDict)
            self.conn.execute(sql)
            raise


        # ステータスを更新
        tableLBL = self.conn.getTable("LOAD_BALANCER_LISTENER")
        updateDict = self.conn.selectOne(table.select(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort)))
        updateDict["STATUS"] = self.RUNNING
        sql = tableLBL.update(and_(tableLBL.c.LOAD_BALANCER_NO==loadBalancerNo, tableLBL.c.LOAD_BALANCER_PORT ==loadBalancerPort), values=updateDict)
        self.conn.execute(sql)
Esempio n. 18
0
    def createDnsUserData(self, instanceNo):
        # UserDataを作成
        userData = {}
        # Primary DNSサーバ
        userData.update({"dns": getDnsProperty("dns.server")})

        # Secondry DNSサーバ
        dns2 = getDnsProperty("dns.server2")
        if (isNotEmpty(dns2)):
            userData.update({"dns2": dns2})

        # DNSドメイン
        userData.update({"dnsdomain": getDnsProperty("dns.domain")})

        return userData
    def  createDnsUserData(self,instanceNo):
        # UserDataを作成
        userData = {}
        # Primary DNSサーバ
        userData.update({"dns": getDnsProperty("dns.server")})

        # Secondry DNSサーバ
        dns2 = getDnsProperty("dns.server2")
        if (isNotEmpty(dns2)):
            userData.update({"dns2": dns2})

        # DNSドメイン
        userData.update({"dnsdomain": getDnsProperty("dns.domain")})

        return userData;
    def startVolume(self, instanceNo, volumeNo):
        table = self.conn.getTable('AZURE_DISK')
        volume = self.conn.selectOne(table.select(table.c.DISK_NO == volumeNo))

        # インスタンス名がある場合はスキップ
        if (isNotEmpty(volume['INSTANCE_NAME'])):
            return

        if (isEmpty(volume['DISK_NAME'])):
            # ボリューム名がない場合は新規作成
            self._createAttachVolume(instanceNo, volumeNo)
        else:
            # ボリューム名がある場合は既存のデータディスクをアタッチ
            self._attachVolume(instanceNo, volumeNo)

        return
    def startVolume(self, instanceNo, volumeNo) :
        table = self.conn.getTable('AZURE_DISK')
        volume = self.conn.selectOne(table.select(table.c.DISK_NO==volumeNo))

        # インスタンス名がある場合はスキップ
        if (isNotEmpty(volume['INSTANCE_NAME'])) :
            return

        if (isEmpty(volume['DISK_NAME'])) :
            # ボリューム名がない場合は新規作成
            self._createAttachVolume(instanceNo, volumeNo)
        else:
            # ボリューム名がある場合は既存のデータディスクをアタッチ
            self._attachVolume(instanceNo, volumeNo)

        return
Esempio n. 22
0
    def startVolume(self, instanceNo, volumeNo) :
        table = self.conn.getTable("CLOUDSTACK_VOLUME")
        volume = self.conn.selectOne(table.select(table.c.VOLUME_NO==volumeNo))

        # インスタンスIDがある場合はスキップ
        if (isNotEmpty(volume["INSTANCE_ID"])) :
            return

        if (isEmpty(volume["VOLUME_ID"])) :
            # ボリュームIDがない場合は新規作成
            self.createVolume(instanceNo, volumeNo)

        # ボリュームのアタッチ
        self.attachVolume(instanceNo, volumeNo)
        #ディスク認識の為リブート
        ##self.rebootInstance(instanceNo)
        #起動スクリプトを待つ
        time.sleep(10)
    def startVolume(self, instanceNo, volumeNo) :
        table = self.conn.getTable("CLOUDSTACK_VOLUME")
        volume = self.conn.selectOne(table.select(table.c.VOLUME_NO==volumeNo))

        # インスタンスIDがある場合はスキップ
        if (isNotEmpty(volume["INSTANCE_ID"])) :
            return

        if (isEmpty(volume["VOLUME_ID"])) :
            # ボリュームIDがない場合は新規作成
            self.createVolume(instanceNo, volumeNo)

        # ボリュームのアタッチ
        self.attachVolume(instanceNo, volumeNo)
        #ディスク認識の為リブート
        ##self.rebootInstance(instanceNo)
        #起動スクリプトを待つ
        time.sleep(10)
Esempio n. 24
0
    def startAddress(self, instanceNo):
        # アドレス情報の取得
        awsAddress = self.getAwsAddress(instanceNo)
        if not awsAddress:
            # アドレス情報がない場合は終了
            return

        if isNotEmpty(awsAddress["INSTANCE_ID"]):
            # インスタンスIDがある場合はスキップ
            return

        addressNo = awsAddress["ADDRESS_NO"]

        # アドレスのステータスチェック
        self.checkAvailableAddress(instanceNo, addressNo)

        # アドレスの関連付け
        self.associateAddress(instanceNo, addressNo)
    def startAddress(self, instanceNo) :
        # アドレス情報の取得
        awsAddress = self.getAwsAddress(instanceNo);
        if not awsAddress:
            # アドレス情報がない場合は終了
            return

        if isNotEmpty(awsAddress["INSTANCE_ID"]) :
            # インスタンスIDがある場合はスキップ
            return

        addressNo = awsAddress["ADDRESS_NO"]

        # アドレスのステータスチェック
        self.checkAvailableAddress(instanceNo, addressNo)

        # アドレスの関連付け
        self.associateAddress(instanceNo, addressNo)
    def startInstance(self, instanceNo):
        try:
            self.instancecontroller.startInstance(instanceNo)
        except Exception:
            self.logger.error(traceback.format_exc())
            raise

        # ボリュームに関する処理
        table = self.conn.getTable("OPENSTACK_VOLUME")
        volumes = self.conn.select(table.select(table.c.INSTANCE_NO==instanceNo))
        for volume in volumes:
            if isNotEmpty(volume["COMPONENT_NO"]):
                # コンポーネント番号がある場合はスキップ
                continue
            #Volumeスタート
            self.volumecontroller.startVolume(instanceNo, volume["VOLUME_NO"])

        self.conn.commit()
        return True
Esempio n. 27
0
    def startInstance(self, instanceNo):
        try:
            self.instancecontroller.startInstance(instanceNo)
        except Exception:
            self.logger.error(traceback.format_exc())
            raise

        # ボリュームに関する処理
        table = self.conn.getTable("OPENSTACK_VOLUME")
        volumes = self.conn.select(
            table.select(table.c.INSTANCE_NO == instanceNo))
        for volume in volumes:
            if isNotEmpty(volume["COMPONENT_NO"]):
                # コンポーネント番号がある場合はスキップ
                continue
            #Volumeスタート
            self.volumecontroller.startVolume(instanceNo, volume["VOLUME_NO"])

        self.conn.commit()
        return True
Esempio n. 28
0
    def startVolume(self, instanceNo, volumeNo) :
        table = self.conn.getTable("OPENSTACK_VOLUME")
        volume = self.conn.selectOne(table.select(table.c.VOLUME_NO==volumeNo))

        # インスタンスIDがある場合はスキップ
        if (isNotEmpty(volume["INSTANCE_ID"])) :
            return

        if (isEmpty(volume["VOLUME_ID"])) :
            # ボリュームIDがない場合は新規作成
            self.createVolume(instanceNo, volumeNo)

            # ボリュームの作成待ち
            self.waitCreateVolume(instanceNo, volumeNo)

        # ボリュームのアタッチ
        self.attachVolume(instanceNo, volumeNo)

        # ボリュームのアタッチ待ち
        self.waitAttachVolume(instanceNo, volumeNo)
    def startInstance(self, instanceNo):

        # インスタンスに関する処理   TODO タイムアウトリトライは未実装
        try:
            self.instancecontroller.startInstance(instanceNo)
        except Exception:
            self.logger.error(traceback.format_exc())
            raise

        # ボリュームに関する処理
        table = self.conn.getTable("AWS_VOLUME")
        volumes = self.conn.select(table.select(table.c.INSTANCE_NO==instanceNo))
        for volume in volumes:
            if isNotEmpty(volume["COMPONENT_NO"]):
                # コンポーネント番号がある場合はスキップ
                continue
            #Volumeスタート
            self.volumecontroller.startVolume(instanceNo, volume["VOLUME_NO"])

        # アドレスに関する処理
        self.addresscontroller.startAddress(instanceNo)

        self.conn.commit()
        return "RESULT:TRUE"
Esempio n. 30
0
    def run(self, instanceNo, csInstance, pccInstance, image):

        #serviceoffering名称をIDへ変換
        serviceofferings = self.client.describeServiceOfferings()
        #デフォルトは最初にHitするID
        serviceofferingid = serviceofferings[0]["id"]
        for serviceoffering in serviceofferings:
            if csInstance["INSTANCE_TYPE"] == serviceoffering["name"]:
                serviceofferingid = serviceoffering["id"]


        availabilityZone = None
        if (isNotEmpty(csInstance["ZONEID"])):
            availabilityZone = csInstance["ZONEID"]

        #任意設定はここから  必要な分増やす
        extra_args = {}
        if (isNotEmpty(csInstance["NETWORKID"])):
            extra_args["network_id"] = csInstance["NETWORKID"]

        #SecurityGroup
        securityGroups = []
        if (isNotEmpty(csInstance["SECURITYGROUP"])):
            securityGroups.append(csInstance["SECURITYGROUP"].split(","))
            extra_args["securitygroupnames"] = securityGroups

        if (isNotEmpty(csInstance["KEY_NAME"])):
            extra_args["keypair"] = csInstance["KEY_NAME"]

        #UserDataを作成
        userData = self.createUserData(instanceNo, pccInstance, csInstance)
        userData = self.makeUserData(userData)
        extra_args["userdata"] = userData
        self.logger.info("userData:"+userData)


        #イベントログ出力
        self.conn.debug(pccInstance["FARM_NO"], None, None, instanceNo, pccInstance["INSTANCE_NAME"], "CloudStackInstanceCreate",["CLOUDSTACK"])

        #インスタンスの作成
        node = self.client.runInstances(pccInstance["INSTANCE_NAME"],
                                             pccInstance["FQDN"],
                                             serviceofferingid,
                                             image["templateId"],
                                             availabilityZone,
                                             **extra_args)



        if node["state"] != "Running":
            # インスタンス作成失敗時
            raise IaasException("EPROCESS-000716", [node["id"], node["state"]])

        # ログ出力
        self.logger.info(None, "IPROCESS-100603", [node["id"],])

        # イベントログ出力
        self.conn.debug(pccInstance["FARM_NO"], None, None, instanceNo, pccInstance["INSTANCE_NAME"], "CloudStackInstanceCreateFinish",["CLOUDSTACK", node["id"]])

        # データベース更新
        table = self.conn.getTable("CLOUDSTACK_INSTANCE")
        updateDict = self.conn.selectOne(table.select(table.c.INSTANCE_NO==instanceNo))
        updateDict["INSTANCE_ID"] = node["id"]
        updateDict["ZONEID"] = node["zoneid"]
        updateDict["STATE"] = node["state"]
        updateDict["DISPLAYNAME"] = node["displayname"]
        updateDict["IPADDRESS"] = node["nic"][0]["ipaddress"]
        sql = table.update(table.c.INSTANCE_NO ==updateDict["INSTANCE_NO"], values=updateDict)
        self.conn.execute(sql)
    def _change_vm_nw(self, vm_id, vm_nw):
        rasd_ns = "{http://www.vmware.com/vcloud/v1.5}"

        indexList = ["0","1","2","3","4","5","6","7","8","9","10",]

        #リストを名称キーのマップへ変換
        editmap = {}
        makemap = {}
        for nw in vm_nw:
            if nw["NETWORK_INDEX"] is not None:
                editmap[str(nw["NETWORK_INDEX"])] = nw
            else:
                makemap[str(nw["NETWORK_NO"])] = nw

        isEdit = False
        vms = self._get_vm_elements(vm_id)
        for vm in vms:
            res = self.requestLoop('%s/networkConnectionSection' % get_url_path(vm.get('href')))
            def_primary_index = res.object.find(fixxpath(res.object, 'PrimaryNetworkConnectionIndex')).text
            primary_index = def_primary_index
            net_conns = res.object.findall(fixxpath(res.object, 'NetworkConnection'))
            for item in net_conns:
                name = item.get('network')
                index = item.find(fixxpath(item, 'NetworkConnectionIndex')).text
                #対象の設定を取得
                if not editmap.has_key(index):
                    #取得できなければこのNWは削除
                    res.object.remove(item)
                    isEdit = True
                else:
                    #利用済インデックスをリストから削除
                    indexList.remove(index)
                    #取得できれば設定を比較
                    newNw = editmap.pop(index)

                    #Primary チェック
                    if isBit(newNw["IS_PRIMARY"]):
                        primary_index = newNw["NETWORK_INDEX"]

                    #IPMODE
                    if newNw["IP_MODE"] != item.find(fixxpath(item, 'IpAddressAllocationMode')).text:
                        item.find(fixxpath(item, 'IpAddressAllocationMode')).text = newNw["IP_MODE"]
                        isEdit = True
                        if newNw["IP_MODE"] == "MANUAL":
                            #設定「MANUAL」の場合はアドレスも変更する
                            item.find(fixxpath(item, 'IpAddress')).text = newNw["IP_ADDRESS"]
                    else:
                        if newNw["IP_ADDRESS"] != item.find(fixxpath(item, 'IpAddress')).text:
                            #IPアドレスのみ変更する場合
                            item.find(fixxpath(item, 'IpAddress')).text = newNw["IP_ADDRESS"]
                            isEdit = True

            #邪魔なのでLinkタグを消す
            link = res.object.find(fixxpath(res.object, 'Link'))
            res.object.remove(link)

            #追加ネットワークの登録
            if len(makemap) > 0:
                for key in makemap:
                    newNw = makemap[key]
                    networkConnection = ET.Element('%sNetworkConnection' % rasd_ns,
                                              {'network': newNw["NETWORK_NAME"]}
                                            )
                    ET.SubElement(networkConnection, '%sNetworkConnectionIndex' % rasd_ns).text = str(indexList[0])

                    #Primary チェック
                    if isBit(newNw["IS_PRIMARY"]):
                        primary_index = indexList[0]

                    if isNotEmpty(newNw["IP_ADDRESS"]):
                        ET.SubElement(networkConnection, '%sIpAddress' % rasd_ns).text = newNw["IP_ADDRESS"]
                    ET.SubElement(networkConnection, '%sIsConnected' % rasd_ns).text = "true"
                    ET.SubElement(networkConnection, '%sIpAddressAllocationMode' % rasd_ns).text = newNw["IP_MODE"]

                    res.object.append(networkConnection)
                    isEdit  = True
                    indexList.remove(indexList[0])


            if str(def_primary_index) != str(primary_index):
                #プライマリの再設定
                res.object.find(fixxpath(res.object, 'PrimaryNetworkConnectionIndex')).text = str(primary_index)
                isEdit  = True

            #取っ払ったLinkを戻す
            res.object.append(link)
            self.logger.info(ET.tostring(res.object))
            #変更を行った場合のみ通信する
            if isEdit:
                self.logger.info(ET.tostring(res.object))
                res = self.requestLoop(
                    '%s/networkConnectionSection' % get_url_path(vm.get('href')),
                    data=ET.tostring(res.object),
                    method='PUT',
                    headers={'Content-Type': 'application/vnd.vmware.vcloud.networkConnectionSection+xml'}
                )
                self._wait_for_task_completion(res.object.get('href'))
    def _add_vm_item(self, parent):
        sourcedItem = ET.SubElement(parent, "SourcedItem",
                                    {'sourceDelete': 'false'})
        ET.SubElement(sourcedItem, "Source", {
            'href': self.image,
            'name': self.vm_name
        })

        instantionation_params = ET.SubElement(sourcedItem,
                                               "InstantiationParams")
        network_connection_section = ET.SubElement(
            instantionation_params, "NetworkConnectionSection", {
                'xmlns': "http://www.vmware.com/vcloud/v1.5",
                'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"
            })
        ET.SubElement(network_connection_section, "Info",
                      {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"})

        #散りあえずプライマリーは0
        primary_xml = ET.SubElement(network_connection_section,
                                    'PrimaryNetworkConnectionIndex')
        primary_xml.text = "0"

        netIndex = 0
        p_index = 0
        for vm_network in self.vm_networks:
            networkConnection = ET.SubElement(network_connection_section,
                                              'NetworkConnection',
                                              {'network': vm_network.name})
            ET.SubElement(networkConnection,
                          'NetworkConnectionIndex').text = str(netIndex)
            if isNotEmpty(vm_network.ipAddress):
                ET.SubElement(networkConnection,
                              'IpAddress').text = vm_network.ipAddress
            ET.SubElement(networkConnection, 'IsConnected').text = "true"
            ET.SubElement(networkConnection,
                          'IpAddressAllocationMode').text = vm_network.ipMode
            #プライマリかどうか
            if vm_network.isPrimary:
                p_index = netIndex

            netIndex = netIndex + 1

        #プライマリを指定のものへ変更
        primary_xml.text = str(p_index)

        guest_customization_section = ET.SubElement(
            instantionation_params, "GuestCustomizationSection", {
                'xmlns': "http://www.vmware.com/vcloud/v1.5",
                'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"
            })
        ET.SubElement(guest_customization_section, "Info",
                      {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"})
        ET.SubElement(guest_customization_section, 'Enabled').text = "true"
        ET.SubElement(guest_customization_section,
                      'ComputerName').text = self.vm_name

        ET.SubElement(sourcedItem, "StorageProfile", {
            'href': self.vm_storage.href,
            'name': self.vm_storage.name
        })
Esempio n. 33
0
    def run(self, instanceNo, awsInstance, pccInstance, image):
        #UserDataを作成
        userData = self.createUserData(instanceNo, pccInstance, awsInstance)
        userData = self.makeUserData(userData)

        self.logger.info("userData:" + userData)

        #サブネット
        subnet = None
        if (isNotEmpty(awsInstance["SUBNET_ID"])):
            subnet = self.client.describeSubnets(awsInstance["SUBNET_ID"])[0]

        groupmap = {}
        groups = self.client.describeSecurityGroups()
        for group in groups:
            #サブネット入力時はVPCIDが一致する物をマッピング
            if subnet is not None:
                if subnet.vpcId == group.vpcId:
                    groupmap.update({group.groupName: group.groupId})

        #SecurityGroup
        securityGroups = []
        if (isNotEmpty(awsInstance["SECURITY_GROUPS"])):
            securityGroups = awsInstance["SECURITY_GROUPS"].split(",")

        availabilityZone = None
        if (isNotEmpty(awsInstance["AVAILABILITY_ZONE"])):
            availabilityZone = awsInstance["AVAILABILITY_ZONE"]

        blockDeviceMappings = self.createBlockDeviceMappings(
            image["imageId"], awsInstance["INSTANCE_TYPE"])

        #イベントログ出力
        self.conn.debug(pccInstance["FARM_NO"], None, None, instanceNo,
                        pccInstance["INSTANCE_NAME"], "AwsInstanceCreate",
                        ["EC2"])

        #インスタンスの作成
        instance2 = self.client.runInstances(
            groupmap=groupmap,
            imageId=image["imageId"],
            kernelId=image["kernelId"],
            ramdiskId=image["ramdiskId"],
            keyName=awsInstance["KEY_NAME"],
            instanceType=awsInstance["INSTANCE_TYPE"],
            securityGroup=securityGroups,
            location=availabilityZone,
            userData=userData,
            subnetId=awsInstance["SUBNET_ID"],
            privateIpAddress=awsInstance["PRIVATE_IP_ADDRESS"],
            blockDeviceMapping=blockDeviceMappings)

        #データベース更新
        table = self.conn.getTable("AWS_INSTANCE")
        updateDict = self.conn.selectOne(
            table.select(table.c.INSTANCE_NO == instanceNo))
        updateDict["INSTANCE_ID"] = instance2.id
        updateDict["STATUS"] = instance2.extra['status']
        sql = table.update(table.c.INSTANCE_NO == updateDict["INSTANCE_NO"],
                           values=updateDict)
        self.conn.execute(sql)
    def _add_vm_item(self, parent):
        sourcedItem = ET.SubElement(parent,
                                    "SourcedItem",
                                    {'sourceDelete':'false'}
        )
        ET.SubElement(
            sourcedItem,
            "Source",
            {'href': self.image,
             'name': self.vm_name}
        )

        instantionation_params = ET.SubElement(sourcedItem, "InstantiationParams")
        network_connection_section = ET.SubElement(instantionation_params,
                                                   "NetworkConnectionSection",
                                                   {'xmlns': "http://www.vmware.com/vcloud/v1.5",
                                                    'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"}
        )
        ET.SubElement(
            network_connection_section,
            "Info",
            {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"}
        )

        #散りあえずプライマリーは0
        primary_xml =  ET.SubElement(network_connection_section, 'PrimaryNetworkConnectionIndex')
        primary_xml.text = "0"

        netIndex = 0
        p_index = 0
        for vm_network in self.vm_networks:
            networkConnection = ET.SubElement(network_connection_section,
                                              'NetworkConnection',
                                              {'network': vm_network.name}
            )
            ET.SubElement(networkConnection, 'NetworkConnectionIndex').text = str(netIndex)
            if isNotEmpty(vm_network.ipAddress):
                ET.SubElement(networkConnection, 'IpAddress').text = vm_network.ipAddress
            ET.SubElement(networkConnection, 'IsConnected').text = "true"
            ET.SubElement(networkConnection, 'IpAddressAllocationMode').text = vm_network.ipMode
            #プライマリかどうか
            if vm_network.isPrimary:
                p_index = netIndex

            netIndex = netIndex + 1

        #プライマリを指定のものへ変更
        primary_xml.text = str(p_index)

        guest_customization_section = ET.SubElement(instantionation_params,
                                                   "GuestCustomizationSection",
                                                   {'xmlns': "http://www.vmware.com/vcloud/v1.5",
                                                    'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"}
        )
        ET.SubElement(
            guest_customization_section,
            "Info",
            {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"}
        )
        ET.SubElement(guest_customization_section, 'Enabled').text = "true"
        ET.SubElement(guest_customization_section, 'ComputerName').text = self.vm_name

        ET.SubElement(
            sourcedItem,
            "StorageProfile",
            {'href': self.vm_storage.href,
             'name': self.vm_storage.name}
        )
class CloudStackController(IaasController):

    logger = IaasLogger()

    conn = None
    client = None
    accessInfo = None

    instancecontroller = None
    volumecontroller = None
    addresscontroller = None
    loadBalancercontroller = None
    othercontroller = None

    def __init__(self, conn, accessInfo, platforminfo):
        self.conn = conn
        self.accessInfo = accessInfo

        self.client = CloudStackIaasClient(platforminfo, accessInfo["USER_NAME"], accessInfo["ACCESS_ID"], accessInfo["SECRET_KEY"])
        #コントローラ作成
        self.instancecontroller      = CloudStackInstanceController(platforminfo, self.client, self.conn)
        self.volumecontroller        = CloudStackVolumController(platforminfo, self.client, self.conn)
        self.addresscontroller       = CloudStackAddressController(platforminfo, self.client, self.conn)
        self.loadBalancercontroller  = CloudStackLoadBalancercontroller(platforminfo, self.client, self.conn)
        self.othercontroller         = CloudStackOtherController(platforminfo, self.client, self.conn)

    def __del__(self):
        self.conn.rollback()
        self.conn.close()

    def describeDiskOfferings(self):
        return self.client.describeDiskOfferings()

    def describePublicIpAddresses(self, id):
        return self.client.describePublicIpAddresses(id)

    def describeOnlyInstances(self):
        return self.client.describeOnlyInstances()

    def describeServiceOfferings(self):
        return self.client.describeServiceOfferings()


    def describeImages(self):
        return self.client.describeImages()

    def describeInstances(self):
        return self.client.describeInstances()


    def startInstance(self, instanceNo):

        # インスタンスに関する処理   TODO タイムアウトリトライは未実装
        try:
            self.instancecontroller.startInstance(instanceNo)
        except Exception, e:
            self.logger.error(traceback.format_exc())
            raise

        # ボリュームに関する処理
        table = self.conn.getTable("CLOUDSTACK_VOLUME")
        volumes = self.conn.select(table.select(table.c.INSTANCE_NO==instanceNo))
        for volume in volumes:
            if isNotEmpty(volume["COMPONENT_NO"]):
                # コンポーネント番号がある場合はスキップ
                continue
            #Volumeスタート
            self.volumecontroller.startVolume(instanceNo, volume["VOLUME_NO"])

        # アドレスに関する処理
        self.addresscontroller.startAddress(instanceNo)

        self.conn.commit()
        return True
Esempio n. 36
0
 def makeMassage(self, str=None, messid=None, *args):
     if isNotEmpty(str):
         return str
     else:
         return getMassage(messid, *args)
    def createLoadBalancer(self, farmNo, loadBalancerNo, availabilityZones, subnets, groupmap) :
        tableAWSLB = self.conn.getTable("AWS_LOAD_BALANCER")
        awsLoadBalancer = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))

        # ロードバランサ作成情報
        loadBalancerName = awsLoadBalancer["NAME"]

        # 内部ロードバランサ
        internal = awsLoadBalancer["INTERNAL"]

        # デフォルトゾーンの特定 デフォルト1件目
        availabilityZone = None
        for zone in availabilityZones:
            availabilityZone = zone.name

        #セキュリティグループ
        securityGroups = []
        if (isNotEmpty(awsLoadBalancer["SECURITY_GROUPS"])):
            securityGroups = awsLoadBalancer["SECURITY_GROUPS"].split(",")

        #サブネットID
        subnetIds = []
        if (isNotEmpty(awsLoadBalancer["SUBNET_ID"])):
            subnetIds = awsLoadBalancer["SUBNET_ID"].split(",")

        # サブネット(VPC)との関係からセキュリティグループIDを取得
        securityGroupIds = []
        if len(subnetIds) != 0:
            for subnet in subnets:
                if subnetIds[0] == subnet.subnetId:
                    #セキュリティグループID
                    for group in securityGroups:
                        key = group+subnet.vpcId
                        securityGroupIds.append(groupmap[key])


        # ダミーのリスナーの設定  instancePort, instanceProtocol, loadBalancerPort, protocol, sslCertificateId
        listener = Listener("65535", None, "65535","TCP",None)
        listeners = [listener]

        # ロードバランサの作成
        dnsName = self.client.createLoadBalancer(availabilityZone, listeners, loadBalancerName, subnetIds, securityGroupIds, internal)

        #実行ログ
        self.logger.info(None ,"IPROCESS-200111", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsElbCreate", ["EC2", loadBalancerName] )

        # ダミーのリスナーの削除
        self.client.deleteLoadBalancerListeners(["65535",], loadBalancerName)

        #クロスゾーン負荷分散を有効化
        self.client.modifyLoadBalancer(loadBalancerName)

        #実行ログ
        self.logger.info(None ,"IPROCESS-200226", [awsLoadBalancer["NAME"],])

        # イベントログ出力
        self.conn.debug(farmNo, None, None, None, None, "AwsCrossZoneEnabled", ["EC2", loadBalancerName] )

        # データベース更新
        updateDict = self.conn.selectOne(tableAWSLB.select(tableAWSLB.c.LOAD_BALANCER_NO==loadBalancerNo))
        updateDict["DNS_NAME"] = dnsName
        sql = tableAWSLB.update(tableAWSLB.c.LOAD_BALANCER_NO ==updateDict["LOAD_BALANCER_NO"], values=updateDict)
        self.conn.execute(sql)

        return dnsName;
Esempio n. 38
0
 def makeMassage(self, str = None, messid = None, *args):
     if isNotEmpty(str):
         return str
     else:
         return getMassage(messid, *args)
Esempio n. 39
0
    def attachVolume(self, vcInstance, disk):
        #FARM 取得
        tableFarm = self.conn.getTable("FARM")
        farm = self.conn.selectOne(
            tableFarm.select(tableFarm.c.FARM_NO == disk["FARM_NO"]))

        #組織
        vdc = self.client.getUseVdc()
        #マイクラウド
        vApp = self.client.describeMyCloud(vdc, farm["FARM_NAME"])
        #既存VM検索
        vm = self.client.describeInstance(vApp, vcInstance["VM_NAME"])
        # DISKNAMEがある場合は編集確認
        if (isNotEmpty(disk["DISK_ID"])):
            oldDisk = self.client.describeVolume(vm, disk["DISK_ID"])
            #ディスクの実態が確認できない(矛盾発生)場合はそのまま返す
            if oldDisk is None:
                self.logger.info("VOLUME IS NONE")
                return

            #何らかの影響でクラウド側の容量の方が大きい場合はDBを更新し合わせる
            if int(oldDisk.size) > (int(disk["SIZE"]) * 1024):
                table = self.conn.getTable("VCLOUD_DISK")
                updateDict = self.conn.selectOne(
                    table.select(table.c.DISK_NO == disk["DISK_NO"]))
                updateDict["SIZE"] = int(oldDisk.size) / 1024
                sql = table.update(table.c.DISK_NO == updateDict["DISK_NO"],
                                   values=updateDict)
                self.conn.execute(sql)

            #サイズ増
            if (int(disk["SIZE"]) * 1024) > int(oldDisk.size):
                #変更が有れば更新
                self.client.editVolume(vm, disk)
            #いずれにしても処理終了
            return

        #イベントログ出力
        tableCPNT = self.conn.getTable("COMPONENT")
        component = self.conn.selectOne(
            tableCPNT.select(tableCPNT.c.COMPONENT_NO == disk["COMPONENT_NO"]))
        componentName = None
        if component:
            componentName = component["COMPONENT_NAME"]
        tableINS = self.conn.getTable("INSTANCE")
        instance = self.conn.selectOne(
            tableINS.select(
                tableINS.c.INSTANCE_NO == vcInstance["INSTANCE_NO"]))
        self.conn.debug(
            instance["FARM_NO"], disk["COMPONENT_NO"], componentName,
            vcInstance["INSTANCE_NO"], instance["INSTANCE_NAME"],
            "VCloudDiskAttach",
            [instance["INSTANCE_NAME"], disk["DISK_ID"], disk["SIZE"]])

        # ボリュームのアタッチ
        pccdisk = self.client.attachVolume(vm, disk)

        #イベントログ出力
        self.conn.debug(
            instance["FARM_NO"], disk["COMPONENT_NO"], componentName,
            vcInstance["INSTANCE_NO"], instance["INSTANCE_NAME"],
            "VCloudDiskAttachFinish",
            [instance["INSTANCE_NAME"], disk["DISK_ID"], disk["SIZE"]])

        # データベースの更新
        table = self.conn.getTable("VCLOUD_DISK")
        updateDict = self.conn.selectOne(
            table.select(table.c.DISK_NO == disk["DISK_NO"]))
        updateDict["DISK_ID"] = pccdisk.name
        updateDict["ATTACHED"] = True
        updateDict["UNIT_NO"] = pccdisk.unitNo
        sql = table.update(table.c.DISK_NO == updateDict["DISK_NO"],
                           values=updateDict)
        self.conn.execute(sql)