Exemplo n.º 1
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=["token"]),
            access_token_secret=dict(required=True, aliases=["token_secret"]),
            zone=dict(required=False, default="is1a", choices=["is1a", "is1b", "tk1a"]),
            disk_resource_id=dict(required=False, type="int", aliases=["disk_id"]),
            name=dict(required=False, default="default"),
            desc=dict(required=False),
            tags=dict(required=False, type="list"),
            icon=dict(required=False),
            size_gib=dict(required=False, default=20, type="int", aliases=["disk_size"]),
            archive_resource_id=dict(required=False, type="int", aliases=["archive_id"]),
            server_resource_id=dict(required=False, type="int", aliases=["server_id"]),
            plan=dict(required=False, default="ssd", choices=["ssd", "hdd"]),
            config_host_name=dict(required=False),
            config_password=dict(required=False),
            config_ipv4_address=dict(required=False),
            config_ssh_key=dict(required=False),
            config_network_mask_len=dict(required=False, type="int"),
            config_default_route=dict(required=False),
            state=dict(required=False, default="present", choices=["present", "absent", "connected", "disconnected"]),
        ),
        supports_check_mode=True,
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg="Required module saklient not found")

    try:
        saklient = API.authorize(
            module.params["access_token"], module.params["access_token_secret"], module.params["zone"]
        )
    except Exception, e:
        module.fail_json(msg="Failed to access sacloud: %s" % e)
Exemplo n.º 2
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=['token']),
            access_token_secret=dict(required=True, aliases=['token_secret']),
            zone=dict(required=False, default='is1a',
                            choices=['is1a', 'is1b', 'tk1a', 'tk1v']),
            router_resource_id=dict(required=False, type='int'),
            name=dict(required=False, default='default'),
            desc=dict(required=False),
            tags=dict(required=False, type='list'),
            icon=dict(required=False),
            band_width_mbps=dict(required=False,
                                       default=100, type='int',
                                       choices=[100, 500, 1000]),
            network_mask_len=dict(required=False,
                                        default=28, type='int',
                                        choices=[26, 27, 28]),
            state=dict(required=False, default='present',
                        choices=['present', 'absent', 'connected', 'disconnected']),
            server_resource_id=dict(required=False, type='int'),
            iface_resource_id=dict(required=False, type='int')
        ),
        supports_check_mode=True
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg='Required module saklient not found')

    try:
        saklient = API.authorize(module.params['access_token'],
                                module.params['access_token_secret'],
                                module.params['zone'])
    except Exception, e:
        module.fail_json(msg='Failed to access sacloud: %s' % e)
Exemplo n.º 3
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=["token"]),
            access_token_secret=dict(required=True, aliases=["token_secret"]),
            zone=dict(required=False, default="is1a", choices=["is1a", "is1b", "tk1a"]),
            router_resource_id=dict(required=False, type="int"),
            name=dict(required=False, default="default"),
            desc=dict(required=False),
            tags=dict(required=False, type="list"),
            icon=dict(required=False),
            band_width_mbps=dict(required=False, default=100, type="int", choices=[100, 500, 1000]),
            network_mask_len=dict(required=False, default=28, type="int", choices=[26, 27, 28]),
            state=dict(required=False, default="present", choices=["present", "absent", "connected", "disconnected"]),
            server_resource_id=dict(required=False, type="int"),
            iface_resource_id=dict(required=False, type="int"),
        ),
        supports_check_mode=True,
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg="Required module saklient not found")

    try:
        saklient = API.authorize(
            module.params["access_token"], module.params["access_token_secret"], module.params["zone"]
        )
    except Exception, e:
        module.fail_json(msg="Failed to access sacloud: %s" % e)
Exemplo n.º 4
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=['token']),
            access_token_secret=dict(required=True, aliases=['token_secret']),
            zone=dict(required=False, default='is1a',
                            choices=['is1a', 'is1b', 'tk1a']),
            server_resource_id=dict(required=False, type='int'),
            cpu=dict(required=False, default='1', type='int'),
            mem=dict(required=False, default='1', type='int'),
            name=dict(required=False, default='default'),
            desc=dict(required=False),
            tags=dict(required=False, type='list'),
            icon=dict(required=False),
            force=dict(required=False, default=False, type='bool'),
            state=dict(required=False, default='present',
                        choices=['present', 'absent', 'stopped', 'running'])
        ),
        supports_check_mode=True
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg='Required module saklient not found')

    try:
        saklient = API.authorize(module.params['access_token'],
                                module.params['access_token_secret'],
                                module.params['zone'])
    except Exception, e:
        module.fail_json(msg='Failed to access sacloud: %s' % e)
Exemplo n.º 5
0
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])

        # search a region
        print('searching a region...')
        regions = api.facility.region.find()
        self.assertTrue(len(regions) > 0)

        # create a bridge
        print('creating a bridge...')
        bridge = api.bridge.create()
        bridge.name = name
        bridge.description = ''
        bridge.region = regions[0]
        bridge.save()

        # delete the bridge
        print('deleting the bridge...')
        bridge.destroy()
Exemplo n.º 6
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     
     
     
     # search a region
     print('searching a region...')
     regions = api.facility.region.find()
     self.assertTrue(len(regions) > 0)
     
     # create a bridge
     print('creating a bridge...')
     bridge = api.bridge.create()
     bridge.name = name
     bridge.description = ''
     bridge.region = regions[0]
     bridge.save()
     
     # delete the bridge
     print('deleting the bridge...')
     bridge.destroy()
Exemplo n.º 7
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=['token']),
            access_token_secret=dict(required=True, aliases=['token_secret']),
            zone=dict(required=False, default='is1a',
                            choices=['is1a', 'is1b', 'tk1a']),
            router_resource_id=dict(required=False, type='int'),
            lb_resource_id=dict(required=False, type='int'),
            name=dict(required=False, default='default'),
            desc=dict(required=False),
            tags=dict(required=False, type='list'),
            icon=dict(required=False),
            vrid=dict(required=False, type='int'),
            real_ips=dict(required=False, type='list'),
            high_spec=dict(required=False, default=False, type='bool'),
            force=dict(required=False, default=False, type='bool'),
            virtual_ip=dict(required=False),
            port=dict(required=False, default=80, type='int'),
            delay_loop=dict(required=False, default=10, type='int'),
            lbserver_ips=dict(required=False, type='list'),
            lbserver_port=dict(required=False, default=80, type='int'),
            lbserver_protocol=dict(required=False, default='http',
                                    choices=['http', 'https', 'tcp', 'ping']),
            lbserver_path=dict(required=False, default='/index.html'),
            lbserver_response=dict(required=False, default=200, type='int'),
            state=dict(required=False, default='present',
                        choices=['present', 'absent', 'stopped', 'running', 'applied'])
        ),
        supports_check_mode=True
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg='Required module saklient not found')

    try:
        saklient = API.authorize(module.params['access_token'],
                                module.params['access_token_secret'],
                                module.params['zone'])
    except Exception, e:
        module.fail_json(msg='Failed to access sacloud: %s' % e)
