예제 #1
0
파일: test_parser.py 프로젝트: vladikr/heat
    def test_schema_invariance(self):
        params1 = parser.Parameters('test', params_schema)
        params1['Defaulted'] = "wibble"
        self.assertEqual(params1['Defaulted'], 'wibble')

        params2 = parser.Parameters('test', params_schema)
        self.assertEqual(params2['Defaulted'], 'foobar')
예제 #2
0
    def test_stack_create_verify_err(self):
        stack_name = 'service_create_verify_err_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')
        self.m.StubOutWithMock(parser, 'Stack')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name, stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name, stack.t,
                     stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        stack.validate().AndRaise(
            exception.StackValidationFailed(message='fubar'))

        self.m.ReplayAll()

        self.assertRaises(exception.StackValidationFailed,
                          self.man.create_stack, self.ctx, stack_name,
                          template, params, {})
        self.m.VerifyAll()
예제 #3
0
    def test_stack_create_verify_err(self):
        stack_name = 'service_create_verify_err_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')
        self.m.StubOutWithMock(parser, 'Stack')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name,
                          stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name,
                     stack.t, stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        error = 'fubar'
        stack.validate().AndReturn(error)

        #self.m.StubOutWithMock(threadgroup, 'ThreadGroup')
        #threadgroup.ThreadGroup(stack_name).AndReturn(DummyThreadGroup())

        self.m.ReplayAll()

        result = self.man.create_stack(self.ctx, stack_name,
                                       template, params, {})
        self.assertEqual(result, {'Description': error})
        self.m.VerifyAll()
예제 #4
0
    def test_stack_update(self):
        stack_name = 'service_update_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        old_stack = get_wordpress_stack(stack_name, self.ctx)
        sid = old_stack.store()
        s = db_api.stack_get(self.ctx, sid)

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Stack')
        self.m.StubOutWithMock(parser.Stack, 'load')
        parser.Stack.load(self.ctx, stack=s).AndReturn(old_stack)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name, stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name, stack.t,
                     stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        stack.validate().AndReturn(None)

        self.m.ReplayAll()

        result = self.man.update_stack(self.ctx, old_stack.identifier(),
                                       template, params, {})
        self.assertEqual(result, old_stack.identifier())
        self.assertTrue(isinstance(result, dict))
        self.assertTrue(result['stack_id'])
        self.m.VerifyAll()
예제 #5
0
파일: service.py 프로젝트: jordant/heat
    def validate_template(self, cnxt, template):
        """
        The validate_template method uses the stack parser to check
        the validity of a template.

        arg1 -> RPC context.
        arg3 -> Template of stack you want to create.
        arg4 -> Stack Input Params
        """
        logger.info('validate_template')
        if template is None:
            msg = _("No Template provided.")
            return webob.exc.HTTPBadRequest(explanation=msg)

        tmpl = parser.Template(template)
        tmpl_resources = template.get('Resources', [])

        if not tmpl_resources:
            return {'Error': 'At least one Resources member must be defined.'}

        for res in tmpl_resources.values():
            if not res.get('Type'):
                return {'Error':
                        'Every Resources object must contain a Type member.'}

        tmpl_params = parser.Parameters(None, tmpl)
        format_validate_parameter = lambda p: dict(p.schema)
        is_real_param = lambda p: p.name not in parameters.PSEUDO_PARAMETERS
        params = tmpl_params.map(format_validate_parameter, is_real_param)

        result = {
            'Description': template.get('Description', ''),
            'Parameters': params,
        }
        return result
예제 #6
0
    def test_stack_update_verify_err(self):
        stack_name = 'service_update_verify_err_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        old_stack = get_wordpress_stack(stack_name, self.ctx)
        old_stack.store()
        sid = old_stack.store()
        s = db_api.stack_get(self.ctx, sid)

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Stack')
        self.m.StubOutWithMock(parser.Stack, 'load')
        parser.Stack.load(self.ctx, stack=s).AndReturn(old_stack)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name, stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name, stack.t,
                     stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        stack.validate().AndRaise(
            exception.StackValidationFailed(message='fubar'))

        self.m.ReplayAll()

        self.assertRaises(exception.StackValidationFailed,
                          self.man.update_stack, self.ctx,
                          old_stack.identifier(), template, params, {})
        self.m.VerifyAll()
