Search in sources :

Example 11 with NarClassLoader

use of org.apache.pulsar.common.nar.NarClassLoader in project pulsar by apache.

the class SourceApiV3ResourceTest method testUpdateSourceWithUrl.

@Test
public void testUpdateSourceWithUrl() throws Exception {
    Configurator.setRootLevel(Level.DEBUG);
    String filePackageUrl = getPulsarIOCassandraNar().toURI().toString();
    SourceConfig sourceConfig = new SourceConfig();
    sourceConfig.setTopicName(outputTopic);
    sourceConfig.setSerdeClassName(outputSerdeClassName);
    sourceConfig.setTenant(tenant);
    sourceConfig.setNamespace(namespace);
    sourceConfig.setName(source);
    sourceConfig.setClassName(TWITTER_FIRE_HOSE);
    sourceConfig.setParallelism(parallelism);
    when(mockedManager.containsFunction(eq(tenant), eq(namespace), eq(source))).thenReturn(true);
    mockStatic(ConnectorUtils.class, c -> {
    });
    mockStatic(ClassLoaderUtils.class, c -> {
    });
    mockStatic(FunctionCommon.class, ctx -> {
        ctx.when(() -> FunctionCommon.extractFileFromPkgURL(any())).thenCallRealMethod();
        ctx.when(() -> FunctionCommon.getClassLoaderFromPackage(any(), any(), any(), any())).thenCallRealMethod();
        ctx.when(() -> FunctionCommon.getSourceType(argThat(clazz -> clazz.getName().equals(TWITTER_FIRE_HOSE)))).thenReturn(String.class);
        ctx.when(() -> FunctionCommon.extractNarClassLoader(any(), any())).thenReturn(narClassLoader);
    });
    this.mockedFunctionMetaData = FunctionMetaData.newBuilder().setFunctionDetails(createDefaultFunctionDetails()).build();
    when(mockedManager.getFunctionMetaData(any(), any(), any())).thenReturn(mockedFunctionMetaData);
    resource.updateSource(tenant, namespace, source, null, null, filePackageUrl, sourceConfig, null, null, null);
}
Also used : Tenants(org.apache.pulsar.client.admin.Tenants) FormDataContentDisposition(org.glassfish.jersey.media.multipart.FormDataContentDisposition) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Level(org.apache.logging.log4j.Level) FunctionMetaData(org.apache.pulsar.functions.proto.Function.FunctionMetaData) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) SinkApiV3ResourceTest.getPulsarIOTwitterNar(org.apache.pulsar.functions.worker.rest.api.v3.SinkApiV3ResourceTest.getPulsarIOTwitterNar) Mockito.doThrow(org.mockito.Mockito.doThrow) Packages(org.apache.pulsar.client.admin.Packages) NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) FunctionDetails(org.apache.pulsar.functions.proto.Function.FunctionDetails) PulsarWorkerService(org.apache.pulsar.functions.worker.PulsarWorkerService) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) TopicSchema(org.apache.pulsar.functions.source.TopicSchema) RuntimeFactory(org.apache.pulsar.functions.runtime.RuntimeFactory) ClassLoaderUtils(org.apache.pulsar.common.util.ClassLoaderUtils) WorkerUtils(org.apache.pulsar.functions.worker.WorkerUtils) BeforeClass(org.testng.annotations.BeforeClass) BeforeMethod(org.testng.annotations.BeforeMethod) WorkerConfig(org.apache.pulsar.functions.worker.WorkerConfig) SourcesImpl(org.apache.pulsar.functions.worker.rest.api.SourcesImpl) FunctionMetaDataManager(org.apache.pulsar.functions.worker.FunctionMetaDataManager) List(java.util.List) MockedStatic(org.mockito.MockedStatic) Response(javax.ws.rs.core.Response) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Utils(org.apache.pulsar.common.functions.Utils) ConnectorUtils(org.apache.pulsar.functions.utils.io.ConnectorUtils) SourceSpec(org.apache.pulsar.functions.proto.Function.SourceSpec) LeaderService(org.apache.pulsar.functions.worker.LeaderService) SourceConfigUtils(org.apache.pulsar.functions.utils.SourceConfigUtils) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) PulsarAdmin(org.apache.pulsar.client.admin.PulsarAdmin) Mockito.spy(org.mockito.Mockito.spy) RestException(org.apache.pulsar.common.util.RestException) StandardCopyOption(java.nio.file.StandardCopyOption) Lists(com.google.common.collect.Lists) Namespaces(org.apache.pulsar.client.admin.Namespaces) NarClassLoaderBuilder(org.apache.pulsar.common.nar.NarClassLoaderBuilder) Configurator(org.apache.logging.log4j.core.config.Configurator) IdentityFunction(org.apache.pulsar.functions.api.utils.IdentityFunction) LinkedList(java.util.LinkedList) Functions(org.apache.pulsar.client.admin.Functions) PulsarFunctionTestTemporaryDirectory(org.apache.pulsar.functions.worker.rest.api.PulsarFunctionTestTemporaryDirectory) AfterClass(org.testng.annotations.AfterClass) SourceConfig(org.apache.pulsar.common.io.SourceConfig) Files(java.nio.file.Files) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) PackageLocationMetaData(org.apache.pulsar.functions.proto.Function.PackageLocationMetaData) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) FileInputStream(java.io.FileInputStream) File(java.io.File) Consumer(java.util.function.Consumer) Namespace(org.apache.distributedlog.api.namespace.Namespace) Mockito(org.mockito.Mockito) SinkApiV3ResourceTest.getPulsarIOCassandraNar(org.apache.pulsar.functions.worker.rest.api.v3.SinkApiV3ResourceTest.getPulsarIOCassandraNar) FunctionCommon(org.apache.pulsar.functions.utils.FunctionCommon) Paths(java.nio.file.Paths) SinkSpec(org.apache.pulsar.functions.proto.Function.SinkSpec) FunctionRuntimeManager(org.apache.pulsar.functions.worker.FunctionRuntimeManager) ProcessingGuarantees(org.apache.pulsar.functions.proto.Function.ProcessingGuarantees) SinkApiV3ResourceTest.getPulsarIOInvalidNar(org.apache.pulsar.functions.worker.rest.api.v3.SinkApiV3ResourceTest.getPulsarIOInvalidNar) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) InputStream(java.io.InputStream) SourceConfig(org.apache.pulsar.common.io.SourceConfig) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.testng.annotations.Test)