Exemplo n.º 8
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            access_token=dict(required=True, aliases=['token']),
            access_token_secret=dict(required=True, aliases=['token_secret']),
            zone=dict(required=False, default='is1a',
                            choices=['is1a', 'is1b', 'tk1a', 'tk1v']),
            disk_resource_id=dict(required=False, type='int', aliases=['disk_id']),
            name=dict(required=False, default='default'),
            desc=dict(required=False),
            tags=dict(required=False, type='list'),
            icon=dict(required=False),
            size_gib=dict(required=False, default=20,
                                type='int', aliases=['disk_size']),
            archive_resource_id=dict(required=False, type='int',
                                        aliases=['archive_id']),
            server_resource_id=dict(required=False, type='int',
                                        aliases=['server_id']),
            plan=dict(required=False, default='ssd',
                            choices=['ssd', 'hdd']),
            config_host_name=dict(required=False),
            config_password=dict(required=False),
            config_ipv4_address=dict(required=False),
            config_ssh_key=dict(required=False),
            config_network_mask_len=dict(required=False, type='int'),
            config_default_route=dict(required=False),
            state=dict(required=False, default='present',
                        choices=['present', 'absent', 'connected', 'disconnected'])
        ),
        supports_check_mode=True
    )

    if not HAS_SAKLIENT:
        module.fail_json(msg='Required module saklient not found')

    try:
        saklient = API.authorize(module.params['access_token'],
                                module.params['access_token_secret'],
                                module.params['zone'])
    except Exception, e:
        module.fail_json(msg='Failed to access sacloud: %s' % e)
Exemplo n.º 9
0
def lambda_handler(event, context):

    #token = os.environ['SAKURACLOUD_ACCESS_TOKEN']
    token = boto3.client('kms').decrypt(CiphertextBlob=b64decode(
        os.environ['SAKURACLOUD_ACCESS_TOKEN']))['Plaintext'].decode('utf-8')
    #secret = os.environ['SAKURACLOUD_ACCESS_TOKEN_SECRET']
    secret = boto3.client('kms').decrypt(
        CiphertextBlob=b64decode(os.environ['SAKURACLOUD_ACCESS_TOKEN_SECRET']
                                 ))['Plaintext'].decode('utf-8')
    #zone = os.environ['SAKURACLOUD_ZONE']
    zones = ["is1a", "is1b", "tk1a"]
    target_tags = ["autostartstop"]
    action = event['Action']
    #messages = ['', '', '']
    text = ''
    count = 0

    if action == 'Start':
        msg = "おはようございます :sunrise: *以下のサーバを起動しました。* \\n\\n"
        text += '[{"type": "section", "text": {"type": "mrkdwn", "text": "' + msg + '"}},{"type": "section","fields": ['
    elif action == 'Stop':
        msg = "お疲れさまでした :stars: *以下のサーバを停止しました。* \\n\\n"
        text += '[{"type": "section", "text": {"type": "mrkdwn", "text": "' + msg + '"}},{"type": "section","fields": ['

    for zone in zones:
        api = API.authorize(token, secret, zone)

        #print('searching servers')
        model_server = api.server
        model_server.with_tags(target_tags)
        servers = model_server.find()

        start_list = []
        stop_list = []

        for i in servers:
            #print(i.name)
            #print(inspect.getmembers(i.instance))
            #print(i.instance.status)
            if i.instance.status == 'down' and action == 'Start':
                start_list.append(i.id)
            elif i.instance.status == 'up' and action == 'Stop':
                stop_list.append(i.id)

        #print('Zone ->', zone)
        #messages[count] += ':sacloud-green: Zone -> ' + zone + '\\n'
        text += '{"type": "plain_text","text": ":sacloud-green: Zone -> ' + zone + '","emoji": true},'
        text += '{"type": "plain_text","text": ":ballot_box_with_check: Result","emoji": true},'
        if start_list:
            #print('Starting', len(start_list), 'instances', start_list)
            #messages[count] += 'Starting' + len(start_list) + 'instances' + start_list + '\\n'
            for i in start_list:
                #messages[count] += model_server.get_by_id(i).get_name() + ' -> '
                text += '{"type": "plain_text","text": "' + model_server.get_by_id(
                    i).get_name() + '","emoji": true},'
                try:
                    model_server.get_by_id(i).boot()
                    #print('Start:', model_server.get_by_id(i).get_name())
                    #messages[count] += 'started\\n'
                    text += '{"type": "plain_text","text": ":up:","emoji": true},'
                except Exception as e:
                    text += '{"type": "plain_text","text": ":warning: Error:' + str(
                        e) + '","emoji": true},'

        elif stop_list:
            #print('Stopping', len(stop_list), 'instances', stop_list)
            #messages[count] += 'Stopping' + len(stop_list) + 'instances' + stop_list + '\\n'
            for i in stop_list:
                #messages[count] += model_server.get_by_id(i).get_name() + ' -> '
                text += '{"type": "plain_text","text": "' + model_server.get_by_id(
                    i).get_name() + '","emoji": true},'
                try:
                    model_server.get_by_id(i).shutdown()  # stop
                    #print('Stop:', model_server.get_by_id(i).get_name())
                    #messages[count] += 'stopped\\n'
                    text += '{"type": "plain_text","text": ":no_entry:","emoji": true},'
                except Exception as e:
                    text += '{"type": "plain_text","text": ":warning: Error:' + str(
                        e) + '","emoji": true},'

        count += 1
        text = text.rstrip(",")
        if count < len(zones):
            text += ']},{"type": "divider"},{"type": "section","fields": ['

    #print(messages)
    #j = '[{"type": "section", "text": {"type": "mrkdwn", "text": "' + text + '"}},{"type": "section","fields": [{"type": "plain_text","text": "' + messages[0] + '", "emoji": true},{"type": "plain_text","text": "' + messages[1] + '", "emoji": true},{"type": "plain_text","text": "' + messages[2] + '","emoji": true}]}]'
    text += ']}]'
    json_data = json.loads(text)
    #print(json_data)
    post_to_slack(json_data)