예제 #7
0
    def test_stack_create(self):
        stack_name = 'service_create_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')
        self.m.StubOutWithMock(parser, 'Stack')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name, stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name, stack.t,
                     stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        stack.validate().AndReturn(None)

        self.m.StubOutWithMock(threadgroup, 'ThreadGroup')
        threadgroup.ThreadGroup().AndReturn(DummyThreadGroup())

        self.m.ReplayAll()

        result = self.man.create_stack(self.ctx, stack_name, template, params,
                                       {})
        self.assertEqual(result, stack.identifier())
        self.assertTrue(isinstance(result, dict))
        self.assertTrue(result['stack_id'])
        self.m.VerifyAll()
예제 #8
0
    def create_with_template(self,
                             child_template,
                             user_params,
                             timeout_mins=None):
        '''
        Handle the creation of the nested stack from a given JSON template.
        '''
        template = parser.Template(child_template)
        params = parser.Parameters(self.physical_resource_name(), template,
                                   user_params)

        # Note we disable rollback for nested stacks, since they
        # should be rolled back by the parent stack on failure
        self._nested = parser.Stack(self.context,
                                    self.physical_resource_name(),
                                    template,
                                    params,
                                    timeout_mins=timeout_mins,
                                    disable_rollback=True)

        nested_id = self._nested.store(self.stack)
        self.resource_id_set(nested_id)

        stack_creator = scheduler.TaskRunner(self._nested.create_task)
        stack_creator.start(timeout=self._nested.timeout_secs())
        return stack_creator
예제 #9
0
    def _setup_test_instance(self, return_server, name):
        stack_name = '%s_stack' % name
        t = template_format.parse(wp_template)
        template = parser.Template(t)
        params = parser.Parameters(stack_name, template, {'KeyName': 'test'})
        stack = parser.Stack(None, stack_name, template, params,
                             stack_id=uuidutils.generate_uuid())

        t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'
        t['Resources']['WebServer']['Properties']['InstanceType'] = \
            '256 MB Server'
        instance = instances.Instance('%s_name' % name,
                                      t['Resources']['WebServer'], stack)

        self.m.StubOutWithMock(instance, 'nova')
        instance.nova().MultipleTimes().AndReturn(self.fc)

        instance.t = instance.stack.resolve_runtime_data(instance.t)

        # need to resolve the template functions
        server_userdata = instance._build_userdata(
            instance.t['Properties']['UserData'])
        self.m.StubOutWithMock(self.fc.servers, 'create')
        self.fc.servers.create(
            image=1, flavor=1, key_name='test',
            name=utils.PhysName(stack_name, instance.name),
            security_groups=None,
            userdata=server_userdata, scheduler_hints=None,
            meta=None, nics=None, availability_zone=None).AndReturn(
                return_server)

        return instance
예제 #10
0
    def create_stack(self, stack_name='test_stack2', params={}):
        temp = template_format.parse(test_template_waitcondition)
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, params)
        ctx = context.get_admin_context()
        ctx.tenant_id = 'test_tenant'
        stack = parser.Stack(ctx,
                             stack_name,
                             template,
                             parameters,
                             disable_rollback=True)
        # Stub out the UUID for this test, so we can get an expected signature
        self.m.StubOutWithMock(uuid, 'uuid4')
        uuid.uuid4().AndReturn('STACKABCD1234')
        self.m.ReplayAll()
        stack.store()

        # Stub waitcondition status so all goes CREATE_COMPLETE
        self.m.StubOutWithMock(wc.WaitConditionHandle, 'get_status')
        wc.WaitConditionHandle.get_status().AndReturn(['SUCCESS'])

        # Stub keystone() with fake client
        self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone')
        wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(self.fc)

        id = identifier.ResourceIdentifier('test_tenant', stack.name, stack.id,
                                           '', 'WaitHandle')
        self.m.StubOutWithMock(wc.WaitConditionHandle, 'identifier')
        wc.WaitConditionHandle.identifier().MultipleTimes().AndReturn(id)

        self.m.ReplayAll()
        stack.create()

        return stack