Example 12 with NarClassLoader

use of org.apache.pulsar.common.nar.NarClassLoader in project pulsar by apache.

the class SinkApiV3ResourceTest method testRegisterSinkSuccessK8sNoUpload.

/*
    Externally managed runtime,
    uploadBuiltinSinksSources == false
    Make sure uploadFileToBookkeeper is not called
    */
@Test
public void testRegisterSinkSuccessK8sNoUpload() throws Exception {
    mockedWorkerService.getWorkerConfig().setUploadBuiltinSinksSources(false);
    mockStatic(WorkerUtils.class, ctx -> {
        ctx.when(() -> WorkerUtils.uploadFileToBookkeeper(anyString(), any(File.class), any(Namespace.class))).thenThrow(new RuntimeException("uploadFileToBookkeeper triggered"));
    });
    NarClassLoader mockedClassLoader = mock(NarClassLoader.class);
    mockStatic(FunctionCommon.class, ctx -> {
        ctx.when(() -> FunctionCommon.getSinkType(any())).thenReturn(String.class);
        ctx.when(() -> FunctionCommon.getClassLoaderFromPackage(any(), any(), any(), any())).thenCallRealMethod();
        ctx.when(() -> FunctionCommon.isFunctionCodeBuiltin(any())).thenReturn(true);
        ctx.when(() -> FunctionCommon.isFunctionCodeBuiltin(any())).thenReturn(true);
        ctx.when(() -> FunctionCommon.extractNarClassLoader(any(), any())).thenReturn(mockedClassLoader);
    });
    ConnectorsManager mockedConnManager = mock(ConnectorsManager.class);
    Connector connector = Connector.builder().classLoader(mockedClassLoader).build();
    when(mockedConnManager.getConnector("cassandra")).thenReturn(connector);
    when(mockedWorkerService.getConnectorsManager()).thenReturn(mockedConnManager);
    when(mockedRuntimeFactory.externallyManaged()).thenReturn(true);
    when(mockedManager.containsFunction(eq(tenant), eq(namespace), eq(sink))).thenReturn(false);
    SinkConfig sinkConfig = createDefaultSinkConfig();
    sinkConfig.setArchive("builtin://cassandra");
    try (FileInputStream inputStream = new FileInputStream(getPulsarIOCassandraNar())) {
        resource.registerSink(tenant, namespace, sink, inputStream, mockedFormData, null, sinkConfig, null, null);
    }
}
Also used : Connector(org.apache.pulsar.functions.utils.io.Connector) SinkConfig(org.apache.pulsar.common.io.SinkConfig) NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) File(java.io.File) Namespace(org.apache.distributedlog.api.namespace.Namespace) FileInputStream(java.io.FileInputStream) ConnectorsManager(org.apache.pulsar.functions.worker.ConnectorsManager) Test(org.testng.annotations.Test)

Example 13 with NarClassLoader

use of org.apache.pulsar.common.nar.NarClassLoader in project pulsar by apache.

the class ProxyExtensionsUtils method load.

/**
 * Load the extension according to the handler definition.
 *
 * @param metadata the extension definition.
 * @return
 */
