Example #1
0
    def process(self):
        self.manual = Help()
        if self.__help():
            return

        self.result = DataCollector()
        self.out = DataOutput(
            self.result,
            self.global_args['--output-format'],
            self.global_args['--output-style']
        )

        self.load_config()

        self.account = AzureAccount(self.config)
        self.storage_account = StorageAccount(self.account)

        if self.command_args['--name']:
            self.validate_account_name()
        if self.command_args['--description']:
            self.validate_description()
        if self.command_args['--label']:
            self.validate_label()

        if self.command_args['create']:
            self.__create()
        elif self.command_args['update']:
            self.__update()
        elif self.command_args['show']:
            self.__show()
        elif self.command_args['list']:
            self.__list()
        elif self.command_args['delete']:
            self.__delete()
        elif self.command_args['regions']:
            self.__list_locations()
        self.out.display()
Example #2
0
    def setup(self):
        account = AzureAccount(
            Config(
                region_name='East US 2', filename='../data/config'
            )
        )
        self.service = mock.Mock()
        account.get_management_service = mock.Mock(return_value=self.service)
        account.get_blob_service_host_base = mock.Mock(
            return_value='.blob.test.url'
        )
        account.storage_key = mock.Mock()

        self.containers_list = ['container_a', 'container_b']
        self.mock_storage_service = mock.Mock(
            storage_service_keys=None,
            storage_service_properties=mock.Mock(
                status='Created',
                account_type='Standard_GRS',
                description='mock storage service',
                geo_secondary_region='West US',
                creation_time='2015-12-09T07:53:54Z',
                geo_primary_region='East US 2',
                label='mockstorageservice',
                status_of_primary='Available',
                location='East US 2',
                affinity_group='',
                last_geo_failover_time='',
                status_of_secondary='Available',
                endpoints=[
                    'https://mockstorageservice.blob.core.windows.net/',
                    'https://mockstorageservice.queue.core.windows.net/',
                    'https://mockstorageservice.table.core.windows.net/',
                    'https://mockstorageservice.file.core.windows.net/'
                ],
                geo_replication_enabled='True'
            ),
            url=(
                'https://management.core.windows.net/' +
                '00000000-0000-0000-0000-000000000000/services/' +
                'storageservices/mockstorageservice'
            ),
            service_name='mockstorageservice',
            capabilities='None',
            extended_properties={
                'ResourceGroup': 'Default-Storage-EastUS2',
                'ResourceLocation': 'East US 2'
            },
            containers=None
        )
        self.keyed_service = mock.Mock(
            storage_service_keys=mock.Mock(
                primary='1234567890abcdef==',
                secondary='fedcba0987654321=='
            )
        )
        self.expected_list_result = [{
            "backup": {
                "backup-region": "West US",
                "backup-region-status": "Available",
                "last-failover": "",
                "status": "Available"
            },
            "backup-strategy": "--geo-redundant",
            "description": "mock storage service",
            "endpoints": [
                "https://mockstorageservice.blob.core.windows.net/",
                "https://mockstorageservice.queue.core.windows.net/",
                "https://mockstorageservice.table.core.windows.net/",
                "https://mockstorageservice.file.core.windows.net/"
            ],
            "label": "mockstorageservice",
            "name": "mockstorageservice",
            "region": "East US 2",
            "status": "Created"
        }]
        self.expected_show_result = {
            "backup": {
                "backup-region": "West US",
                "backup-region-status": "Available",
                "last-failover": "",
                "status": "Available"
            },
            "backup-strategy": "--geo-redundant",
            "containers": self.containers_list,
            "description": "mock storage service",
            "endpoints": [
                "https://mockstorageservice.blob.core.windows.net/",
                "https://mockstorageservice.queue.core.windows.net/",
                "https://mockstorageservice.table.core.windows.net/",
                "https://mockstorageservice.file.core.windows.net/"
            ],
            "keys": {
                "primary": self.keyed_service.storage_service_keys.primary,
                "secondary": self.keyed_service.storage_service_keys.secondary
            },
            "label": "mockstorageservice",
            "name": "mockstorageservice",
            "region": "East US 2",
            "status": "Created"
        }

        self.my_request = mock.Mock(request_id=Defaults.unify_id(42))

        self.storage_account = StorageAccount(account)