예제 #11
0
    def create_stack(self,
                     stack_name='test_stack',
                     template=test_template_metadata,
                     params={},
                     stub=True):
        temp = template_format.parse(template)
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, params)
        ctx = context.get_admin_context()
        ctx.tenant_id = 'test_tenant'
        stack = parser.Stack(ctx,
                             stack_name,
                             template,
                             parameters,
                             disable_rollback=True)

        self.stack_id = stack.store()

        if stub:
            self.m.StubOutWithMock(instance.Instance, 'handle_create')
            self.m.StubOutWithMock(instance.Instance, 'check_active')
            instance.Instance.handle_create().AndReturn(None)
            instance.Instance.check_active(None).AndReturn(True)
            self.m.StubOutWithMock(instance.Instance, 'FnGetAtt')

        return stack
예제 #12
0
    def test_stack_create(self):
        stack_name = 'manager_create_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')
        self.m.StubOutWithMock(parser, 'Stack')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name,
                          stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name,
                     stack.t, stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        stack.validate().AndReturn({'Description': 'Successfully validated'})

        self.m.StubOutWithMock(manager.greenpool, 'spawn')
        manager.greenpool.spawn(stack.create).AndReturn(DummyGreenThread())

        self.m.ReplayAll()

        result = self.man.create_stack(self.ctx, stack_name,
                                       template, params, {})
        self.assertEqual(result, stack.identifier())
        self.assertTrue(isinstance(result, dict))
        self.assertTrue(result['stack_id'])
        self.m.VerifyAll()
예제 #13
0
    def update_stack(self, cnxt, stack_identity, template, params, args):
        """
        The update_stack method updates an existing stack based on the
        provided template and parameters.
        Note that at this stage the template has already been fetched from the
        heat-api process if using a template-url.
        arg1 -> RPC context.
        arg2 -> Name of the stack you want to create.
        arg3 -> Template of stack you want to create.
        arg4 -> Stack Input Params
        arg4 -> Request parameters/args passed from API
        """
        logger.info('template is %s' % template)

        # Get the database representation of the existing stack
        db_stack = self._get_stack(cnxt, stack_identity)

        current_stack = parser.Stack.load(cnxt, stack=db_stack)

        # Now parse the template and any parameters for the updated
        # stack definition.
        tmpl = parser.Template(template)
        stack_name = current_stack.name
        template_params = parser.Parameters(stack_name, tmpl, params)
        common_params = api.extract_args(args)

        updated_stack = parser.Stack(cnxt, stack_name, tmpl, template_params,
                                     **common_params)

        updated_stack.validate()

        self._start_in_thread(db_stack.id, current_stack.update, updated_stack)

        return dict(current_stack.identifier())
예제 #14
0
    def test_stack_create_verify_err(self):
        stack_name = 'manager_create_verify_err_test_stack'
        params = {'foo': 'bar'}
        template = '{ "Template": "data" }'

        stack = get_wordpress_stack(stack_name, self.ctx)

        self.m.StubOutWithMock(parser, 'Template')
        self.m.StubOutWithMock(parser, 'Parameters')
        self.m.StubOutWithMock(parser, 'Stack')

        parser.Template(template).AndReturn(stack.t)
        parser.Parameters(stack_name,
                          stack.t,
                          params).AndReturn(stack.parameters)
        parser.Stack(self.ctx, stack.name,
                     stack.t, stack.parameters).AndReturn(stack)

        self.m.StubOutWithMock(stack, 'validate')
        error = {'Description': 'fubar'}
        stack.validate().AndReturn(error)

        self.m.StubOutWithMock(manager.greenpool, 'spawn')

        self.m.ReplayAll()

        result = self.man.create_stack(self.ctx, stack_name,
                                       template, params, {})
        self.assertEqual(result, error)
        self.m.VerifyAll()
