def setUp(self):
        ctx = MockCloudifyContext(
            target=MockContext({
                'instance': MockNodeInstanceContext(
                    'sg1', {
                        OPENSTACK_ID_PROPERTY: 'test-sg',
                        OPENSTACK_NAME_PROPERTY: 'test-sg-name'
                    })
            }),
            source=MockContext({
                'node': mock.MagicMock(),
                'instance': MockNodeInstanceContext(
                    'server', {
                        OPENSTACK_ID_PROPERTY: 'server'
                    }
                )})
        )

        current_ctx.set(ctx)
        self.addCleanup(current_ctx.clear)
        findctx = mock.patch(
            'openstack_plugin_common._find_context_in_kw',
            return_value=ctx,
        )
        findctx.start()
        self.addCleanup(findctx.stop)
Example #2
0
 def test_set_directory_config(self, _):
     target = MockContext({
         'instance': MockNodeInstanceContext(
             id='terra_install-1',
             runtime_properties=self.get_terraform_conf_props(
                 test_dir2).get("terraform_config")
         ),
         'node': MockNodeContext(
             id='1',
             properties=self.get_terraform_conf_props(test_dir2)
         ), '_context': {
             'node_id': '1'
         }})
     source_work_dir = mkdtemp()
     source = MockContext({
         'instance': MockNodeInstanceContext(
             id='terra_module-1',
             runtime_properties={}),
         'node': MockNodeContext(
             id='2',
             properties=self.get_terraform_module_conf_props(
                 source_work_dir)
         ), '_context': {
             'node_id': '2'
         }})
     ctx = MockCloudifyContextRels(source=source, target=target)
     current_ctx.set(ctx=ctx)
     kwargs = {
         'ctx': ctx
     }
     set_directory_config(**kwargs)
     self.assertEqual(
         ctx.source.instance.runtime_properties.get("executable_path"),
         ctx.target.instance.runtime_properties.get("executable_path"))
 def _get_ctx_mock(self, instance_id, boot):
     rel_specs = [MockRelationshipContext(
         target=MockRelationshipSubjectContext(node=MockNodeContext(
             properties={'boot': boot}), instance=MockNodeInstanceContext(
             runtime_properties={
                 OPENSTACK_TYPE_PROPERTY: VOLUME_OPENSTACK_TYPE,
                 OPENSTACK_ID_PROPERTY: instance_id,
                 VOLUME_BOOTABLE: False
             })))]
     ctx = mock.MagicMock()
     ctx.instance = MockNodeInstanceContext(relationships=rel_specs)
     ctx.logger = setup_logger('mock-logger')
     return ctx
Example #4
0
    def test_evaluate_negative(self):
        # given
        value = 5
        runtime_properties = {
            'key': {
                'nested_key1': {
                    'nested_key2': value
                }
            },
            'other_key': 'blahblahblah'
        }

        node_ctx = MockNodeContext()
        node_ctx.type_hierarchy = ['cloudify.nodes.Root']

        relationship_ctx = MockRelationshipContext(target=None,
                                                   type=self.relationship_type)
        relationship_ctx.type_hierarchy = [
            'cloudify.relationships.connected_to', self.relationship_type
        ]

        instance_ctx = MockNodeInstanceContext(
            runtime_properties=runtime_properties)

        # when
        result = self.full_rule.evaluate(relationship_ctx, node_ctx,
                                         instance_ctx)

        # then
        self.assertEquals((False, None), result)
Example #5
0
 def mock_ctx(self, test_vars, test_id,
              test_deployment_id, runtime_properties=None):
     ctx = MockContext()
     ctx.node = MockNodeContext(properties=test_vars)
     ctx.instance = MockNodeInstanceContext(
         id=test_id, runtime_properties=runtime_properties or {})
     ctx.deployment = mock.Mock()
     ctx.deployment.id = test_deployment_id
     ctx.type = NODE_INSTANCE
     return ctx
Example #6
0
    def test_get_runtime_property_negative_wrong_runtime_properties(self):
        # given
        runtime_properties = {'emptiness': None}
        instance_ctx = MockNodeInstanceContext(
            runtime_properties=runtime_properties)

        # then
        with self.assertRaises(InputArgumentResolvingError):
            # when
            self.full_rule.get_runtime_property(instance_ctx)
