def test_ctx_type(self):
     ctx = context.CloudifyContext({})
     self.assertEqual(constants.DEPLOYMENT, ctx.type)
     ctx = context.CloudifyContext({'node_id': 'node-instance-id'})
     self.assertEqual(constants.NODE_INSTANCE, ctx.type)
     ctx = context.CloudifyContext({
         'node_id': 'node-instance-id',
         'related': {
             'node_id': 'related-instance-id',
             'is_target': True
         },
         'relationships': ['related-instance-id']
     })
     self.assertEqual(constants.RELATIONSHIP_INSTANCE, ctx.type)
    def setUpClass(cls):
        state.current_ctx.set(context.CloudifyContext({}), {})

        os.environ[constants.REST_PORT_KEY] = '53333'
        os.environ[constants.REST_HOST_KEY] = "localhost"
        os.environ[constants.MANAGER_FILE_SERVER_SCHEME] = "http"
        _, os.environ[constants.LOCAL_REST_CERT_FILE_KEY] = tempfile.mkstemp()
 def test_operation_retry(self):
     ctx = context.CloudifyContext({})
     e = self.assertRaises(exceptions.OperationRetry,
                           retry_operation,
                           ctx)
     self.assertEqual(RETRY_AFTER, e.retry_after)
     self.assertIn(RETRY_MESSAGE, str(e))
 def setup_tenant_context(self):
     self.context = context.CloudifyContext({
         'blueprint_id': 'test_blueprint',
         'tenant': {
             'name': 'default_tenant'
         }
     })
     self.redirect_log_to_stdout(self.context.logger)
 def setUp(self):
     super(CloudifyContextTest, self).setUp()
     self.context = context.CloudifyContext({
         'blueprint_id': '',
         'tenant': {'name': 'default_tenant'}
     })
     # the context logger will try to publish messages to rabbit, which is
     # not available here. instead, we redirect the output to stdout.
     self.redirect_log_to_stdout(self.context.logger)
 def test_operation_retry_api(self):
     op_name = 'operation'
     ctx = context.CloudifyContext({
         'operation': {
             'name': op_name,
             'retry_number': 0,
             'max_retries': 10
         }
     })
     self.assertEqual(op_name, ctx.operation.name)
     self.assertEqual(0, ctx.operation.retry_number)
     self.assertEqual(10, ctx.operation.max_retries)
 def test_source_target_not_in_relationship(self):
     ctx = context.CloudifyContext({})
     e = self.assertRaises(exceptions.NonRecoverableError,
                           lambda: ctx.source)
     self.assertIn('ctx.source/ctx.target can only be used in a '
                   'relationship-instance context but used in a '
                   'deployment context.', str(e))
     e = self.assertRaises(exceptions.NonRecoverableError,
                           lambda: ctx.target)
     self.assertIn('ctx.source/ctx.target can only be used in a '
                   'relationship-instance context but used in a '
                   'deployment context.', str(e))
    def setUpClass(cls):

        state.current_ctx.set(context.CloudifyContext({}), {})

        resources_path = os.path.join(dirname(tests_path.__file__))

        from cloudify.tests.file_server import FileServer
        from cloudify.tests.file_server import PORT

        cls.file_server_process = FileServer(resources_path)
        cls.file_server_process.start()

        os.environ[constants.MANAGER_FILE_SERVER_URL_KEY] = \
            "http://localhost:{0}".format(PORT)
        _, os.environ[constants.LOCAL_REST_CERT_FILE_KEY] = tempfile.mkstemp()
        cls.context = context.CloudifyContext({
            'blueprint_id': '',
            'tenant': {
                'name': 'default_tenant'
            }
        })
        # the context logger will try to publish messages to rabbit, which is
        # not available here. instead, we redirect the output to stdout.
        cls.redirect_log_to_stdout(cls.context.logger)
    def setUpClass(cls):

        state.current_ctx.set(context.CloudifyContext({}), {})

        resources_path = os.path.join(dirname(tests_path.__file__))

        from cloudify.tests.file_server import FileServer
        from cloudify.tests.file_server import PORT

        cls.file_server_process = FileServer(resources_path)
        cls.file_server_process.start()

        os.environ[constants.REST_PORT_KEY] = "{0}".format(PORT)
        os.environ[constants.REST_HOST_KEY] = "localhost"
        os.environ[constants.MANAGER_FILE_SERVER_SCHEME] = "http"
        _, os.environ[constants.LOCAL_REST_CERT_FILE_KEY] = tempfile.mkstemp()