Exemplo n.º 10
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be found
     servers = api.server.sort_by_memory().find()
     self.assertIsInstance(servers, list)
     self.assertTrue(0 < len(servers))
     
     mem = 0
     for server in servers:
         self.assertIsInstance(server, Server)
         self.assertIsInstance(server.plan, ServerPlan)
         self.assertTrue(0 < server.plan.cpu)
         self.assertTrue(0 < server.plan.memory_mib)
         self.assertTrue(0 < server.plan.memory_gib)
         self.assertEqual(server.plan.memory_mib / server.plan.memory_gib, 1024)
         self.assertIsInstance(server.tags, list)
         for tag in server.tags:
             self.assertIsInstance(tag, str)
         self.assertTrue(mem <= server.plan.memory_gib)
         mem = server.plan.memory_gib
     
     # should be limited
     servers = api.server.limit(1).find()
     self.assertEqual(len(servers), 1)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     cpu = 1
     mem = 2
     host_name = 'saklient-test'
     ssh_public_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3sSg8Vfxrs3eFTx3G//wMRlgqmFGxh5Ia8DZSSf2YrkZGqKbL1t2AsiUtIMwxGiEVVBc0K89lORzra7qoHQj5v5Xlcdqodgcs9nwuSeS38XWO6tXNF4a8LvKnfGS55+uzmBmVUwAztr3TIJR5TTWxZXpcxSsSEHx7nIcr31zcvosjgdxqvSokAsIgJyPQyxCxsPK8SFIsUV+aATqBCWNyp+R1jECPkd74ipEBoccnA0pYZnRhIsKNWR9phBRXIVd5jx/gK5jHqouhFWvCucUs0gwilEGwpng3b/YxrinNskpfOpMhOD9zjNU58OCoMS8MA17yqoZv59l3u16CrnrD saklient-test@local'
     ssh_private_key_file = root + '/test-sshkey.txt'
     
     # search archives
     print('searching archives...')
     archives = api.archive \
         .with_name_like('CentOS 6.5 64bit') \
         .with_size_gib(20) \
         .with_shared_scope() \
         .limit(1) \
         .find()
     self.assertTrue(0 < len(archives))
     archive = archives[0]
     
     # search scripts
     print('searching scripts...')
     scripts = api.script \
         .with_name_like('WordPress') \
         .with_shared_scope() \
         .limit(1) \
         .find()
     self.assertTrue(0 < len(scripts))
     script = scripts[0]
     
     # create a disk
     print('creating a disk...')
     disk = api.disk.create()
     self.assertRaises(SaklientException, lambda: disk.save())
     # Requiredフィールドが未set時は SaklientException がスローされなければなりません
     disk.name = name
     disk.description = description
     disk.tags = [tag]
     disk.plan = api.product.disk.ssd
     disk.source = archive
     disk.save()
     self.assertEqual(disk.size_gib, 20)
     
     # check an immutable field
     print('updating the disk...')
     def immutable_test():
         disk.size_mib = 20480
         disk.save()
     self.assertRaises(SaklientException, immutable_test)
     # Immutableフィールドの再set時は SaklientException がスローされなければなりません
     
     # create a server
     print('creating a server...')
     server = api.server.create()
     self.assertIsInstance(server, Server)
     server.name = name
     server.description = description
     server.tags = [tag]
     server.plan = api.product.server.get_by_spec(cpu, mem)
     server.save()
     
     # check the server properties
     self.assertTrue(0 < int(server.id))
     self.assertEqual(server.name, name)
     self.assertEqual(server.description, description)
     self.assertIsInstance(server.tags, list)
     self.assertEqual(len(server.tags), 1)
     self.assertEqual(server.tags[0], tag)
     self.assertEqual(server.plan.cpu, cpu)
     self.assertEqual(server.plan.memory_gib, mem)
     
     # connect to shared segment
     print('connecting the server to shared segment...')
     iface = server.add_iface()
     self.assertIsInstance(iface, Iface)
     self.assertTrue(0 < int(iface.id))
     iface.connect_to_shared_segment()
     
     # wait disk copy
     print('waiting disk copy...')
     self.assertTrue(disk.sleep_while_copying())
     # アーカイブからディスクへのコピーがタイムアウトしました
     disk.source = None
     disk.reload()
     self.assertIsInstance(disk.source, Archive)
     self.assertEqual(disk.source.id, archive.id)
     self.assertEqual(disk.size_gib, archive.size_gib)
     
     # connect the disk to the server
     print('connecting the disk to the server...')
     disk.connect_to(server)
     
     # config the disk
     print('writing configuration to the disk...')
     passwd = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     diskcfg = disk.create_config()
     diskcfg.host_name = host_name
     diskcfg.password = passwd
     diskcfg.ssh_key = ssh_public_key
     diskcfg.add_script = script
     diskcfg.write()
     
     # boot
     print('booting the server...')
     server.boot()
     time.sleep(1)
     server.reload()
     self.assertEqual(server.instance.status, EServerInstanceStatus.UP)
     
     # boot conflict
     print('checking the server power conflicts...')
     self.assertRaises(HttpConflictException, lambda: server.boot())
     # サーバ起動中の起動試行時は HttpConflictException がスローされなければなりません
     
     # ssh
     ip_address = server.ifaces[0].ip_address
     self.assertIsNotNone(ip_address)
     cmd = "ssh -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -i"+ssh_private_key_file+" root@"+ip_address+" hostname"
     ssh_success = False
     print('trying to SSH to the server...')
     for i in range(10):
         time.sleep(5)
         ph = subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
         host_name_got = "".join([l.decode("utf-8") for l in ph.stdout.readlines()]).rstrip()
         err = "".join([l.decode("utf-8") for l in ph.stderr.readlines()]).rstrip()
         ph.stdout.close()
         ph.stderr.close()
         if err != "": print(err)
         if host_name != host_name_got: continue
         ssh_success = True
         break
     self.assertTrue(ssh_success)
     # 作成したサーバへ正常にSSHできません
     
     # stop
     time.sleep(3)
     print('stopping the server...')
     server.stop()
     self.assertTrue(server.sleep_until_down())
     # サーバが正常に停止しません
     
     # disconnect the disk from the server
     print('disconnecting the disk from the server...')
     disk.disconnect()
     
     # delete the server
     print('deleting the server...')
     server.destroy()
     
     # duplicate the disk
     print('duplicating the disk (expanding to 40GiB)...')
     disk2 = api.disk.create()
     disk2.name = name + "-copy"
     disk2.description = description
     disk2.tags = [tag]
     disk2.plan = api.product.disk.hdd
     disk2.source = disk
     disk2.size_gib = 40
     disk2.save()
     
     # wait disk duplication
     print('waiting disk duplication...')
     self.assertTrue(disk2.sleep_while_copying())
     # ディスクの複製がタイムアウトしました 
     disk2.source = None
     disk2.reload()
     self.assertIsInstance(disk2.source, Disk)
     self.assertEqual(disk2.source.id, disk.id)
     self.assertEqual(disk2.size_gib, 40)
     
     # delete the disks
     print('deleting the disks...')
     disk2.destroy()
     disk.destroy()