Example #7
0
    def get_mock_relationship_ctx_for_node(self, rel_specs):
        """
        This method will generate list of mock relationship associated with
        certain node
        :param rel_specs: Relationships is an ordered collection of
        relationship specs - dicts with the keys "node" and "instance" used
        to construct the MockNodeContext and the MockNodeInstanceContext,
        and optionally a "type" key.
        Examples: [
            {},
            {"node": {"id": 5}},
            {
                "type": "some_type",
                "instance": {
                    "id": 3,
                    "runtime_properties":{}
                }
            }
        ]
        :return list: Return list of "MockRelationshipContext" instances
        """

        relationships = []
        for rel_spec in rel_specs:
            node = rel_spec.get('node', {})
            node_id = node.pop('id', uuid.uuid4().hex)

            instance = rel_spec.get('instance', {})
            instance_id = instance.pop(
                'id', '{0}_{1}'.format(node_id,
                                       uuid.uuid4().hex))
            if 'properties' not in node:
                node['properties'] = {}

            mock_data = {
                'id': node_id,
                'properties': node['properties'],
            }

            if rel_spec.get('type_hierarchy'):
                mock_data['type_hierarchy'] = rel_spec['type_hierarchy']

            node_ctx = CustomMockNodeContext(**mock_data)
            instance_ctx = MockNodeInstanceContext(id=instance_id, **instance)

            rel_subject_ctx = MockRelationshipSubjectContext(
                node=node_ctx, instance=instance_ctx)
            rel_type = rel_spec.get('type')
            rel_ctx = MockRelationshipContext(target=rel_subject_ctx,
                                              type=rel_type)
            relationships.append(rel_ctx)

        return relationships
    def test_connect_sg_to_port_race_condition(self, *_):
        mock_neutron = MockNeutronClient(update=False)

        ctx = MockCloudifyContext(
            source=MockRelationshipSubjectContext(node=mock.MagicMock(),
                                                  instance=mock.MagicMock()),
            target=MockRelationshipSubjectContext(
                node=mock.MagicMock(),
                instance=MockNodeInstanceContext(
                    runtime_properties={OPENSTACK_ID_PROPERTY: 'test-sg-id'})))
        with mock.patch('neutron_plugin.port.ctx', ctx):
            neutron_plugin.port.connect_security_group(mock_neutron, ctx=ctx)
            self.assertIsInstance(ctx.operation._operation_retry,
                                  OperationRetry)
def test_stop():
    from cloudify_healer.stopper import stop

    # start process then stop it
    p = subprocess.Popen(["exec sleep 120"], shell=True)
    ctx = MockCloudifyContext(source=MockRelationshipSubjectContext(
        None, MockNodeInstanceContext(runtime_properties={"pid": str(p.pid)})))

    current_ctx.set(ctx)
    stop()
    sleep(2)
    if p.poll() is None:
        p.terminate()
        p.wait()
        assert False
 def mock_ctx(self,
              test_vars,
              test_id,
              test_deployment_id,
              runtime_properties=None):
     ctx = MockContext()
     ctx.node = MockNodeContext(properties=test_vars)
     ctx.bootstrap_context = BootstrapContext(
         common_test.BOOTSTRAP_CONTEXTS_WITHOUT_PREFIX[0])
     ctx.instance = MockNodeInstanceContext(
         id=test_id, runtime_properties=runtime_properties or {})
     ctx.deployment = mock.Mock()
     ctx.deployment.id = test_deployment_id
     ctx.type = NODE_INSTANCE
     ctx.logger = mock.Mock()
     return ctx
    def mock_ctx(self,
                 test_vars,
                 test_id,
                 test_deployment_id,
                 runtime_properties=None):

        ctx = MockContext()
        ctx.node = MockNodeContext(properties=test_vars)
        ctx.instance = MockNodeInstanceContext(
            id=test_id, runtime_properties=runtime_properties or {})
        ctx.deployment = mock.Mock()
        ctx.deployment.id = test_deployment_id
        ctx.bootstrap_context = mock.Mock()
        setattr(ctx.bootstrap_context, 'resources_prefix', '')
        ctx.type = NODE_INSTANCE
        ctx.logger = mock.Mock()

        return ctx
    def _make_vm_ctx_with_relationships(self, rel_specs, properties=None):
        """Prepare a mock CloudifyContext from the given relationship spec.

        rel_specs is an ordered collection of relationship specs - dicts
        with the keys "node" and "instance" used to construct the
        MockNodeContext and the MockNodeInstanceContext, and optionally a
        "type" key.
        Examples: [
            {},
            {"node": {"id": 5}},
            {
                "type": "some_type",
                "instance": {
                    "id": 3,
                    "runtime_properties":{}
                }
            }
        ]
        """
        if properties is None:
            properties = {}
        relationships = []
        for rel_spec in rel_specs:
            node = rel_spec.get('node', {})
            node_id = node.pop('id', uuid.uuid4().hex)

            instance = rel_spec.get('instance', {})
            instance_id = instance.pop(
                'id', '{0}_{1}'.format(node_id,
                                       uuid.uuid4().hex))
            if 'properties' not in node:
                node['properties'] = {}
            node_ctx = MockNodeContext(id=node_id, **node)
            instance_ctx = MockNodeInstanceContext(id=instance_id, **instance)

            rel_subject_ctx = MockRelationshipSubjectContext(
                node=node_ctx, instance=instance_ctx)
            rel_type = rel_spec.get('type')
            rel_ctx = MockRelationshipContext(target=rel_subject_ctx,
                                              type=rel_type)
            relationships.append(rel_ctx)
        return MockCloudifyContext(node_id='vm',
                                   properties=properties,
                                   relationships=relationships)