Exemple #10
0
    def setUpClass(cls):

        resources_path = os.path.join(dirname(tests_path.__file__),
                                      "resources")

        from cloudify.tests.file_server import FileServer
        from cloudify.tests.file_server import PORT

        cls.file_server_process = FileServer(resources_path)
        cls.file_server_process.start()

        os.environ[constants.MANAGER_FILE_SERVER_BLUEPRINTS_ROOT_URL_KEY] \
            = "http://localhost:{0}".format(PORT)
        os.environ[constants.MANAGER_FILE_SERVER_URL_KEY] = \
            "http://localhost:{0}".format(PORT)
        cls.context = context.CloudifyContext({'blueprint_id': ''})
 def setUp(self):
     super(PluginContextTests, self).setUp()
     self.plugin_name = 'test_plugin'
     self.plugin_pacakge_name = 'test-plugin'
     self.plugin_pacakge_version = '0.1.1'
     self.deployment_id = 'test_deployment'
     self.tenant_name = 'default_tenant'
     self.ctx = context.CloudifyContext({
         'deployment_id': self.deployment_id,
         'tenant': {'name': self.tenant_name},
         'plugin': {
             'name': self.plugin_name,
             'package_name': self.plugin_pacakge_name,
             'package_version': self.plugin_pacakge_version
         }
     })
     self.test_prefix = tempfile.mkdtemp(prefix='context-plugin-test-')
     self.addCleanup(lambda: shutil.rmtree(self.test_prefix,
                                           ignore_errors=True))
Exemple #12
0
    def setUpClass(cls):

        resources_path = os.path.join(dirname(tests_path.__file__),
                                      "resources")

        from cloudify.tests.file_server import FileServer
        from cloudify.tests.file_server import PORT

        cls.file_server_process = FileServer(resources_path)
        cls.file_server_process.start()

        os.environ[constants.MANAGER_FILE_SERVER_BLUEPRINTS_ROOT_URL_KEY] \
            = "http://localhost:{0}".format(PORT)
        os.environ[constants.MANAGER_FILE_SERVER_URL_KEY] = \
            "http://localhost:{0}".format(PORT)
        cls.context = context.CloudifyContext({'blueprint_id': ''})
        # the context logger will try to publish messages to rabbit, which is
        # not available here. instead, we redirect the output to stdout.
        cls.redirect_log_to_stdout(cls.context.logger)
 def test_ctx_instance_in_relationship(self):
     ctx = context.CloudifyContext({
         'node_id': 'node-instance-id',
         'related': {
             'node_id': 'related-instance-id',
             'is_target': True
         },
         'relationships': ['related-instance-id']
     })
     self.assertEqual('node-instance-id', ctx.source.instance.id)
     self.assertEqual('related-instance-id', ctx.target.instance.id)
     e = self.assertRaises(exceptions.NonRecoverableError,
                           lambda: ctx.node)
     self.assertIn('ctx.node/ctx.instance can only be used in a '
                   'node-instance context but used in a '
                   'relationship-instance context.', str(e))
     e = self.assertRaises(exceptions.NonRecoverableError,
                           lambda: ctx.instance)
     self.assertIn('ctx.node/ctx.instance can only be used in a '
                   'node-instance context but used in a '
                   'relationship-instance context.', str(e))