Exemplo n.º 11
0
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])
        description = 'This instance was created by saklient.python test'
        tag = 'saklient-test'

        # search a switch
        print('searching a swytch...')
        swytches = api.swytch.with_tag('lb-attached').limit(1).find()
        self.assertTrue(len(swytches) > 0)
        swytch = swytches[0]
        self.assertIsInstance(swytch, Swytch)
        self.assertTrue(len(swytch.ipv4_nets) > 0)
        net = swytch.ipv4_nets[0]
        print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))

        # create a loadbalancer
        print('creating a LB...')
        vrid = 123
        lb = api.appliance.create_load_balancer(
            swytch, vrid, ['133.242.255.244', '133.242.255.245'], True)

        def test_required():
            lb.save()

        self.assertRaises(SaklientException, test_required)
        # Requiredフィールドが未set時は SaklientException がスローされなければなりません
        lb.name = name
        lb.description = ''
        lb.tags = [tag]
        lb.save()

        lb.reload()
        self.assertEqual(lb.default_route, net.default_route)
        self.assertEqual(lb.mask_len, net.mask_len)
        self.assertEqual(lb.vrid, vrid)
        self.assertEqual(lb.swytch_id, swytch.id)

        # wait the LB becomes up
        print('waiting the LB becomes up...')
        if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')

        # stop the LB
        time.sleep(1)
        print('stopping the LB...')
        if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')

        # delete the LB
        print('deleting the LB...')
        lb.destroy()
Exemplo n.º 12
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     
     
     
     # create a LB
     if self.TESTS_CONFIG_READYMADE_LB_ID is None:
         
         # search a switch
         print('作成済みのルータ+スイッチを検索しています...')
         swytches = api.swytch.with_name_like('saklient-lb-attached').limit(1).find()
         if 0 < len(swytches):
             swytch = swytches[0]
         else:
             print('ルータ+スイッチを作成しています...')
             router = api.router.create()
             router.name = 'saklient-lb-attached'
             router.band_width_mbps = 100
             router.network_mask_len = 28
             router.save()
             
             print('ルータ+スイッチの作成完了を待機しています...')
             if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
             swytch = router.get_swytch()
         
         self.assertIsInstance(swytch, Swytch)
         self.assertTrue(len(swytch.ipv4_nets) > 0)
         net = swytch.ipv4_nets[0]
         print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))
         
         # create a loadbalancer
         print('ロードバランサを作成しています...')
         vrid = 123
         real_ip1 = Util.long2ip(Util.ip2long(net.default_route) + 3)
         real_ip2 = Util.long2ip(Util.ip2long(net.default_route) + 4)
         lb = api.appliance.create_load_balancer(swytch, vrid, [real_ip1, real_ip2], True)
         
         def test_required():
             lb.save()
         self.assertRaises(SaklientException, test_required)
         # Requiredフィールドが未set時は SaklientException がスローされなければなりません
         lb.name = name
         lb.description = ''
         lb.tags = [tag]
         lb.save()
         
         lb.reload()
         self.assertEqual(lb.default_route, net.default_route)
         self.assertEqual(lb.mask_len, net.mask_len)
         self.assertEqual(lb.vrid, vrid)
         self.assertEqual(lb.swytch_id, swytch.id)
         
         # wait the LB becomes up
         print('ロードバランサの起動を待機しています...')
         if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')
     
     else:
         
         lb = api.appliance.get_by_id(self.TESTS_CONFIG_READYMADE_LB_ID)
         self.assertIsInstance(lb, LoadBalancer)
         swytch = lb.get_swytch()
         self.assertIsInstance(swytch, Swytch)
         net = swytch.ipv4_nets[0]
         self.assertIsInstance(net, Ipv4Net)
         print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))
     
     
     
     # clear virtual ips
     
     lb.clear_virtual_ips()
     lb.save()
     lb.reload()
     self.assertEqual(len(lb.virtual_ips), 0)
     
     
     
     # setting virtual ips test 1
     
     vip1Ip     = long2ip(ip2long(net.default_route) + 5)
     vip1SrvIp1 = long2ip(ip2long(net.default_route) + 6)
     vip1SrvIp2 = long2ip(ip2long(net.default_route) + 7)
     vip1SrvIp3 = long2ip(ip2long(net.default_route) + 8)
     vip1SrvIp4 = long2ip(ip2long(net.default_route) + 9)
     
     lb.add_virtual_ip({
         'vip': vip1Ip,
         'port': 80,
         'delay': 15,
         'servers': [
             { 'ip':vip1SrvIp1, 'port':80, 'protocol':'http', 'path_to_check':'/index.html', 'response_expected':200 },
             { 'ip':vip1SrvIp2, 'port':80, 'protocol':'https', 'path_to_check':'/', 'response_expected':200 },
             { 'ip':vip1SrvIp3, 'port':80, 'protocol':'tcp' }
         ]
     })
     
     vip2Ip     = long2ip(ip2long(net.default_route) + 10)
     vip2SrvIp1 = long2ip(ip2long(net.default_route) + 11)
     vip2SrvIp2 = long2ip(ip2long(net.default_route) + 12)
     
     vip2 = lb.add_virtual_ip()
     vip2.virtual_ip_address = vip2Ip
     vip2.port = 80
     vip2.delay_loop = 15
     vip2Srv1 = vip2.add_server()
     vip2Srv1.ip_address = vip2SrvIp1
     vip2Srv1.port = 80
     vip2Srv1.protocol = 'http'
     vip2Srv1.path_to_check = '/index.html'
     vip2Srv1.response_expected = 200
     vip2Srv2 = vip2.add_server()
     vip2Srv2.ip_address = vip2SrvIp2
     vip2Srv2.port = 80
     vip2Srv2.protocol = 'tcp'
     lb.save()
     lb.reload()
     
     self.assertEqual(len(lb.virtual_ips), 2)
     self.assertEqual(lb.virtual_ips[0].virtual_ip_address, vip1Ip)
     self.assertEqual(len(lb.virtual_ips[0].servers), 3)
     self.assertEqual(lb.virtual_ips[0].servers[0].ip_address, vip1SrvIp1)
     self.assertEqual(lb.virtual_ips[0].servers[0].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[0].protocol, 'http')
     self.assertEqual(lb.virtual_ips[0].servers[0].path_to_check, '/index.html')
     self.assertEqual(lb.virtual_ips[0].servers[0].response_expected, 200)
     self.assertEqual(lb.virtual_ips[0].servers[1].ip_address, vip1SrvIp2)
     self.assertEqual(lb.virtual_ips[0].servers[1].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[1].protocol, 'https')
     self.assertEqual(lb.virtual_ips[0].servers[1].path_to_check, '/')
     self.assertEqual(lb.virtual_ips[0].servers[1].response_expected, 200)
     self.assertEqual(lb.virtual_ips[0].servers[2].ip_address, vip1SrvIp3)
     self.assertEqual(lb.virtual_ips[0].servers[2].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[2].protocol, 'tcp')
     self.assertEqual(lb.virtual_ips[1].virtual_ip_address, vip2Ip)
     self.assertEqual(len(lb.virtual_ips[1].servers), 2)
     self.assertEqual(lb.virtual_ips[1].servers[0].ip_address, vip2SrvIp1)
     self.assertEqual(lb.virtual_ips[1].servers[0].port, 80)
     self.assertEqual(lb.virtual_ips[1].servers[0].protocol, 'http')
     self.assertEqual(lb.virtual_ips[1].servers[0].path_to_check, '/index.html')
     self.assertEqual(lb.virtual_ips[1].servers[0].response_expected, 200)
     self.assertEqual(lb.virtual_ips[1].servers[1].ip_address, vip2SrvIp2)
     self.assertEqual(lb.virtual_ips[1].servers[1].port, 80)
     self.assertEqual(lb.virtual_ips[1].servers[1].protocol, 'tcp')
     
     
     
     # setting virtual ips test 2
     
     lb.get_virtual_ip_by_address(vip1Ip).add_server({
         'ip': vip1SrvIp4,
         'port': 80,
         'protocol': 'ping'
     })
     lb.save()
     lb.reload()
     
     self.assertEqual(len(lb.virtual_ips), 2)
     self.assertEqual(len(lb.virtual_ips[0].servers), 4)
     self.assertEqual(lb.virtual_ips[0].servers[3].ip_address, vip1SrvIp4)
     self.assertEqual(lb.virtual_ips[0].servers[3].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[3].protocol, 'ping')
     self.assertEqual(len(lb.virtual_ips[1].servers), 2)
     
     
     
     # checking status
     
     lb.reload_status()
     for vip in lb.virtual_ips:
         print('  vip %s:%s every %ssec(s)' % (vip.virtual_ip_address, vip.port, vip.delay_loop))
         for server in vip.servers:
             print('    [%s(%s)]' % (server.status, server.active_connections), end='')
             print(' server %s://%s' % (server.protocol, server.ip_address), end='')
             if server.port: print(':%d' % (server.port), end='')
             if server.path_to_check: print(server.path_to_check, end='')
             print(' answers', end='')
             if server.response_expected: print(' %d' % (server.response_expected), end='')
             print('')
             self.assertEqual(server.status, 'down')
     
     
     
     if not self.TESTS_CONFIG_READYMADE_LB_ID:
         
         # stop the LB
         time.sleep(1)
         print('ロードバランサを停止しています...')
         if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')
         
         # delete the LB
         print('ロードバランサを削除しています...')
         lb.destroy()
