Search in sources :

Example 1 with Service

use of org.apache.ignite.services.Service in project ignite by apache.

the class GridServiceProcessor method service.

/**
 * @param name Service name.
 * @param <T> Service type.
 * @return Service by specified service name.
 */
@SuppressWarnings("unchecked")
public <T> T service(String name) {
    ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null);
    Collection<ServiceContextImpl> ctxs;
    synchronized (locSvcs) {
        ctxs = locSvcs.get(name);
    }
    if (ctxs == null)
        return null;
    synchronized (ctxs) {
        if (ctxs.isEmpty())
            return null;
        for (ServiceContextImpl ctx : ctxs) {
            Service svc = ctx.service();
            if (svc != null)
                return (T) svc;
        }
        return null;
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) Service(org.apache.ignite.services.Service)

Example 2 with Service

use of org.apache.ignite.services.Service in project ignite by apache.

the class GridServiceProcessor method redeploy.

/**
 * Redeploys local services based on assignments.
 *
 * @param assigns Assignments.
 */
private void redeploy(GridServiceAssignments assigns) {
    if (assigns.topologyVersion() < ctx.discovery().topologyVersion()) {
        if (log.isDebugEnabled())
            log.debug("Skip outdated assignment [assigns=" + assigns + ", topVer=" + ctx.discovery().topologyVersion() + ']');
        return;
    }
    String svcName = assigns.name();
    Integer assignCnt = assigns.assigns().get(ctx.localNodeId());
    if (assignCnt == null)
        assignCnt = 0;
    Collection<ServiceContextImpl> ctxs;
    synchronized (locSvcs) {
        ctxs = locSvcs.get(svcName);
        if (ctxs == null)
            locSvcs.put(svcName, ctxs = new ArrayList<>());
    }
    Collection<ServiceContextImpl> toInit = new ArrayList<>();
    synchronized (ctxs) {
        if (ctxs.size() > assignCnt) {
            int cancelCnt = ctxs.size() - assignCnt;
            cancel(ctxs, cancelCnt);
        } else if (ctxs.size() < assignCnt) {
            int createCnt = assignCnt - ctxs.size();
            for (int i = 0; i < createCnt; i++) {
                ServiceContextImpl svcCtx = new ServiceContextImpl(assigns.name(), UUID.randomUUID(), assigns.cacheName(), assigns.affinityKey(), Executors.newSingleThreadExecutor(threadFactory));
                ctxs.add(svcCtx);
                toInit.add(svcCtx);
            }
        }
    }
    for (final ServiceContextImpl svcCtx : toInit) {
        final Service svc;
        try {
            svc = copyAndInject(assigns.configuration());
            // Initialize service.
            svc.init(svcCtx);
            svcCtx.service(svc);
        } catch (Throwable e) {
            U.error(log, "Failed to initialize service (service will not be deployed): " + assigns.name(), e);
            synchronized (ctxs) {
                ctxs.removeAll(toInit);
            }
            if (e instanceof Error)
                throw (Error) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            return;
        }
        if (log.isInfoEnabled())
            log.info("Starting service instance [name=" + svcCtx.name() + ", execId=" + svcCtx.executionId() + ']');
        // Start service in its own thread.
        final ExecutorService exe = svcCtx.executor();
        exe.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    svc.execute(svcCtx);
                } catch (InterruptedException | IgniteInterruptedCheckedException ignore) {
                    if (log.isDebugEnabled())
                        log.debug("Service thread was interrupted [name=" + svcCtx.name() + ", execId=" + svcCtx.executionId() + ']');
                } catch (IgniteException e) {
                    if (e.hasCause(InterruptedException.class) || e.hasCause(IgniteInterruptedCheckedException.class)) {
                        if (log.isDebugEnabled())
                            log.debug("Service thread was interrupted [name=" + svcCtx.name() + ", execId=" + svcCtx.executionId() + ']');
                    } else {
                        U.error(log, "Service execution stopped with error [name=" + svcCtx.name() + ", execId=" + svcCtx.executionId() + ']', e);
                    }
                } catch (Throwable e) {
                    log.error("Service execution stopped with error [name=" + svcCtx.name() + ", execId=" + svcCtx.executionId() + ']', e);
                    if (e instanceof Error)
                        throw (Error) e;
                } finally {
                    // Suicide.
                    exe.shutdownNow();
                }
            }
        });
    }
}
Also used : ArrayList(java.util.ArrayList) ExecutorService(java.util.concurrent.ExecutorService) Service(org.apache.ignite.services.Service) IgniteSystemProperties.getString(org.apache.ignite.IgniteSystemProperties.getString) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteException(org.apache.ignite.IgniteException) ExecutorService(java.util.concurrent.ExecutorService)