예제 #15
0
def get_wordpress_stack(stack_name, ctx):
    t = template_format.parse(wp_template)
    template = parser.Template(t)
    parameters = parser.Parameters(stack_name, template, {'KeyName': 'test'})

    stack = parser.Stack(ctx, stack_name, template, parameters)
    return stack
예제 #16
0
    def create_stack(self, stack_name='test_stack'):
        temp = template_format.parse(test_template_waitcondition)
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, {})
        stack = parser.Stack(self.ctx,
                             stack_name,
                             template,
                             parameters,
                             disable_rollback=True)

        self.stack_id = stack.store()

        self.m.StubOutWithMock(instance.Instance, 'handle_create')
        self.m.StubOutWithMock(instance.Instance, 'check_create_complete')
        cookie = object()
        instance.Instance.handle_create().AndReturn(cookie)
        instance.Instance.check_create_complete(cookie).AndReturn(True)

        self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone')
        wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(self.fc)

        id = identifier.ResourceIdentifier('test_tenant', stack.name, stack.id,
                                           '', 'WH')
        self.m.StubOutWithMock(wc.WaitConditionHandle, 'identifier')
        wc.WaitConditionHandle.identifier().MultipleTimes().AndReturn(id)

        self.m.StubOutWithMock(eventlet, 'sleep')

        return stack
예제 #17
0
    def create_stack(self,
                     stack_name='test_stack',
                     template=test_template_waitcondition,
                     params={},
                     stub=True):
        temp = template_format.parse(template)
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, params)
        ctx = context.get_admin_context()
        ctx.tenant_id = 'test_tenant'
        stack = parser.Stack(ctx,
                             stack_name,
                             template,
                             parameters,
                             disable_rollback=True)

        self.stack_id = stack.store()

        if stub:
            self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone')
            wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(
                self.fc)

            id = identifier.ResourceIdentifier('test_tenant', stack.name,
                                               stack.id, '', 'WaitHandle')
            self.m.StubOutWithMock(wc.WaitConditionHandle, 'identifier')
            wc.WaitConditionHandle.identifier().MultipleTimes().AndReturn(id)

        return stack
예제 #18
0
    def _create_test_instance_with_nic(self, return_server, name):
        stack_name = '%s_stack' % name
        t = template_format.parse(wp_template_with_nic)
        template = parser.Template(t)
        kwargs = {
            'KeyName': 'test',
            'InstanceType': 'm1.large',
            'SubnetId': '4156c7a5-e8c4-4aff-a6e1-8f3c7bc83861'
        }
        params = parser.Parameters(stack_name, template, kwargs)
        stack = parser.Stack(None,
                             stack_name,
                             template,
                             params,
                             stack_id=uuidutils.generate_uuid())

        t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'

        nic = network_interfaces.NetworkInterface('%s_nic' % name,
                                                  t['Resources']['nic1'],
                                                  stack)

        instance = instances.Instance('%s_name' % name,
                                      t['Resources']['WebServer'], stack)

        self.m.StubOutWithMock(nic, 'quantum')
        nic.quantum().MultipleTimes().AndReturn(FakeQuantum())

        self.m.StubOutWithMock(instance, 'nova')
        instance.nova().MultipleTimes().AndReturn(self.fc)

        nic.t = nic.stack.resolve_runtime_data(nic.t)
        instance.t = instance.stack.resolve_runtime_data(instance.t)

        # need to resolve the template functions
        server_userdata = instance._build_userdata(
            instance.t['Properties']['UserData'])
        self.m.StubOutWithMock(self.fc.servers, 'create')
        self.fc.servers.create(image=1,
                               flavor=3,
                               key_name='test',
                               name=utils.PhysName(stack_name, instance.name),
                               security_groups=None,
                               userdata=server_userdata,
                               scheduler_hints=None,
                               meta=None,
                               nics=[{
                                   'port-id':
                                   '64d913c1-bcb1-42d2-8f0a-9593dbcaf251'
                               }],
                               availability_zone=None).AndReturn(return_server)
        self.m.ReplayAll()

        # create network interface
        scheduler.TaskRunner(nic.create)()
        stack.resources["nic1"] = nic

        scheduler.TaskRunner(instance.create)()
        return instance