Exemplo n.º 13
0
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])
        description = 'This instance was created by saklient.python test'
        tag = 'saklient-test'

        # create a LB
        if self.TESTS_CONFIG_READYMADE_LB_ID is None:

            # search a switch
            print('作成済みのルータ+スイッチを検索しています...')
            swytches = api.swytch.with_name_like('saklient-lb-attached').limit(
                1).find()
            if 0 < len(swytches):
                swytch = swytches[0]
            else:
                print('ルータ+スイッチを作成しています...')
                router = api.router.create()
                router.name = 'saklient-lb-attached'
                router.band_width_mbps = 100
                router.network_mask_len = 28
                router.save()

                print('ルータ+スイッチの作成完了を待機しています...')
                if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
                swytch = router.get_swytch()

            self.assertIsInstance(swytch, Swytch)
            self.assertTrue(len(swytch.ipv4_nets) > 0)
            net = swytch.ipv4_nets[0]
            print('%s/%d -> %s' %
                  (net.address, net.mask_len, net.default_route))

            # create a loadbalancer
            print('ロードバランサを作成しています...')
            vrid = 123
            real_ip1 = Util.long2ip(Util.ip2long(net.default_route) + 3)
            real_ip2 = Util.long2ip(Util.ip2long(net.default_route) + 4)
            lb = api.appliance.create_load_balancer(swytch, vrid,
                                                    [real_ip1, real_ip2], True)

            def test_required():
                lb.save()

            self.assertRaises(SaklientException, test_required)
            # Requiredフィールドが未set時は SaklientException がスローされなければなりません
            lb.name = name
            lb.description = ''
            lb.tags = [tag]
            lb.save()

            lb.reload()
            self.assertEqual(lb.default_route, net.default_route)
            self.assertEqual(lb.mask_len, net.mask_len)
            self.assertEqual(lb.vrid, vrid)
            self.assertEqual(lb.swytch_id, swytch.id)

            # wait the LB becomes up
            print('ロードバランサの起動を待機しています...')
            if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')

        else:

            lb = api.appliance.get_by_id(self.TESTS_CONFIG_READYMADE_LB_ID)
            self.assertIsInstance(lb, LoadBalancer)
            swytch = lb.get_swytch()
            self.assertIsInstance(swytch, Swytch)
            net = swytch.ipv4_nets[0]
            self.assertIsInstance(net, Ipv4Net)
            print('%s/%d -> %s' %
                  (net.address, net.mask_len, net.default_route))

        # clear virtual ips

        lb.clear_virtual_ips()
        lb.save()
        lb.reload()
        self.assertEqual(len(lb.virtual_ips), 0)

        # setting virtual ips test 1

        vip1Ip = long2ip(ip2long(net.default_route) + 5)
        vip1SrvIp1 = long2ip(ip2long(net.default_route) + 6)
        vip1SrvIp2 = long2ip(ip2long(net.default_route) + 7)
        vip1SrvIp3 = long2ip(ip2long(net.default_route) + 8)
        vip1SrvIp4 = long2ip(ip2long(net.default_route) + 9)

        lb.add_virtual_ip({
            'vip':
            vip1Ip,
            'port':
            80,
            'delay':
            15,
            'servers': [{
                'ip': vip1SrvIp1,
                'port': 80,
                'protocol': 'http',
                'path_to_check': '/index.html',
                'response_expected': 200
            }, {
                'ip': vip1SrvIp2,
                'port': 80,
                'protocol': 'https',
                'path_to_check': '/',
                'response_expected': 200
            }, {
                'ip': vip1SrvIp3,
                'port': 80,
                'protocol': 'tcp'
            }]
        })

        vip2Ip = long2ip(ip2long(net.default_route) + 10)
        vip2SrvIp1 = long2ip(ip2long(net.default_route) + 11)
        vip2SrvIp2 = long2ip(ip2long(net.default_route) + 12)

        vip2 = lb.add_virtual_ip()
        vip2.virtual_ip_address = vip2Ip
        vip2.port = 80
        vip2.delay_loop = 15
        vip2Srv1 = vip2.add_server()
        vip2Srv1.ip_address = vip2SrvIp1
        vip2Srv1.port = 80
        vip2Srv1.protocol = 'http'
        vip2Srv1.path_to_check = '/index.html'
        vip2Srv1.response_expected = 200
        vip2Srv2 = vip2.add_server()
        vip2Srv2.ip_address = vip2SrvIp2
        vip2Srv2.port = 80
        vip2Srv2.protocol = 'tcp'
        lb.save()
        lb.reload()

        self.assertEqual(len(lb.virtual_ips), 2)
        self.assertEqual(lb.virtual_ips[0].virtual_ip_address, vip1Ip)
        self.assertEqual(len(lb.virtual_ips[0].servers), 3)
        self.assertEqual(lb.virtual_ips[0].servers[0].ip_address, vip1SrvIp1)
        self.assertEqual(lb.virtual_ips[0].servers[0].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[0].protocol, 'http')
        self.assertEqual(lb.virtual_ips[0].servers[0].path_to_check,
                         '/index.html')
        self.assertEqual(lb.virtual_ips[0].servers[0].response_expected, 200)
        self.assertEqual(lb.virtual_ips[0].servers[1].ip_address, vip1SrvIp2)
        self.assertEqual(lb.virtual_ips[0].servers[1].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[1].protocol, 'https')
        self.assertEqual(lb.virtual_ips[0].servers[1].path_to_check, '/')
        self.assertEqual(lb.virtual_ips[0].servers[1].response_expected, 200)
        self.assertEqual(lb.virtual_ips[0].servers[2].ip_address, vip1SrvIp3)
        self.assertEqual(lb.virtual_ips[0].servers[2].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[2].protocol, 'tcp')
        self.assertEqual(lb.virtual_ips[1].virtual_ip_address, vip2Ip)
        self.assertEqual(len(lb.virtual_ips[1].servers), 2)
        self.assertEqual(lb.virtual_ips[1].servers[0].ip_address, vip2SrvIp1)
        self.assertEqual(lb.virtual_ips[1].servers[0].port, 80)
        self.assertEqual(lb.virtual_ips[1].servers[0].protocol, 'http')
        self.assertEqual(lb.virtual_ips[1].servers[0].path_to_check,
                         '/index.html')
        self.assertEqual(lb.virtual_ips[1].servers[0].response_expected, 200)
        self.assertEqual(lb.virtual_ips[1].servers[1].ip_address, vip2SrvIp2)
        self.assertEqual(lb.virtual_ips[1].servers[1].port, 80)
        self.assertEqual(lb.virtual_ips[1].servers[1].protocol, 'tcp')

        # setting virtual ips test 2

        lb.get_virtual_ip_by_address(vip1Ip).add_server({
            'ip': vip1SrvIp4,
            'port': 80,
            'protocol': 'ping'
        })
        lb.save()
        lb.reload()

        self.assertEqual(len(lb.virtual_ips), 2)
        self.assertEqual(len(lb.virtual_ips[0].servers), 4)
        self.assertEqual(lb.virtual_ips[0].servers[3].ip_address, vip1SrvIp4)
        self.assertEqual(lb.virtual_ips[0].servers[3].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[3].protocol, 'ping')
        self.assertEqual(len(lb.virtual_ips[1].servers), 2)

        # checking status

        lb.reload_status()
        for vip in lb.virtual_ips:
            print('  vip %s:%s every %ssec(s)' %
                  (vip.virtual_ip_address, vip.port, vip.delay_loop))
            for server in vip.servers:
                msg = '    [%s(%s)]' % (server.status,
                                        server.active_connections)
                msg += ' server %s://%s' % (server.protocol, server.ip_address)
                if server.port: msg += ':%d' % (server.port)
                if server.path_to_check: msg += server.path_to_check
                msg += ' answers'
                if server.response_expected:
                    msg += ' %d' % (server.response_expected)
                print(msg)
                # self.assertEqual(server.status, 'down')

        if not self.TESTS_CONFIG_READYMADE_LB_ID:

            # stop the LB
            time.sleep(1)
            print('ロードバランサを停止しています...')
            if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')

            # delete the LB
            print('ロードバランサを削除しています...')
            lb.destroy()