Example #13
0
    def test_get_runtime_property_positive_simple_value(self):
        # given
        value = 5
        runtime_properties = {
            'key': {
                'nested_key1': {
                    'nested_key2': value
                }
            },
            'other_key': 'blahblahblah'
        }
        instance_ctx = MockNodeInstanceContext(
            runtime_properties=runtime_properties)

        # when
        result = self.full_rule.get_runtime_property(instance_ctx)

        # then
        self.assertEquals(result, value)
    def mock_relationship(self,
                          type=RBAC_POLICY_APPLIED_FOR_RELATIONSHIP_TYPE,
                          runtime_properties=None):

        class _MockRelationshipContext(MockRelationshipContext):

            @property
            def type_hierarchy(self):
                return [self.type]

        return _MockRelationshipContext(
            MockRelationshipSubjectContext(
                node=None,
                instance=MockNodeInstanceContext(
                    runtime_properties=runtime_properties or {},
                )
            ),
            type=type
        )
Example #15
0
    def setUp(self):
        self.properties = {'a': 1, 'b': 2}
        self.runtime_properties = {'a': 1, 'b': 2, 'c': 3}
        self.input_args = {'b': 11, 'c': 4, 'd': 5, 'e': 6}
        self.resolved_values = {'a': 10, 'd': 7, 'e': 8, 'f': 9}
        self.expected_result = {'a': 1, 'b': 2, 'c': 3, 'd': 5, 'e': 6, 'f': 9}

        self.mocked_node = MockNodeContext(properties=self.properties)
        self.mocked_instance = MockNodeInstanceContext(
            runtime_properties=self.runtime_properties)
        self.mocked_logger = Mock()
        self.mocked_logger_warn = Mock()
        self.mocked_logger.warn = self.mocked_logger_warn

        self.mocked_ctx = Mock()
        self.mocked_ctx.node = self.mocked_node
        self.mocked_ctx.instance = self.mocked_instance
        self.mocked_ctx.logger = self.mocked_logger

        self.mocked_resolver = Mock()
        self.mocked_resolver_resolve = Mock(return_value=self.resolved_values)
        self.mocked_resolver.resolve = self.mocked_resolver_resolve