Example #3
0
class TestStorageAccount:
    def setup(self):
        account = AzureAccount(
            Config(
                region_name='East US 2', filename='../data/config'
            )
        )
        self.service = mock.Mock()
        account.get_management_service = mock.Mock(return_value=self.service)
        account.get_blob_service_host_base = mock.Mock(
            return_value='.blob.test.url'
        )
        account.storage_key = mock.Mock()

        self.containers_list = ['container_a', 'container_b']
        self.mock_storage_service = mock.Mock(
            storage_service_keys=None,
            storage_service_properties=mock.Mock(
                status='Created',
                account_type='Standard_GRS',
                description='mock storage service',
                geo_secondary_region='West US',
                creation_time='2015-12-09T07:53:54Z',
                geo_primary_region='East US 2',
                label='mockstorageservice',
                status_of_primary='Available',
                location='East US 2',
                affinity_group='',
                last_geo_failover_time='',
                status_of_secondary='Available',
                endpoints=[
                    'https://mockstorageservice.blob.core.windows.net/',
                    'https://mockstorageservice.queue.core.windows.net/',
                    'https://mockstorageservice.table.core.windows.net/',
                    'https://mockstorageservice.file.core.windows.net/'
                ],
                geo_replication_enabled='True'
            ),
            url=(
                'https://management.core.windows.net/' +
                '00000000-0000-0000-0000-000000000000/services/' +
                'storageservices/mockstorageservice'
            ),
            service_name='mockstorageservice',
            capabilities='None',
            extended_properties={
                'ResourceGroup': 'Default-Storage-EastUS2',
                'ResourceLocation': 'East US 2'
            },
            containers=None
        )
        self.keyed_service = mock.Mock(
            storage_service_keys=mock.Mock(
                primary='1234567890abcdef==',
                secondary='fedcba0987654321=='
            )
        )
        self.expected_list_result = [{
            "backup": {
                "backup-region": "West US",
                "backup-region-status": "Available",
                "last-failover": "",
                "status": "Available"
            },
            "backup-strategy": "--geo-redundant",
            "description": "mock storage service",
            "endpoints": [
                "https://mockstorageservice.blob.core.windows.net/",
                "https://mockstorageservice.queue.core.windows.net/",
                "https://mockstorageservice.table.core.windows.net/",
                "https://mockstorageservice.file.core.windows.net/"
            ],
            "label": "mockstorageservice",
            "name": "mockstorageservice",
            "region": "East US 2",
            "status": "Created"
        }]
        self.expected_show_result = {
            "backup": {
                "backup-region": "West US",
                "backup-region-status": "Available",
                "last-failover": "",
                "status": "Available"
            },
            "backup-strategy": "--geo-redundant",
            "containers": self.containers_list,
            "description": "mock storage service",
            "endpoints": [
                "https://mockstorageservice.blob.core.windows.net/",
                "https://mockstorageservice.queue.core.windows.net/",
                "https://mockstorageservice.table.core.windows.net/",
                "https://mockstorageservice.file.core.windows.net/"
            ],
            "keys": {
                "primary": self.keyed_service.storage_service_keys.primary,
                "secondary": self.keyed_service.storage_service_keys.secondary
            },
            "label": "mockstorageservice",
            "name": "mockstorageservice",
            "region": "East US 2",
            "status": "Created"
        }

        self.my_request = mock.Mock(request_id=Defaults.unify_id(42))

        self.storage_account = StorageAccount(account)

    def test_list(self):
        self.service.list_storage_accounts.return_value = [
            self.mock_storage_service
        ]
        result = self.storage_account.list()
        assert result == self.expected_list_result

    def test_exists_false(self):
        self.service.get_storage_account_properties.side_effect = Exception
        assert self.storage_account.exists('some-name') is False

    def test_exists_true(self):
        assert self.storage_account.exists('some-name') is True

    def test_list_error(self):
        self.service.list_storage_accounts.side_effect = Exception
        with raises(AzureStorageAccountListError):
            self.storage_account.list()

    @patch('azurectl.storage.account.Container.list')
    def test_show(self, mock_container_list):
        self.service.get_storage_account_keys.return_value = \
            self.keyed_service
        self.service.get_storage_account_properties.return_value = \
            self.mock_storage_service
        mock_container_list.return_value = self.containers_list
        result = self.storage_account.show(
            self.mock_storage_service.service_name
        )
        assert result == self.expected_show_result

    def test_show_error(self):
        self.service.get_storage_account_properties.side_effect = Exception
        with raises(AzureStorageAccountShowError):
            self.storage_account.show('mockstorageservice')

    def test_show_add_keys_error(self):
        self.service.get_storage_account_keys.side_effect = Exception
        self.service.get_storage_account_properties.return_value = \
            self.mock_storage_service
        with raises(AzureStorageAccountShowError):
            self.storage_account.show('mockstorageservice')

    def test_create(self):
        self.service.create_storage_account.return_value = self.my_request
        result = self.storage_account.create(
            'mockstorageservice',
            None,
            None,
            '--locally-redundant'
        )
        assert result == self.my_request.request_id

    def test_create_error(self):
        self.service.create_storage_account.side_effect = Exception
        with raises(AzureStorageAccountCreateError):
            result = self.storage_account.create(
                'mockstorageservice',
                None,
                None,
                '--locally-redundant'
            )

    @patch('azurectl.storage.account.Container.list')
    def test_basic_update(self, mock_container_list):
        self.service.update_storage_account.return_value = \
            self.my_request
        self.service.get_storage_account_keys.return_value = \
            self.keyed_service
        self.service.get_storage_account_properties.return_value = \
            self.mock_storage_service
        mock_container_list.return_value = self.containers_list
        result = self.storage_account.update(
            'mockstorageservice',
            None,
            None,
            '--locally-redundant'
        )
        assert result == self.my_request.request_id

    def test_update_error(self):
        self.service.update_storage_account.side_effect = Exception
        with raises(AzureStorageAccountUpdateError):
            result = self.storage_account.update(
                'mockstorageservice',
                None,
                None,
                '--locally-redundant'
            )

    @patch('azurectl.storage.account.Container.list')
    def test_update_keys(self, mock_container_list):
        self.service.regenerate_storage_account_keys.return_value = \
            self.my_request
        self.service.update_storage_account.return_value = \
            self.my_request
        self.service.get_storage_account_keys.return_value = \
            self.keyed_service
        self.service.get_storage_account_properties.return_value = \
            self.mock_storage_service
        mock_container_list.return_value = self.containers_list

        # primary key
        result = self.storage_account.update(
            'mockstorageservice',
            None,
            None,
            '--locally-redundant',
            regenerate_primary_key=True
        )
        self.service.regenerate_storage_account_keys.assert_called_with(
            'mockstorageservice',
            'Primary'
        )

        # secondary key
        result = self.storage_account.update(
            'mockstorageservice',
            None,
            None,
            '--locally-redundant',
            regenerate_secondary_key=True
        )
        self.service.regenerate_storage_account_keys.assert_called_with(
            'mockstorageservice',
            'Secondary'
        )

    def test_delete(self):
        self.service.delete_storage_account.return_value = self.my_request
        result = self.storage_account.delete('mockstorageservice')
        assert result == self.my_request.request_id

    def test_delete_error(self):
        self.service.delete_storage_account.side_effect = Exception
        with raises(AzureStorageAccountDeleteError):
            self.storage_account.delete('mockstorageservice')