Exemplo n.º 14
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     mask_len = 28
     mask_len_cnt = 1<<32-mask_len
     sroute_mask_len = 28
     sroute_mask_len_cnt = 1<<32-sroute_mask_len
     
     #
     swytch = None
     if True:
         print('ルータ+スイッチの帯域プランを検索しています...')
         plans = api.product.router.find()
         min_mbps = 0x7FFFFFFF
         for plan in plans:
             self.assertIsInstance(plan, RouterPlan)
             self.assertTrue(0 < plan.band_width_mbps)
             min_mbps = min(plan.band_width_mbps, min_mbps)
         
         print('ルータ+スイッチを作成しています...')
         router = api.router.create()
         router.name = name
         router.description = description
         router.band_width_mbps = min_mbps
         router.network_mask_len = mask_len
         router.save()
         
         print('ルータ+スイッチの作成完了を待機しています...')
         if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
         swytch = router.get_swytch()
     else:
         print('既存のルータ+スイッチを取得しています...')
         swytches = api.swytch.with_name_like('saklient-static-1').limit(1).find()
         self.assertEqual(len(swytches), 1)
         swytch = swytches[0]
     
     self.assertIsInstance(swytch, Swytch)
     self.assertEqual(len(swytch.ipv4_nets), 1)
     self.assertIsInstance(swytch.ipv4_nets[0], Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets[0].range.as_array), mask_len_cnt-5)
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 0)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-5)
     
     #
     print('サーバを作成しています...')
     server = api.server.create()
     self.assertIsInstance(server, Server)
     server.name = name
     server.description = description
     server.plan = api.product.server.get_by_spec(1, 1)
     server.save()
     self.assertTrue(0 < int(server.id))
      
     #
     print('インタフェースを増設しています...')
     iface = server.add_iface()
     self.assertIsInstance(iface, Iface)
     self.assertTrue(0 < int(iface.id))
     
     #
     print('インタフェースをルータ+スイッチに接続しています...')
     iface.connect_to_swytch(swytch)
     
     #
     print('インタフェースにIPアドレスを設定しています...')
     iface.user_ip_address = swytch.ipv4_nets[0].range.as_array[1]
     iface.save()
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 1)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-6)
     
     #
     print('ルータ+スイッチの帯域プランを変更しています...')
     router_id_before = swytch.router.id
     swytch.change_plan(500 if swytch.router.band_width_mbps==100 else 100)
     self.assertNotEqual(swytch.router.id, router_id_before)
     
     #
     print('ルータ+スイッチにIPv6ネットワークを割り当てています...')
     v6net = swytch.add_ipv6_net()
     self.assertIsInstance(v6net, Ipv6Net)
     self.assertEqual(len(swytch.ipv6_nets), 1)
     
     #
     print('ルータ+スイッチにスタティックルートを割り当てています...')
     net0 = swytch.ipv4_nets[0]
     next_hop = Util.long2ip(Util.ip2long(net0.address) + 4)
     sroute = swytch.add_static_route(28, next_hop)
     self.assertIsInstance(sroute, Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets), 2)
     self.assertEqual(len(swytch.ipv4_nets[1].range.as_array), sroute_mask_len_cnt)
     
     #
     for i in range(len(swytch.ipv4_nets) - 1, 0, -1):
         print('ルータ+スイッチからスタティックルートの割当を解除しています...')
         net = swytch.ipv4_nets[i]
         swytch.remove_static_route(net)
     
     #
     if 0 < len(swytch.ipv6_nets):
         print('ルータ+スイッチからIPv6ネットワークの割当を解除しています...')
         swytch.remove_ipv6_net()
     
     #
     print('サーバを削除しています...')
     server.destroy()