예제 #19
0
    def create_stack(self, stack_name, temp, params):
        template = parser.Template(temp)
        parameters = parser.Parameters(stack_name, template, params)
        stack = parser.Stack(context.get_admin_context(), stack_name, template,
                             parameters)

        stack.store()
        return stack
예제 #20
0
    def check_user_data(self, template_file):
        return  # until TODO is fixed

#        transport = self.ssh.get_transport()
#        channel = transport.open_session()
#        channel.get_pty()
#        channel.invoke_shell()  # sudo requires tty
#        channel.sendall('sudo chmod 777 \
#            sudo chmod 777 /var/lib/cloud/instance/user-data.txt.i\n')
#        time.sleep(1)  # necessary for sendall to complete

        f = open(basepath + '/templates/' + template_file)
        t = template_format.parse(f.read())
        f.close()

        template = parser.Template(t)
        params = parser.Parameters('test', t,
                                   {'KeyName': 'required_parameter',
                                    'DBUsername': self.dbusername,
                                    'DBPassword': self.creds['password']})

        stack = parser.Stack(None, 'test', template, params)
        parsed_t = stack.resolve_static_data(t)
        remote_file = self.sftp.open('/var/lib/heat-cfntools/cfn-userdata')
        remote_file_list = remote_file.read().split('\n')
        remote_file_list_u = map(unicode, remote_file_list)
        remote_file.close()

        # TODO: make server name generic
        t_data = parsed_t['Resources']['WikiDatabase']['Properties']
        t_data = t_data['UserData']['Fn::Base64']['Fn::Join'].pop()
        joined_t_data = ''.join(t_data)
        t_data_list = joined_t_data.split('\n')

        self.testcase.assertEqual(t_data_list, remote_file_list_u)

        remote_file = self.sftp.open('/var/lib/cloud/instance/user-data.txt.i')
        msg = email.message_from_file(remote_file)
        remote_file.close()

        filepaths = {
            'cloud-config': basepath + '/heat/cloudinit/config',
            'part-handler.py': basepath +
            '/heat/cloudinit/part-handler.py'
        }

        # check multipart mime accuracy
        for part in msg.walk():
            # multipart/* are just containers
            if part.get_content_maintype() == 'multipart':
                continue

            file = part.get_filename()
            data = part.get_payload()

            if file in filepaths.keys():
                with open(filepaths[file]) as f:
                    self.testcase.assertEqual(data, f.read())
예제 #21
0
    def validate_template(self, cnxt, template):
        """
        The validate_template method uses the stack parser to check
        the validity of a template.

        arg1 -> RPC context.
        arg3 -> Template of stack you want to create.
        arg4 -> Stack Input Params
        """
        logger.info('validate_template')
        if template is None:
            msg = _("No Template provided.")
            return webob.exc.HTTPBadRequest(explanation=msg)

        tmpl = parser.Template(template)
        tmpl_resources = tmpl.get('Resources', [])

        if not tmpl_resources:
            return {'Error': 'At least one Resources member must be defined.'}

        for res in tmpl_resources.values():
            try:
                if not res.get('Type'):
                    return {
                        'Error':
                        'Every Resource object must '
                        'contain a Type member.'
                    }
            except AttributeError:
                type_res = type(res)
                if isinstance(res, unicode):
                    type_res = "string"
                return {
                    'Error':
                    'Resources must contain Resource. '
                    'Found a [%s] instead' % type_res
                }

            ResourceClass = resource.get_class(res['Type'])
            props = properties.Properties(ResourceClass.properties_schema,
                                          res.get('Properties', {}))
            try:
                ResourceClass.validate_deletion_policy(res)
                props.validate(with_value=False)
            except Exception as ex:
                return {'Error': str(ex)}

        tmpl_params = parser.Parameters(None, tmpl, validate_value=False)
        format_validate_parameter = lambda p: dict(p.schema)
        is_real_param = lambda p: p.name not in parameters.PSEUDO_PARAMETERS
        params = tmpl_params.map(format_validate_parameter, is_real_param)

        result = {
            'Description': tmpl.get('Description', ''),
            'Parameters': params,
        }
        return result