Exemple #14
0
def install_local(agent_file, output_agent_file, rest_token, rest_cert_path):
    if agent_file is None:
        raise click.ClickException('--agent-file should be specified.')
    cloudify_agent = json.load(agent_file)
    ctx = context.CloudifyContext({'rest_token': rest_token})
    state.current_ctx.set(ctx, {})
    if not cloudify_agent.get('rest_port'):
        cloudify_agent['rest_port'] = defaults.INTERNAL_REST_PORT
    os.environ[utils.internal.CLOUDIFY_DAEMON_USER_KEY] = str(
        cloudify_agent['user'])
    os.environ[CLOUDIFY_LOCAL_REST_CERT_PATH] = str(rest_cert_path)
    if 'basedir' not in cloudify_agent:
        cloudify_agent['basedir'] = utils.get_home_dir(cloudify_agent['user'])
    configuration.directory_attributes(cloudify_agent)
    installer = prepare_local_installer(cloudify_agent)
    installer.create_agent()
    installer.configure_agent()
    installer.start_agent()
    if output_agent_file is not None:
        with open(output_agent_file, 'w') as out:
            out.write(json.dumps(cloudify_agent))

    # Remove the temporary cert file, as it was copied to the agent's dir
    os.remove(rest_cert_path)
        def wrapper(*args, **kwargs):
            ctx = _find_context_arg(args, kwargs, _is_cloudify_context)
            if ctx is None:
                ctx = {}
            if not _is_cloudify_context(ctx):
                ctx = context.CloudifyContext(ctx)
                # remove __cloudify_context
                raw_context = kwargs.pop(CLOUDIFY_CONTEXT_PROPERTY_KEY, {})
                if ctx.task_target is None:
                    # task is local (not through celery) so we need to
                    # clone kwarg
                    kwargs = copy.deepcopy(kwargs)
                if raw_context.get('has_intrinsic_functions') is True:
                    kwargs = ctx._endpoint.evaluate_functions(payload=kwargs)
                kwargs['ctx'] = ctx
            try:
                current_ctx.set(ctx, kwargs)
                result = func(*args, **kwargs)
            except BaseException as e:
                ctx.logger.error(
                    'Exception raised on operation [%s] invocation',
                    ctx.task_name, exc_info=True)

                if ctx.task_target is None:
                    # local task execution
                    # no serialization issues
                    raise

                # extract exception details
                # type, value, traceback
                tpe, value, tb = sys.exc_info()

                # we re-create the exception here
                # since it will be sent
                # over the wire. And the original exception
                # may cause de-serialization issues
                # on the other side.

                # preserve original type in the message
                message = '{0}: {1}'.format(tpe.__name__, str(e))

                # if the exception type is directly one of our exception
                # than there is no need for conversion and we can just
                # raise the original exception
                if type(e) in [exceptions.OperationRetry,
                               exceptions.RecoverableError,
                               exceptions.NonRecoverableError,
                               exceptions.HttpException]:
                    raise

                # if the exception inherits from our base exceptions, there
                # still might be a de-serialization problem caused by one of
                # the types in the inheritance tree.
                if isinstance(e, exceptions.NonRecoverableError):
                    value = exceptions.NonRecoverableError(message)
                elif isinstance(e, exceptions.OperationRetry):
                    value = exceptions.OperationRetry(message, e.retry_after)
                elif isinstance(e, exceptions.RecoverableError):
                    value = exceptions.RecoverableError(message, e.retry_after)
                else:
                    # convert pure user exceptions
                    # to a RecoverableError
                    value = exceptions.RecoverableError(message)

                raise type(value), value, tb

            finally:
                current_ctx.clear()
                if ctx.type == context.NODE_INSTANCE:
                    ctx.instance.update()
                elif ctx.type == context.RELATIONSHIP_INSTANCE:
                    ctx.source.instance.update()
                    ctx.target.instance.update()
            if ctx.operation._operation_retry:
                raise ctx.operation._operation_retry
            return result