Exemplo n.º 15
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     mask_len = 28
     mask_len_cnt = 1<<32-mask_len
     sroute_mask_len = 28
     sroute_mask_len_cnt = 1<<32-sroute_mask_len
     
     #
     swytch = None
     if True:
         print('ルータ+スイッチの帯域プランを検索しています...')
         plans = api.product.router.find()
         min_mbps = 0x7FFFFFFF
         for plan in plans:
             self.assertIsInstance(plan, RouterPlan)
             self.assertTrue(0 < plan.band_width_mbps)
             min_mbps = min(plan.band_width_mbps, min_mbps)
         
         print('ルータ+スイッチを作成しています...')
         router = api.router.create()
         router.name = name
         router.description = description
         router.band_width_mbps = min_mbps
         router.network_mask_len = mask_len
         router.save()
         
         print('ルータ+スイッチの作成完了を待機しています...')
         if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
         swytch = router.get_swytch()
     else:
         print('既存のルータ+スイッチを取得しています...')
         swytches = api.swytch.with_name_like('saklient-static-1').limit(1).find()
         self.assertEqual(len(swytches), 1)
         swytch = swytches[0]
     
     self.assertIsInstance(swytch, Swytch)
     self.assertEqual(len(swytch.ipv4_nets), 1)
     self.assertIsInstance(swytch.ipv4_nets[0], Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets[0].range.as_array), mask_len_cnt-5)
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 0)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-5)
     
     #
     print('サーバを作成しています...')
     server = api.server.create()
     self.assertIsInstance(server, Server)
     server.name = name
     server.description = description
     server.plan = api.product.server.get_by_spec(1, 1)
     server.save()
     self.assertTrue(0 < int(server.id))
      
     #
     print('インタフェースを増設しています...')
     iface = server.add_iface()
     self.assertIsInstance(iface, Iface)
     self.assertTrue(0 < int(iface.id))
     
     #
     print('インタフェースをルータ+スイッチに接続しています...')
     iface.connect_to_swytch(swytch)
     
     #
     print('インタフェースにIPアドレスを設定しています...')
     iface.user_ip_address = swytch.ipv4_nets[0].range.as_array[1]
     iface.save()
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 1)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-6)
     
     #
     print('ルータ+スイッチの帯域プランを変更しています...')
     router_id_before = swytch.router.id
     swytch.change_plan(500 if swytch.router.band_width_mbps==100 else 100)
     self.assertNotEqual(swytch.router.id, router_id_before)
     
     #
     print('ルータ+スイッチにIPv6ネットワークを割り当てています...')
     v6net = swytch.add_ipv6_net()
     self.assertIsInstance(v6net, Ipv6Net)
     self.assertEqual(len(swytch.ipv6_nets), 1)
     
     #
     print('ルータ+スイッチにスタティックルートを割り当てています...')
     net0 = swytch.ipv4_nets[0]
     next_hop = Util.long2ip(Util.ip2long(net0.address) + 4)
     sroute = swytch.add_static_route(28, next_hop)
     self.assertIsInstance(sroute, Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets), 2)
     self.assertEqual(len(swytch.ipv4_nets[1].range.as_array), sroute_mask_len_cnt)
     
     #
     for i in range(len(swytch.ipv4_nets) - 1, 0, -1):
         print('ルータ+スイッチからスタティックルートの割当を解除しています...')
         net = swytch.ipv4_nets[i]
         swytch.remove_static_route(net)
     
     #
     if 0 < len(swytch.ipv6_nets):
         print('ルータ+スイッチからIPv6ネットワークの割当を解除しています...')
         swytch.remove_ipv6_net()
     
     #
     print('サーバを削除しています...')
     server.destroy()
Exemplo n.º 16
0
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])

        # create a LB
        print('GSLBを作成しています...')
        gslb = api.common_service_item.create_gslb("http", 10, True)
        self.assertIsInstance(gslb, Gslb)
        gslb.path_to_check = '/index.html'
        gslb.response_expected = 200
        gslb.name = name
        gslb.description = 'This is a test'
        gslb.save()
        id = gslb.id
        self.assertTrue(int(id) > 0)
        self.assertEqual(gslb.name, name)
        self.assertEqual(len(gslb.servers), 0)

        gslb = api.common_service_item.get_by_id(id)
        self.assertEqual(gslb.id, id)
        self.assertEqual(gslb.path_to_check, '/index.html')
        self.assertEqual(gslb.response_expected, 200)
        self.assertEqual(gslb.name, name)
        self.assertEqual(len(gslb.servers), 0)

        server = gslb.add_server()
        server.enabled = True
        server.weight = 10
        server.ip_address = "49.212.82.90"
        gslb.save()
        self.assertEqual(len(gslb.servers), 1)

        gslb = api.common_service_item.get_by_id(id)
        self.assertEqual(len(gslb.servers), 1)

        print('GSLBを削除しています...')
        gslb.destroy()

        self.assertRaises(HttpNotFoundException,
                          lambda: api.common_service_item.get_by_id(id))
Exemplo n.º 17
0
 def validation_test():
     server = API.authorize("a", "a").server.create()
     server.name = ["abc"]