Example 3 with Service

use of org.apache.ignite.services.Service in project ignite by apache.

the class GridServiceProcessor method copyAndInject.

/**
 * @param cfg Service configuration.
 * @return Copy of service.
 * @throws IgniteCheckedException If failed.
 */
private Service copyAndInject(ServiceConfiguration cfg) throws IgniteCheckedException {
    Marshaller m = ctx.config().getMarshaller();
    if (cfg instanceof LazyServiceConfiguration) {
        byte[] bytes = ((LazyServiceConfiguration) cfg).serviceBytes();
        Service srvc = U.unmarshal(m, bytes, U.resolveClassLoader(null, ctx.config()));
        ctx.resource().inject(srvc);
        return srvc;
    } else {
        Service svc = cfg.getService();
        try {
            byte[] bytes = U.marshal(m, svc);
            Service cp = U.unmarshal(m, bytes, U.resolveClassLoader(svc.getClass().getClassLoader(), ctx.config()));
            ctx.resource().inject(cp);
            return cp;
        } catch (IgniteCheckedException e) {
            U.error(log, "Failed to copy service (will reuse same instance): " + svc.getClass(), e);
            return svc;
        }
    }
}
Also used : Marshaller(org.apache.ignite.marshaller.Marshaller) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ExecutorService(java.util.concurrent.ExecutorService) Service(org.apache.ignite.services.Service)

Example 4 with Service

use of org.apache.ignite.services.Service in project ignite by apache.

the class GridServiceProcessorProxySelfTest method testRemoteStickyProxyInvocation.

/**
 * @throws Exception If failed.
 */
public void testRemoteStickyProxyInvocation() throws Exception {
    final String name = "testRemoteStickyProxyInvocation";
    final Ignite ignite = grid(0);
    ignite.services().deployNodeSingleton(name, new MapServiceImpl<String, Integer>());
    // Get remote proxy.
    MapService<Integer, String> svc = ignite.services(ignite.cluster().forRemotes()).serviceProxy(name, MapService.class, true);
    // Make sure service is a local instance.
    assertFalse(svc instanceof Service);
    for (int i = 0; i < nodeCount(); i++) svc.put(i, Integer.toString(i));
    int size = 0;
    for (ClusterNode n : ignite.cluster().forRemotes().nodes()) {
        MapService<Integer, String> map = ignite.services(ignite.cluster().forNode(n)).serviceProxy(name, MapService.class, false);
        // Make sure service is a local instance.
        assertFalse(map instanceof Service);
        if (map.size() != 0)
            size += map.size();
    }
    assertEquals(nodeCount(), size);
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) Service(org.apache.ignite.services.Service) Ignite(org.apache.ignite.Ignite)

Example 5 with Service

use of org.apache.ignite.services.Service in project ignite by apache.

the class ServicesTest method testServiceDescriptors.

/**
 * Test service descriptors returned correctly.
 */