static ProxyExtensionWithClassLoader load(ProxyExtensionMetadata metadata, String narExtractionDirectory) throws IOException {
    final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
    NarClassLoader ncl = NarClassLoaderBuilder.builder().narFile(narFile).parentClassLoader(ProxyExtension.class.getClassLoader()).extractionDirectory(narExtractionDirectory).build();
    ProxyExtensionDefinition phDef = getProxyExtensionDefinition(ncl);
    if (StringUtils.isBlank(phDef.getExtensionClass())) {
        throw new IOException("extension `" + phDef.getName() + "` does NOT provide a protocol" + " handler implementation");
    }
    try {
        Class extensionClass = ncl.loadClass(phDef.getExtensionClass());
        Object extension = extensionClass.newInstance();
        if (!(extension instanceof ProxyExtension)) {
            throw new IOException("Class " + phDef.getExtensionClass() + " does not implement extension interface");
        }
        ProxyExtension ph = (ProxyExtension) extension;
        return new ProxyExtensionWithClassLoader(ph, ncl);
    } catch (Throwable t) {
        rethrowIOException(t);
        return null;
    }
}
Also used : NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) UtilityClass(lombok.experimental.UtilityClass) IOException(java.io.IOException) File(java.io.File)

Example 14 with NarClassLoader

use of org.apache.pulsar.common.nar.NarClassLoader in project pulsar by apache.

the class ProxyExtensionWithClassLoaderTest method testWrapper.

@Test
public void testWrapper() throws Exception {
    ProxyExtension h = mock(ProxyExtension.class);
    NarClassLoader loader = mock(NarClassLoader.class);
    ProxyExtensionWithClassLoader wrapper = new ProxyExtensionWithClassLoader(h, loader);
    String protocol = "kafka";
    when(h.extensionName()).thenReturn(protocol);
    assertEquals(protocol, wrapper.extensionName());
    verify(h, times(1)).extensionName();
    when(h.accept(eq(protocol))).thenReturn(true);
    assertTrue(wrapper.accept(protocol));
    verify(h, times(1)).accept(same(protocol));
    ProxyConfiguration conf = new ProxyConfiguration();
    wrapper.initialize(conf);
    verify(h, times(1)).initialize(same(conf));
    ProxyService service = mock(ProxyService.class);
    wrapper.start(service);
    verify(h, times(1)).start(service);
}
Also used : ProxyConfiguration(org.apache.pulsar.proxy.server.ProxyConfiguration) ProxyService(org.apache.pulsar.proxy.server.ProxyService) NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) Test(org.testng.annotations.Test)

Example 15 with NarClassLoader

use of org.apache.pulsar.common.nar.NarClassLoader in project pulsar by apache.

the class ProxyExtensionWithClassLoaderTest method testClassLoaderSwitcher.

@Test
public void testClassLoaderSwitcher() throws Exception {
    NarClassLoader loader = mock(NarClassLoader.class);
    String protocol = "test-protocol";
    ProxyExtension h = new ProxyExtension() {

        @Override
        public String extensionName() {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
            return protocol;
        }

        @Override
        public boolean accept(String protocol) {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
            return true;
        }

        @Override
        public void initialize(ProxyConfiguration conf) throws Exception {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
            throw new Exception("test exception");
        }

        @Override
        public void start(ProxyService service) {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
        }

        @Override
        public Map<InetSocketAddress, ChannelInitializer<SocketChannel>> newChannelInitializers() {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
            return null;
        }

        @Override
        public void close() {
            assertEquals(Thread.currentThread().getContextClassLoader(), loader);
        }
    };
    ProxyExtensionWithClassLoader wrapper = new ProxyExtensionWithClassLoader(h, loader);
    ClassLoader curClassLoader = Thread.currentThread().getContextClassLoader();
    assertEquals(wrapper.extensionName(), protocol);
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
    assertTrue(wrapper.accept(protocol));
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
    ProxyConfiguration conf = new ProxyConfiguration();
    expectThrows(Exception.class, () -> wrapper.initialize(conf));
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
    ProxyService service = mock(ProxyService.class);
    wrapper.start(service);
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
    assertNull(wrapper.newChannelInitializers());
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
    wrapper.close();
    assertEquals(Thread.currentThread().getContextClassLoader(), curClassLoader);
}
Also used : ProxyConfiguration(org.apache.pulsar.proxy.server.ProxyConfiguration) ProxyService(org.apache.pulsar.proxy.server.ProxyService) InetSocketAddress(java.net.InetSocketAddress) NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) NarClassLoader(org.apache.pulsar.common.nar.NarClassLoader) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.testng.annotations.Test)

Aggregations

NarClassLoader (org.apache.pulsar.common.nar.NarClassLoader)126 Test (org.testng.annotations.Test)84 IOException (java.io.IOException)53 NarClassLoaderBuilder (org.apache.pulsar.common.nar.NarClassLoaderBuilder)48 File (java.io.File)39 FileInputStream (java.io.FileInputStream)15 UtilityClass (lombok.experimental.UtilityClass)15 Namespace (org.apache.distributedlog.api.namespace.Namespace)15 HashMap (java.util.HashMap)14 Map (java.util.Map)12 ServiceConfiguration (org.apache.pulsar.broker.ServiceConfiguration)12 Lists (com.google.common.collect.Lists)9 InputStream (java.io.InputStream)9 Files (java.nio.file.Files)9 Paths (java.nio.file.Paths)9 StandardCopyOption (java.nio.file.StandardCopyOption)9 LinkedList (java.util.LinkedList)9 List (java.util.List)9 Consumer (java.util.function.Consumer)9 Response (javax.ws.rs.core.Response)9