Example #16
0
    def test_get_runtime_property_negative_wrong_path(self):
        # given
        value = 5
        runtime_properties = {
            'key': {
                'nested_key1': {
                    'nested_key2': value
                }
            },
            'other_key': 'blahblahblah'
        }
        instance_ctx = MockNodeInstanceContext(
            runtime_properties=runtime_properties)

        rule = InputArgumentResolvingRule(
            self.argument_name,
            node_type=self.node_type,
            relationship_type=self.relationship_type,
            runtime_properties_path=['a', 'b', 'cxvcxvcxvxvc'])

        # then
        with self.assertRaises(InputArgumentResolvingError):
            # when
            rule.get_runtime_property(instance_ctx)
    def _mock_item_to_resources_list_rel_ctx(self):
        # target
        tar_rel_subject_ctx = MockRelationshipSubjectContext(
            node=MockNodeContext(
                id='test_resources',
                type='cloudify.nodes.resources.List',
                properties={
                    'resource_config': [
                        '10.0.1.0/24',
                        '10.0.2.0/24',
                        '10.0.3.0/24'
                    ]
                }
            ),
            instance=MockNodeInstanceContext(
                id='test_resources_123456',
                runtime_properties={},
            )
        )

        rel_ctx = MockRelationshipContext(
            type='cloudify.relationships.resources.reserve_list_item',
            target=tar_rel_subject_ctx
        )

        # source
        src_ctx = MockCloudifyContext(
            node_id='test_item_123456',
            node_type='cloudify.nodes.resources.ListItem',
            source=self,
            target=tar_rel_subject_ctx,
            relationships=rel_ctx
        )

        current_ctx.set(src_ctx)
        return src_ctx
Example #18
0
    def test_get_runtime_property_positive_list(self):
        # given
        value = 5
        runtime_properties = {
            'key': [{}, {}, {
                'nested_key1': {
                    'nested_key2': value
                }
            }, {}],
            'other_key': 'blahblahblah'
        }
        instance_ctx = MockNodeInstanceContext(
            runtime_properties=runtime_properties)

        rule = InputArgumentResolvingRule(
            self.argument_name,
            node_type=self.node_type,
            relationship_type=self.relationship_type,
            runtime_properties_path=['key', 2, 'nested_key1', 'nested_key2'])
        # when
        result = rule.get_runtime_property(instance_ctx)

        # then
        self.assertEquals(result, value)
 def _mock_rel(*_):
     return MockNodeInstanceContext(
         runtime_properties={OPENSTACK_ID_PROPERTY: 'my-id'})
Example #20
0
    def test_remove_external_interface_from_router(self, mock_connection):
        target = MockContext({
            'instance':
            MockNodeInstanceContext(id='router-1',
                                    runtime_properties={
                                        RESOURCE_ID:
                                        'a95b5509-c122-4c2f-823e-884bb559afe2',
                                        OPENSTACK_TYPE_PROPERTY:
                                        OPENSTACK_TYPE_PROPERTY,
                                        OPENSTACK_NAME_PROPERTY: 'node-router',
                                    }),
            'node':
            MockNodeContext(id='1',
                            properties={
                                'client_config': self.client_config,
                                'resource_config': self.resource_config,
                                'use_external_resource': True,
                            }),
            '_context': {
                'node_id': '1'
            }
        })

        source = MockContext({
            'instance':
            MockNodeInstanceContext(id='subnet-1',
                                    runtime_properties={
                                        RESOURCE_ID:
                                        'a95b5509-c122-4c2f-823e-884bb559afe8',
                                        OPENSTACK_TYPE_PROPERTY:
                                        SUBNET_OPENSTACK_TYPE,
                                        OPENSTACK_NAME_PROPERTY: 'node-subnet',
                                    }),
            'node':
            MockNodeContext(id='1',
                            properties={
                                'client_config': self.client_config,
                                'resource_config': self.resource_config,
                                'use_external_resource': True,
                            }),
            '_context': {
                'node_id': '1'
            }
        })

        self._pepare_relationship_context_for_operation(
            deployment_id='RouterTest',
            source=source,
            target=target,
            ctx_operation_name='cloudify.interfaces.'
            'relationship_lifecycle.unlink',
            node_id='1')

        router_instance = openstack.network.v2.router.Router(
            **{
                'id': 'a95b5509-c122-4c2f-823e-884bb559afe8',
                'name': 'test_router',
                'description': 'test_description',
                'availability_zone_hints': ['1'],
                'availability_zones': ['2'],
                'created_at': 'timestamp1',
                'distributed': False,
                'external_gateway_info': {
                    'network_id': 'a95b5509-c122-4c2f-823e-884bb559afe4'
                },
                'flavor_id': '5',
                'ha': False,
                'revision': 7,
                'routes': [],
                'status': '9',
                'tenant_id': '10',
                'updated_at': 'timestamp2',
            })
        # Mock get router response
        mock_connection().network.get_router = \
            mock.MagicMock(return_value=router_instance)

        # Call remove interface from router
        router.remove_interface_from_router(
            **{'subnet_id': 'a95b5509-c122-4c2f-823e-884bb559afe8'})