Example #4
0
class StorageAccountTask(CliTask):
    """
        Process commands on storage accounts
    """
    def process(self):
        self.manual = Help()
        if self.__help():
            return

        self.result = DataCollector()
        self.out = DataOutput(
            self.result,
            self.global_args['--output-format'],
            self.global_args['--output-style']
        )

        self.load_config()

        self.account = AzureAccount(self.config)
        self.storage_account = StorageAccount(self.account)

        if self.command_args['--name']:
            self.validate_account_name()
        if self.command_args['--description']:
            self.validate_description()
        if self.command_args['--label']:
            self.validate_label()

        if self.command_args['create']:
            self.__create()
        elif self.command_args['update']:
            self.__update()
        elif self.command_args['show']:
            self.__show()
        elif self.command_args['list']:
            self.__list()
        elif self.command_args['delete']:
            self.__delete()
        elif self.command_args['regions']:
            self.__list_locations()
        self.out.display()

    # argument validation
    def validate_account_name(self, cmd_arg='--name'):
        valid_chars = set(string.ascii_lowercase + string.digits)
        if (set(self.command_args[cmd_arg]) - valid_chars):
            raise AzureInvalidCommand(
                '%s contains invalid characters. ' % cmd_arg +
                'Only lowercase letters and digits are allowed.')
        self.validate_min_length(cmd_arg, 3)
        self.validate_max_length(cmd_arg, 24)

    def validate_description(self, cmd_arg='--description'):
        self.validate_max_length(cmd_arg, 1024)

    def validate_label(self, cmd_arg='--label'):
        self.validate_max_length(cmd_arg, 100)

    # tasks
    def __help(self):
        if self.command_args['help']:
            self.manual.show('azurectl::storage::account')
        else:
            return False
        return self.manual

    def __create(self):
        request_id = self.storage_account.create(
            self.command_args['--name'],
            self.command_args['--description'],
            self.command_args['--label'],
            Defaults.account_type_for_docopts(self.command_args)
        )
        if self.command_args['--wait']:
            self.request_wait(request_id)
        self.result.add(
            'storage_account:' + self.command_args['--name'],
            request_id
        )

    def __update(self):
        request_id = self.storage_account.update(
            self.command_args['--name'],
            self.command_args['--description'],
            self.command_args['--label'],
            Defaults.account_type_for_docopts(self.command_args, False),
            self.command_args['--new-primary-key'],
            self.command_args['--new-secondary-key']
        )
        if self.command_args['--wait']:
            self.request_wait(request_id)
        self.result.add(
            'storage_account:' + self.command_args['--name'],
            request_id
        )

    def __show(self):
        self.result.add(
            'storage_account:' + self.command_args['--name'],
            self.storage_account.show(self.command_args['--name'])
        )

    def __list(self):
        self.result.add('storage_accounts', self.storage_account.list())

    def __delete(self):
        request_id = self.storage_account.delete(
            self.command_args['--name']
        )
        if self.command_args['--wait']:
            self.request_wait(request_id)
        self.result.add(
            'storage_account:' + self.command_args['--name'],
            request_id
        )

    def __list_locations(self):
        self.result.add('regions', self.account.locations('Storage'))