@Test
public void testServiceDescriptors() throws Exception {
    try (IgniteClient client = startClient(0)) {
        Collection<ClientServiceDescriptor> svcs = client.services().serviceDescriptors();
        assertNotNull(svcs);
        assertEquals(3, svcs.size());
        assertTrue(svcs.stream().filter(svc -> svc.name().equals(NODE_ID_SERVICE_NAME)).peek(svc -> {
            assertEquals(NODE_ID_SERVICE_NAME, svc.name());
            assertEquals(TestNodeIdService.class.getName(), svc.serviceClass());
            assertEquals(0, svc.totalCount());
            assertEquals(1, svc.maxPerNodeCount());
            assertNull(svc.cacheName());
            assertEquals(grid(0).localNode().id(), svc.originNodeId());
            assertEquals(PlatformType.JAVA, svc.platformType());
            assertDescriptorsEquals(svc, client.services().serviceDescriptor(NODE_ID_SERVICE_NAME));
        }).findFirst().isPresent());
        assertTrue(svcs.stream().filter(svc -> svc.name().equals(NODE_SINGLTON_SERVICE_NAME)).peek(svc -> {
            assertEquals(NODE_SINGLTON_SERVICE_NAME, svc.name());
            assertEquals(TestService.class.getName(), svc.serviceClass());
            assertEquals(0, svc.totalCount());
            assertEquals(1, svc.maxPerNodeCount());
            assertNull(svc.cacheName());
            assertEquals(grid(0).localNode().id(), svc.originNodeId());
            assertEquals(PlatformType.JAVA, svc.platformType());
            assertDescriptorsEquals(svc, client.services().serviceDescriptor(NODE_SINGLTON_SERVICE_NAME));
        }).findFirst().isPresent());
        assertTrue(svcs.stream().filter(svc -> svc.name().equals(CLUSTER_SINGLTON_SERVICE_NAME)).peek(svc -> {
            assertEquals(CLUSTER_SINGLTON_SERVICE_NAME, svc.name());
            assertEquals(TestService.class.getName(), svc.serviceClass());
            assertEquals(1, svc.totalCount());
            assertEquals(1, svc.maxPerNodeCount());
            assertEquals(DEFAULT_CACHE_NAME, svc.cacheName());
            assertEquals(grid(0).localNode().id(), svc.originNodeId());
            assertEquals(PlatformType.JAVA, svc.platformType());
            assertDescriptorsEquals(svc, client.services().serviceDescriptor(CLUSTER_SINGLTON_SERVICE_NAME));
        }).findFirst().isPresent());
        assertThrowsWithCause(() -> {
            client.services().serviceDescriptor("unknown");
        }, ClientException.class);
    }
}
Also used : ClientClusterGroup(org.apache.ignite.client.ClientClusterGroup) Arrays(java.util.Arrays) Person(org.apache.ignite.client.Person) PlatformType(org.apache.ignite.platform.PlatformType) HashSet(java.util.HashSet) ClientException(org.apache.ignite.client.ClientException) ServiceContext(org.apache.ignite.services.ServiceContext) IgniteClient(org.apache.ignite.client.IgniteClient) Map(java.util.Map) BinaryArray(org.apache.ignite.internal.binary.BinaryArray) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) F(org.apache.ignite.internal.util.typedef.F) ServiceCallContext(org.apache.ignite.services.ServiceCallContext) GridTestUtils.assertThrowsWithCause(org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause) Collection(java.util.Collection) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) Test(org.junit.Test) UUID(java.util.UUID) Ignite(org.apache.ignite.Ignite) ServiceCallContextBuilder(org.apache.ignite.services.ServiceCallContextBuilder) ClientServiceDescriptor(org.apache.ignite.client.ClientServiceDescriptor) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) ServiceContextResource(org.apache.ignite.resources.ServiceContextResource) Service(org.apache.ignite.services.Service) IGNITE_USE_BINARY_ARRAYS(org.apache.ignite.IgniteSystemProperties.IGNITE_USE_BINARY_ARRAYS) IgniteClient(org.apache.ignite.client.IgniteClient) ClientServiceDescriptor(org.apache.ignite.client.ClientServiceDescriptor) Test(org.junit.Test)

Aggregations

Service (org.apache.ignite.services.Service)26 ExecutorService (java.util.concurrent.ExecutorService)11 Ignite (org.apache.ignite.Ignite)9 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)8 Test (org.junit.Test)7 ArrayList (java.util.ArrayList)6 ClusterNode (org.apache.ignite.cluster.ClusterNode)6 PlatformService (org.apache.ignite.internal.processors.platform.services.PlatformService)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 IgniteException (org.apache.ignite.IgniteException)5 IgniteEx (org.apache.ignite.internal.IgniteEx)5 IgniteServices (org.apache.ignite.IgniteServices)3 ServiceConfiguration (org.apache.ignite.services.ServiceConfiguration)3 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Arrays (java.util.Arrays)2 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)2 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)2 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)2 ServiceContext (org.apache.ignite.services.ServiceContext)2