Exemplo n.º 18
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
     # 未定義または読み取り専用フィールドへのset時は AttributeError がスローされなければなりません
     
     #
     self.assertEqual(Util.ip2long('0.0.0.0'), 0)
     self.assertEqual(Util.ip2long('127.255.255.255'), 0x7FFFFFFF)
     self.assertEqual(Util.ip2long('128.0.0.0'), 0x80000000)
     self.assertEqual(Util.ip2long('255.255.255.255'), 0xFFFFFFFF)
     self.assertEqual(Util.ip2long('222.173.190.239'), 0xDEADBEEF)
     #
     self.assertEqual(Util.long2ip(0), '0.0.0.0')
     self.assertEqual(Util.long2ip(0x7FFFFFFF), '127.255.255.255')
     self.assertEqual(Util.long2ip(0x80000000), '128.0.0.0')
     self.assertEqual(Util.long2ip(0xFFFFFFFF), '255.255.255.255')
     self.assertEqual(Util.long2ip(0xDEADBEEF), '222.173.190.239')
     self.assertEqual(Util.long2ip(Util.ip2long('127.255.255.255') + 1), '128.0.0.0')
     #
     self.assertIsNone(Util.ip2long(None))
     self.assertIsNone(Util.ip2long(0))
     self.assertIsNone(Util.ip2long(''))
     self.assertIsNone(Util.ip2long('x'))
     self.assertIsNone(Util.ip2long('0.0.0'))
     self.assertIsNone(Util.ip2long('0.0.0.x'))
     self.assertIsNone(Util.ip2long('0.0.0.0.0'))
     self.assertIsNone(Util.ip2long('255.255.255.256'))
     self.assertIsNone(Util.ip2long('256.255.255.255'))
     self.assertIsNone(Util.long2ip(None))
     self.assertEqual(Util.long2ip('0'), '0.0.0.0')
     self.assertEqual(Util.long2ip(Util.ip2long('0.0.0.0') - 1), '255.255.255.255')
     self.assertIsNone(Util.long2ip(Util.ip2long('255.255.255.255') + 1))
Exemplo n.º 19
0
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])
        description = 'This instance was created by saklient.python test'

        #
        print('creating a swytch...')
        swytch = api.swytch.create()
        self.assertIsInstance(swytch, Swytch)
        swytch.name = name
        swytch.description = description
        swytch.save()
        self.assertTrue(0 < int(swytch.id))

        #
        print('creating a server...')
        server = api.server.create()
        self.assertIsInstance(server, Server)
        server.name = name
        server.description = description
        server.plan = api.product.server.get_by_spec(1, 1)
        server.save()
        self.assertTrue(0 < int(server.id))

        #
        print('adding an interface to the server...')
        iface = server.add_iface()
        self.assertIsInstance(iface, Iface)
        self.assertTrue(0 < int(iface.id))
        self.assertEqual(iface.server_id, server.id)
        server.reload()
        self.assertEqual(server.ifaces[0].id, iface.id)
        self.assertEqual(server.ifaces[0].server_id, server.id)
        iface.reload()
        self.assertEqual(iface.swytch_id, None)

        #
        print('connecting the interface to the swytch...')
        iface.connect_to_swytch(swytch)
        self.assertEqual(iface.swytch_id, swytch.id)
        self.assertEqual(api.swytch.get_by_id(iface.swytch_id).id, swytch.id)

        #
        print('disconnecting the interface from the swytch...')
        iface.disconnect_from_swytch()

        # delete the server
        print('deleting the server...')
        server.destroy()

        # delete the swytch
        print('deleting the swytch...')
        swytch.destroy()
Exemplo n.º 20
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     
     # search a switch
     print('searching a swytch...')
     swytches = api.swytch.with_tag('lb-attached').limit(1).find()
     self.assertTrue(len(swytches) > 0)
     swytch = swytches[0]
     self.assertIsInstance(swytch, Swytch)
     self.assertTrue(len(swytch.ipv4_nets) > 0)
     net = swytch.ipv4_nets[0]
     print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))
     
     # create a loadbalancer
     print('creating a LB...')
     vrid = 123
     lb = api.appliance.create_load_balancer(swytch, vrid, ['133.242.255.244', '133.242.255.245'], True)
     
     def test_required():
         lb.save()
     self.assertRaises(SaklientException, test_required)
     # Requiredフィールドが未set時は SaklientException がスローされなければなりません
     lb.name = name
     lb.description = ''
     lb.tags = [tag]
     lb.save()
     
     lb.reload()
     self.assertEqual(lb.default_route, net.default_route)
     self.assertEqual(lb.mask_len, net.mask_len)
     self.assertEqual(lb.vrid, vrid)
     self.assertEqual(lb.swytch_id, swytch.id)
     
     # wait the LB becomes up
     print('waiting the LB becomes up...')
     if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')
     
     # stop the LB
     time.sleep(1)
     print('stopping the LB...')
     if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')
     
     # delete the LB
     print('deleting the LB...')
     lb.destroy()
Exemplo n.º 22
0
 def immutable_test():
     server = API.authorize("a", "a").server.create()
     server.availability = "available"
Exemplo n.º 23
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
     # 未定義または読み取り専用フィールドへのset時は AttributeError がスローされなければなりません
     
     #
     self.assertEqual(Util.ip2long('0.0.0.0'), 0)
     self.assertEqual(Util.ip2long('127.255.255.255'), 0x7FFFFFFF)
     self.assertEqual(Util.ip2long('128.0.0.0'), 0x80000000)
     self.assertEqual(Util.ip2long('255.255.255.255'), 0xFFFFFFFF)
     self.assertEqual(Util.ip2long('222.173.190.239'), 0xDEADBEEF)
     #
     self.assertEqual(Util.long2ip(0), '0.0.0.0')
     self.assertEqual(Util.long2ip(0x7FFFFFFF), '127.255.255.255')
     self.assertEqual(Util.long2ip(0x80000000), '128.0.0.0')
     self.assertEqual(Util.long2ip(0xFFFFFFFF), '255.255.255.255')
     self.assertEqual(Util.long2ip(0xDEADBEEF), '222.173.190.239')
     self.assertEqual(Util.long2ip(Util.ip2long('127.255.255.255') + 1), '128.0.0.0')
     #
     self.assertIsNone(Util.ip2long(None))
     self.assertIsNone(Util.ip2long(0))
     self.assertIsNone(Util.ip2long(''))
     self.assertIsNone(Util.ip2long('x'))
     self.assertIsNone(Util.ip2long('0.0.0'))
     self.assertIsNone(Util.ip2long('0.0.0.x'))
     self.assertIsNone(Util.ip2long('0.0.0.0.0'))
     self.assertIsNone(Util.ip2long('255.255.255.256'))
     self.assertIsNone(Util.ip2long('256.255.255.255'))
     self.assertIsNone(Util.long2ip(None))
     self.assertEqual(Util.long2ip('0'), '0.0.0.0')
     self.assertEqual(Util.long2ip(Util.ip2long('0.0.0.0') - 1), '255.255.255.255')
     self.assertIsNone(Util.long2ip(Util.ip2long('255.255.255.255') + 1))