Example #21
0
    def test_add_external_interface_to_router(self, mock_connection):
        target = MockContext({
            'instance':
            MockNodeInstanceContext(id='router-1',
                                    runtime_properties={
                                        RESOURCE_ID:
                                        'a95b5509-c122-4c2f-823e-884bb559afe2',
                                        OPENSTACK_TYPE_PROPERTY:
                                        OPENSTACK_TYPE_PROPERTY,
                                        OPENSTACK_NAME_PROPERTY: 'node-router',
                                    }),
            'node':
            MockNodeContext(id='1',
                            properties={
                                'client_config': self.client_config,
                                'resource_config': self.resource_config,
                                'use_external_resource': True,
                            }),
            '_context': {
                'node_id': '1'
            }
        })

        source = MockContext({
            'instance':
            MockNodeInstanceContext(id='subnet-1',
                                    runtime_properties={
                                        RESOURCE_ID:
                                        'a95b5509-c122-4c2f-823e-884bb559afe8',
                                        OPENSTACK_TYPE_PROPERTY:
                                        SUBNET_OPENSTACK_TYPE,
                                        OPENSTACK_NAME_PROPERTY: 'node-subnet',
                                    }),
            'node':
            MockNodeContext(id='1',
                            properties={
                                'client_config': self.client_config,
                                'resource_config': self.resource_config,
                                'use_external_resource': True,
                            }),
            '_context': {
                'node_id': '1'
            }
        })

        self._pepare_relationship_context_for_operation(
            deployment_id='RouterTest',
            source=source,
            target=target,
            ctx_operation_name='cloudify.interfaces.'
            'relationship_lifecycle.postconfigure',
            node_id='1')

        router_instance = openstack.network.v2.router.Router(
            **{
                'id': 'a95b5509-c122-4c2f-823e-884bb559afe8',
                'name': 'test_router',
                'description': 'test_description',
                'availability_zone_hints': ['1'],
                'availability_zones': ['2'],
                'created_at': 'timestamp1',
                'distributed': False,
                'external_gateway_info': {
                    'network_id': 'a95b5509-c122-4c2f-823e-884bb559afe4'
                },
                'flavor_id': '5',
                'ha': False,
                'revision': 7,
                'routes': [],
                'status': '9',
                'tenant_id': '10',
                'updated_at': 'timestamp2',
            })

        ports = [
            openstack.network.v2.port.Port(
                **{
                    'id':
                    'a95b5509-c122-4c2f-823e-884bb559afe1',
                    'name':
                    'test_port_1',
                    'admin_state_up':
                    True,
                    'binding_host_id':
                    '3',
                    'binding_profile': {
                        '4': 4
                    },
                    'binding_vif_details': {
                        '5': 5
                    },
                    'binding_vif_type':
                    '6',
                    'binding_vnic_type':
                    '7',
                    'created_at':
                    '2016-03-09T12:14:57.233772',
                    'data_plane_status':
                    '32',
                    'description':
                    'port_description_2',
                    'device_id':
                    '9',
                    'device_owner':
                    '10',
                    'dns_assignment': [{
                        '11': 11
                    }],
                    'dns_domain':
                    'a11',
                    'dns_name':
                    '12',
                    'extra_dhcp_opts': [{
                        '13': 13
                    }],
                    'fixed_ips':
                    [{
                        'subnet_id': 'a95b5509-c122-4c2f-823e-884bb559afe8'
                    }, {
                        'subnet_id': 'a95b5509-c122-4c2f-823e-884bb559afa7'
                    }],
                    'allowed_address_pairs': [{
                        'ip_address': '10.0.0.3'
                    }, {
                        'ip_address': '10.0.0.4'
                    }],
                    'mac_address':
                    '00-14-22-01-23-45',
                    'network_id':
                    '18',
                    'port_security_enabled':
                    True,
                    'qos_policy_id':
                    '21',
                    'revision_number':
                    22,
                    'security_groups': ['23'],
                    'status':
                    '25',
                    'tenant_id':
                    '26',
                    'updated_at':
                    '2016-07-09T12:14:57.233772',
                }),
            openstack.network.v2.port.Port(
                **{
                    'id':
                    'a95b5509-c122-4c2f-823e-884bb559afe2',
                    'name':
                    'test_port_1',
                    'admin_state_up':
                    True,
                    'binding_host_id':
                    '3',
                    'binding_profile': {
                        '4': 4
                    },
                    'binding_vif_details': {
                        '5': 5
                    },
                    'binding_vif_type':
                    '6',
                    'binding_vnic_type':
                    '7',
                    'created_at':
                    '2016-03-09T12:14:57.233772',
                    'data_plane_status':
                    '32',
                    'description':
                    'port_description_2',
                    'device_id':
                    '9',
                    'device_owner':
                    '10',
                    'dns_assignment': [{
                        '11': 11
                    }],
                    'dns_domain':
                    'a11',
                    'dns_name':
                    '12',
                    'extra_dhcp_opts': [{
                        '13': 13
                    }],
                    'fixed_ips': [{
                        'subnet_id':
                        'a95b5509-c122-4c2f-823e-884bb559afe5'
                    }, {
                        'subnet_id':
                        'a95b5509-c122-4c2f-823e-884bb559afa4'
                    }],
                    'allowed_address_pairs': [{
                        'ip_address': '10.0.0.3'
                    }, {
                        'ip_address': '10.0.0.4'
                    }],
                    'mac_address':
                    '00-41-23-23-23-24',
                    'network_id':
                    '18',
                    'port_security_enabled':
                    True,
                    'qos_policy_id':
                    '21',
                    'revision_number':
                    22,
                    'security_groups': ['23'],
                    'status':
                    '25',
                    'tenant_id':
                    '26',
                    'updated_at':
                    '2016-07-09T12:14:57.233772',
                }),
        ]

        # Mock list port response
        mock_connection().network.ports = mock.MagicMock(return_value=ports)

        # Mock get router response
        mock_connection().network.get_router = \
            mock.MagicMock(return_value=router_instance)

        # Call add interface to router
        router.add_interface_to_router(
            **{'subnet_id': 'a95b5509-c122-4c2f-823e-884bb559afe8'})
    def test_set_directory_config(self, _):
        def get_terraform_conf_props(module_root=test_dir2):
            return {
                "terraform_config": {
                    "executable_path": path.join(module_root, "terraform"),
                    "storage_path": module_root,
                    "plugins_dir": path.join(module_root, '.terraform',
                                             "plugins"),
                },
                "resource_config": {
                    "use_existing_resource":
                    False,
                    "installation_source":
                    "https://releases.hashicorp.com/terraform/0.11.7/"
                    "terraform_0.11.7_linux_amd64.zip",
                    "plugins": []
                }
            }

        def get_terraform_module_conf_props(module_root=test_dir2):
            return {
                "resource_config": {
                    "source": path.join(module_root, "template"),
                    "variables": {
                        "a": "var1",
                        "b": "var2"
                    },
                    "environment_variables": {
                        "EXEC_PATH": path.join(module_root, "execution"),
                    }
                }
            }

        target = MockContext({
            'instance':
            MockNodeInstanceContext(
                id='terra_install-1',
                runtime_properties=get_terraform_conf_props().get(
                    "terraform_config")),
            'node':
            MockNodeContext(id='1', properties=get_terraform_conf_props()),
            '_context': {
                'node_id': '1'
            }
        })
        source_work_dir = mkdtemp()
        source = MockContext({
            'instance':
            MockNodeInstanceContext(id='terra_module-1',
                                    runtime_properties={}),
            'node':
            MockNodeContext(
                id='2',
                properties=get_terraform_module_conf_props(source_work_dir)),
            '_context': {
                'node_id': '2'
            }
        })
        ctx = MockCloudifyContextRels(source=source, target=target)
        current_ctx.set(ctx=ctx)
        kwargs = {'ctx': ctx}
        set_directory_config(**kwargs)
        self.assertEqual(
            ctx.source.instance.runtime_properties.get("executable_path"),
            ctx.target.instance.runtime_properties.get("executable_path"))