Exemplo n.º 1
0
    async def invoke_function(
        self,
        name,
        input_data: typing.List[protos.ParameterBinding],
        metadata: typing.Optional[typing.Mapping[str,
                                                 protos.TypedData]] = None):

        if metadata is None:
            metadata = {}

        if name not in self._available_functions:
            raise RuntimeError(f'cannot load function {name}')

        func = self._available_functions[name]
        invocation_id = self.make_id()

        r = await self.communicate(protos.StreamingMessage(
            invocation_request=protos.InvocationRequest(
                invocation_id=invocation_id,
                function_id=func.id,
                input_data=input_data,
                trigger_metadata=metadata,
            )),
                                   wait_for='invocation_response')

        return invocation_id, r
Exemplo n.º 2
0
    async def _verify_environment_reloaded(
            self,
            test_env: typing.Dict[str, str] = {},
            test_cwd: str = os.getcwd()):
        request = protos.FunctionEnvironmentReloadRequest(
            environment_variables=test_env,
            function_app_directory=test_cwd)

        request_msg = protos.StreamingMessage(
            request_id='0',
            function_environment_reload_request=request)

        disp = testutils.create_dummy_dispatcher()

        try:
            r = await disp._handle__function_environment_reload_request(
                request_msg)

            environ_dict = os.environ.copy()
            self.assertDictEqual(environ_dict, test_env)
            self.assertEqual(os.getcwd(), test_cwd)
            status = r.function_environment_reload_response.result.status
            self.assertEqual(status, protos.StatusResult.Success)
        finally:
            self._reset_environ()
Exemplo n.º 3
0
    async def get_functions_metadata(self):
        r = await self.communicate(protos.StreamingMessage(
            functions_metadata_request=protos.FunctionsMetadataRequest(
                function_app_directory=str(self._scripts_dir))),
                                   wait_for='function_metadata_response')

        return r
Exemplo n.º 4
0
    async def init_worker(self, host_version: str):
        r = await self.communicate(protos.StreamingMessage(
            worker_init_request=protos.WorkerInitRequest(
                host_version=host_version)),
                                   wait_for='worker_init_response')

        return r
async def vertify_nested_namespace_import():
    test_env = {}
    request = protos.FunctionEnvironmentReloadRequest(
        environment_variables=test_env)

    request_msg = protos.StreamingMessage(
        request_id='0', function_environment_reload_request=request)

    disp = testutils.create_dummy_dispatcher()

    # Mock intepreter starts in placeholder mode
    import azure.module_a as mod_a  # noqa: F401

    # Mock function specialization, load customer's libraries and functionapps
    ns_root = os.path.join(testutils.UNIT_TESTS_ROOT, 'azure_namespace_import',
                           'namespace_location_b')
    test_path = os.path.join(ns_root, 'azure', 'namespace_b', 'module_b')
    test_mod_path = os.path.join(test_path, 'test_module.py')

    os.makedirs(test_path)
    with open(test_mod_path, 'w') as f:
        f.write('MESSAGE = "module_b is imported"')

    try:
        # Mock a customer uses test_module
        if sys.argv[1].lower() == 'true':
            await disp._handle__function_environment_reload_request(request_msg
                                                                    )
        from azure.namespace_b.module_b import test_module
        print(test_module.MESSAGE)
    except ModuleNotFoundError:
        print('module_b fails to import')
    finally:
        # Cleanup
        shutil.rmtree(ns_root)
Exemplo n.º 6
0
async def verify_path_imports():
    test_env = {}
    request = protos.FunctionEnvironmentReloadRequest(
        environment_variables=test_env)

    request_msg = protos.StreamingMessage(
        request_id='0', function_environment_reload_request=request)

    disp = testutils.create_dummy_dispatcher()

    test_path = 'test_module_dir'
    test_mod_path = os.path.join(test_path, 'test_module.py')

    os.mkdir(test_path)
    with open(test_mod_path, 'w') as f:
        f.write('CONSTANT = "This module was imported!"')

    if (sys.argv[1] == 'success'):
        await disp._handle__function_environment_reload_request(request_msg)

    try:
        import test_module
        print(test_module.CONSTANT)
    finally:
        # Cleanup
        shutil.rmtree(test_path)
Exemplo n.º 7
0
    async def close_shared_memory_resources(self, map_names: typing.List[str]):

        request = protos.CloseSharedMemoryResourcesRequest(map_names=map_names)

        r = await self.communicate(
            protos.StreamingMessage(
                close_shared_memory_resources_request=request),
            wait_for='close_shared_memory_resources_response')

        return r
    async def test_handles_unsupported_messages_gracefully(self):
        async with testutils.start_mockhost() as host:
            # Intentionally send a message to worker that isn't
            # going to be ever supported by it.  The idea is that
            # workers should survive such messages and continue
            # their operation.  If anything, the host can always
            # terminate the worker.
            await host.send(
                protos.StreamingMessage(
                    worker_heartbeat=protos.WorkerHeartbeat()))

            _, r = await host.load_function('return_out')
            self.assertEqual(r.response.result.status,
                             protos.StatusResult.Success)
Exemplo n.º 9
0
    async def reload_environment(
        self,
        environment: typing.Dict[str, str],
        function_project_path: str = '/home/site/wwwroot'
    ) -> protos.FunctionEnvironmentReloadResponse:

        request_content = protos.FunctionEnvironmentReloadRequest(
            function_app_directory=function_project_path,
            environment_variables={
                k.encode(): v.encode()
                for k, v in environment.items()
            })

        r = await self.communicate(
            protos.StreamingMessage(
                function_environment_reload_request=request_content),
            wait_for='function_environment_reload_response')

        return r
Exemplo n.º 10
0
    async def load_function(self, name):
        if name not in self._available_functions:
            raise RuntimeError(f'cannot load function {name}')

        func = self._available_functions[name]

        bindings = {}
        for b in func.desc['bindings']:
            direction = getattr(protos.BindingInfo, b['direction'])

            data_type_v = b.get('dataType')
            if not data_type_v:
                data_type = protos.BindingInfo.undefined
            elif data_type_v == 'binary':
                data_type = protos.BindingInfo.binary
            elif data_type_v == 'string':
                data_type = protos.BindingInfo.string
            elif data_type_v == 'stream':
                data_type = protos.BindingInfo.stream
            else:
                raise RuntimeError(f'invalid dataType: {data_type_v!r}')

            bindings[b['name']] = protos.BindingInfo(type=b['type'],
                                                     data_type=data_type,
                                                     direction=direction)

        r = await self.communicate(protos.StreamingMessage(
            function_load_request=protos.FunctionLoadRequest(
                function_id=func.id,
                metadata=protos.RpcFunctionMetadata(name=func.name,
                                                    directory=os.path.dirname(
                                                        func.script),
                                                    script_file=func.script,
                                                    bindings=bindings))),
                                   wait_for='function_load_response')

        return func.id, r
Exemplo n.º 11
0
    async def get_worker_status(self):
        r = await self.communicate(protos.StreamingMessage(
            worker_status_request=protos.WorkerStatusRequest()),
                                   wait_for='worker_status_response')

        return r