예제 #22
0
    def parse_stack(self, t):
        template = parser.Template(t)
        params = parser.Parameters('test_stack', template, {'KeyName': 'test'})
        stack = parser.Stack(create_context(self.m),
                             'test_stack',
                             template,
                             params,
                             stack_id=None)
        stack.store()

        return stack
예제 #23
0
파일: test_volume.py 프로젝트: jordant/heat
    def parse_stack(self, t, stack_name):
        ctx = context.RequestContext.from_dict({
            'tenant': 'test_tenant',
            'username': '******',
            'password': '******',
            'auth_url': 'http://localhost:5000/v2.0'})
        template = parser.Template(t)
        params = parser.Parameters(stack_name, template, {'KeyName': 'test'})
        stack = parser.Stack(ctx, stack_name, template, params)

        return stack
예제 #24
0
    def test_invalid_security_group_ids_with_nics(self):
        t = template_format.parse(test_template_invalid_secgroupids)
        template = parser.Template(t)
        params = parser.Parameters('test_stack', template, {'KeyName': 'test'})
        stack = parser.Stack(None, 'test_stack', template, params)

        self.m.StubOutWithMock(instances.Instance, 'nova')
        instances.Instance.nova().AndReturn(self.fc)
        self.m.ReplayAll()

        resource = stack.resources['Instance']
        self.assertNotEqual(resource.validate(), None)
예제 #25
0
def get_wordpress_stack(stack_name, ctx):
    tmpl_path = os.path.join(templates_dir,
                             'WordPress_Single_Instance_gold.template')
    with open(tmpl_path) as f:
        t = template_format.parse(f.read())

    template = parser.Template(t)
    parameters = parser.Parameters(stack_name, template, {'KeyName': 'test'})

    stack = parser.Stack(ctx, stack_name, template, parameters)

    return stack
예제 #26
0
    def test_instance_create_delete(self):
        f = open("%s/WordPress_Single_Instance_gold.template" % self.path)
        t = json.loads(f.read())
        f.close()

        template = parser.Template(t)
        params = parser.Parameters('test_stack', template, {'KeyName': 'test'})
        stack = parser.Stack(None, 'test_stack', template, params, stack_id=-1)

        self.m.StubOutWithMock(db_api, 'resource_get_by_name_and_stack')
        db_api.resource_get_by_name_and_stack(None, 'test_resource_name',
                                              stack).AndReturn(None)

        self.m.StubOutWithMock(instances.Instance, 'nova')
        instances.Instance.nova().AndReturn(self.fc)
        instances.Instance.nova().AndReturn(self.fc)
        instances.Instance.nova().AndReturn(self.fc)
        instances.Instance.nova().AndReturn(self.fc)

        self.m.ReplayAll()

        t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'
        t['Resources']['WebServer']['Properties']['InstanceType'] = \
            '256 MB Server'
        instance = instances.Instance('test_resource_name',
                                      t['Resources']['WebServer'], stack)

        instance.t = instance.stack.resolve_runtime_data(instance.t)

        # need to resolve the template functions
        server_userdata = instance._build_userdata(
            instance.t['Properties']['UserData'])
        self.m.StubOutWithMock(self.fc.servers, 'create')
        self.fc.servers.create(image=1,
                               flavor=1,
                               key_name='test',
                               name='test_resource_name',
                               security_groups=None,
                               userdata=server_userdata,
                               scheduler_hints=None,
                               meta=None).AndReturn(self.fc.servers.list()[1])
        self.m.ReplayAll()

        instance.resource_id = 1234
        instance.create()

        # this makes sure the auto increment worked on instance creation
        self.assertTrue(instance.id > 0)

        instance.delete()
        self.assertTrue(instance.resource_id is None)
        self.assertEqual(instance.state, instance.DELETE_COMPLETE)