Example #5
0
    def __configure_account(self):
        self.__check_account_existing_in_default_config()
        self.setup.configure_account(
            self.command_args['--name'],
            self.command_args['--publish-settings-file'],
            self.command_args['--region'],
            self.command_args['--storage-account-name'],
            self.command_args['--container-name'],
            self.command_args['--subscription-id'],
            self.command_args['--management-pem-file'],
            self.command_args['--management-url']
        )
        self.setup.write()
        log.info(
            'Added account %s', self.command_args['--name']
        )
        if self.command_args['--create']:
            self.global_args['--account'] = self.command_args['--name']
            self.load_config()
            self.account = AzureAccount(self.config)
            self.__load_account_setup(
                self.command_args['--name']
            )

            try:
                storage_account_name = \
                    self.command_args['--storage-account-name']
                storage_account = StorageAccount(self.account)
                if not storage_account.exists(storage_account_name):
                    storage_account_request_id = storage_account.create(
                        name=storage_account_name,
                        description=self.command_args['--name'],
                        label=self.command_args['--storage-account-name'],
                        account_type=Defaults.account_type_for_docopts(
                            self.command_args
                        )
                    )
                    self.request_wait(storage_account_request_id)
                    log.info(
                        'Created %s storage account', storage_account_name
                    )
                else:
                    log.info(
                        'Storage account %s already exists',
                        storage_account_name
                    )

                container_name = self.command_args['--container-name']
                container = Container(self.account)
                if not container.exists(container_name):
                    container.create(container_name)
                    log.info(
                        'Created %s container', container_name
                    )
                else:
                    log.info(
                        'Container %s already exists', container_name
                    )
            except Exception as e:
                self.__remove()
                raise AzureAccountConfigurationError(
                    '%s: %s' % (type(e).__name__, format(e))
                )