예제 #27
0
    def parse_stack(self, t):
        ctx = context.RequestContext.from_dict({
            'tenant': 'test_tenant',
            'username': '******',
            'password': '******',
            'auth_url': 'http://localhost:5000/v2.0'})
        stack_name = 'test_stack'
        tmpl = parser.Template(t)
        params = parser.Parameters(stack_name, tmpl,
                                   {'external_network': 'abcd1234'})
        stack = parser.Stack(ctx, stack_name, tmpl, params)

        return stack
예제 #28
0
    def test_instance_create_delete(self):
        f = open("%s/WordPress_Single_Instance_gold.template" % self.path)
        t = template_format.parse(f.read())
        f.close()

        stack_name = 'instance_create_delete_test_stack'
        template = parser.Template(t)
        params = parser.Parameters(stack_name, template, {'KeyName': 'test'})
        stack = parser.Stack(None, stack_name, template, params,
                             stack_id=uuidutils.generate_uuid())

        t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'
        t['Resources']['WebServer']['Properties']['InstanceType'] = \
            '256 MB Server'
        instance = instances.Instance('create_delete_instance_name',
                                      t['Resources']['WebServer'], stack)

        self.m.StubOutWithMock(instance, 'nova')
        instance.nova().MultipleTimes().AndReturn(self.fc)

        instance.t = instance.stack.resolve_runtime_data(instance.t)

        # need to resolve the template functions
        server_userdata = instance._build_userdata(
            instance.t['Properties']['UserData'])
        self.m.StubOutWithMock(self.fc.servers, 'create')
        self.fc.servers.create(
            image=1, flavor=1, key_name='test',
            name='%s.%s' % (stack_name, instance.name),
            security_groups=None,
            userdata=server_userdata, scheduler_hints=None,
            meta=None, nics=None, availability_zone=None).AndReturn(
                self.fc.servers.list()[1])
        self.m.ReplayAll()

        self.assertEqual(instance.create(), None)
        instance.resource_id = 1234

        # this makes sure the auto increment worked on instance creation
        self.assertTrue(instance.id > 0)

        self.m.StubOutWithMock(self.fc.client, 'get_servers_1234')
        get = self.fc.client.get_servers_1234
        get().AndRaise(instances.clients.novaclient.exceptions.NotFound(404))
        mox.Replay(get)

        instance.delete()
        self.assertTrue(instance.resource_id is None)
        self.assertEqual(instance.state, instance.DELETE_COMPLETE)
        self.m.VerifyAll()
예제 #29
0
    def test_unregistered_key(self):
        t = template_format.parse(test_unregistered_key)
        template = parser.Template(t)
        params = parser.Parameters('test_stack', template,
                                   {'KeyName': 'not_registered'})
        stack = parser.Stack(None, 'test_stack', template, params)

        self.m.StubOutWithMock(instances.Instance, 'nova')
        instances.Instance.nova().AndReturn(self.fc)
        instances.Instance.nova().AndReturn(self.fc)
        self.m.ReplayAll()

        resource = stack.resources['Instance']
        self.assertNotEqual(resource.validate(), None)
예제 #30
0
    def setUpClass(cls):
        # Create a dummy stack in the DB as WatchRule instances
        # must be associated with a stack
        ctx = context.get_admin_context()
        ctx.username = '******'
        ctx.tenant_id = '123456'
        empty_tmpl = {"template": {}}
        tmpl = parser.Template(empty_tmpl)
        stack_name = 'dummystack'
        params = parser.Parameters(stack_name, tmpl, {'foo': 'bar'})
        dummy_stack = parser.Stack(ctx, stack_name, tmpl, params)
        dummy_stack.state_set(dummy_stack.CREATE_COMPLETE, 'Testing')
        dummy_stack.store()

        cls.stack_id = dummy_stack.id