Search in sources :

Example 6 with External

use of io.fabric8.annotations.External in project fabric8 by fabric8io.

the class AbstractServiceRegistar method registerBeanDefinitions.

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    for (Method method : REFLECTIONS.getMethodsAnnotatedWith(Factory.class)) {
        String methodName = method.getName();
        Class sourceType = getSourceType(method);
        Class targetType = method.getReturnType();
        Class beanType = method.getDeclaringClass();
        BeanDefinitionHolder holder = createConverterBean(beanType, methodName, sourceType, targetType);
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }
    for (Field field : REFLECTIONS.getFieldsAnnotatedWith(ServiceName.class)) {
        Class targetClass = field.getType();
        Alias alias = field.getAnnotation(Alias.class);
        ServiceName name = field.getAnnotation(ServiceName.class);
        PortName port = field.getAnnotation(PortName.class);
        Protocol protocol = field.getAnnotation(Protocol.class);
        External external = field.getAnnotation(External.class);
        String serviceName = name != null ? name.value() : null;
        // We copy the service since we are going to add properties to it.
        Service serviceInstance = new ServiceBuilder(getService(serviceName)).build();
        String servicePort = port != null ? port.value() : null;
        String serviceProtocol = protocol != null ? protocol.value() : DEFAULT_PROTOCOL;
        Boolean serviceExternal = external != null && external.value();
        String serviceAlias = alias != null ? alias.value() : createAlias(serviceName, targetClass, serviceProtocol, servicePort, serviceExternal);
        // Add annotation info as additional properties
        serviceInstance.getAdditionalProperties().put(ALIAS, serviceAlias);
        serviceInstance.getAdditionalProperties().put(PROTOCOL, serviceProtocol);
        serviceInstance.getAdditionalProperties().put(EXTERNAL, serviceExternal);
        // We don't want to add a fallback value to the attributes.
        if (port != null) {
            serviceInstance.getAdditionalProperties().put(PORT, servicePort);
        }
        BeanDefinitionHolder holder = createServiceDefinition(serviceInstance, serviceAlias, serviceProtocol, servicePort, targetClass);
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }
}
Also used : Service(io.fabric8.kubernetes.api.model.Service) Method(java.lang.reflect.Method) PortName(io.fabric8.annotations.PortName) ServiceBuilder(io.fabric8.kubernetes.api.model.ServiceBuilder) Field(java.lang.reflect.Field) ServiceName(io.fabric8.annotations.ServiceName) Alias(io.fabric8.annotations.Alias) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) External(io.fabric8.annotations.External) Protocol(io.fabric8.annotations.Protocol)

Example 7 with External

use of io.fabric8.annotations.External in project fabric8 by fabric8io.

the class Fabric8Extension method onInjectionPoint.

public <T, X> void onInjectionPoint(@Observes ProcessInjectionPoint<T, X> event, BeanManager beanManager) {
    final InjectionPoint injectionPoint = event.getInjectionPoint();
    if (isServiceInjectionPoint(injectionPoint)) {
        Annotated annotated = injectionPoint.getAnnotated();
        ServiceName name = annotated.getAnnotation(ServiceName.class);
        Protocol protocol = annotated.getAnnotation(Protocol.class);
        PortName port = annotated.getAnnotation(PortName.class);
        Path path = annotated.getAnnotation(Path.class);
        Alias alias = annotated.getAnnotation(Alias.class);
        Endpoint endpoint = annotated.getAnnotation(Endpoint.class);
        External external = annotated.getAnnotation(External.class);
        String serviceName = name.value();
        String serviceProtocol = protocol != null ? protocol.value() : null;
        String servicePort = port != null ? port.value() : null;
        String servicePath = path != null ? path.value() : null;
        String serviceAlias = alias != null ? alias.value() : null;
        Boolean serviceExternal = external != null ? external.value() : false;
        Boolean serviceEndpoint = endpoint != null ? endpoint.value() : false;
        Type type = annotated.getBaseType();
        if (type instanceof ParameterizedType && Instance.class.equals(((ParameterizedType) type).getRawType())) {
            type = ((ParameterizedType) type).getActualTypeArguments()[0];
        }
        if (type.equals(String.class)) {
            ServiceUrlBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal);
        } else if (isGenericOf(type, List.class, String.class)) {
            ServiceUrlCollectionBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, Types.LIST_OF_STRINGS);
        } else if (isGenericOf(type, List.class, null)) {
        // TODO: Integrate with Factories(?)
        } else if (isGenericOf(type, Set.class, String.class)) {
            ServiceUrlCollectionBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, Types.SET_OF_STRINGS);
        } else if (isGenericOf(type, Set.class, null)) {
        // TODO: Integrate with Factories(?)
        } else if (type instanceof Class) {
            ServiceBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, type);
        } else {
            throw new RuntimeException(String.format(INJECTION_POINT_UNKNOWN_TYPE, injectionPoint.getBean().getBeanClass(), type));
        }
        if (protocol == null) {
            setDefaultProtocol(event);
        }
        if (port == null) {
            setDefaultPort(event);
        }
        if (path == null) {
            setDefaultPath(event);
        }
        if (endpoint == null) {
            setDefaultEndpoint(event);
        }
        if (external == null) {
            setDefaultExternal(event);
        }
    } else if (isConfigurationInjectionPoint(injectionPoint)) {
        Annotated annotated = injectionPoint.getAnnotated();
        Configuration configuration = annotated.getAnnotation(Configuration.class);
        Type type = injectionPoint.getType();
        String configurationId = configuration.value();
        ConfigurationBean.getBean(configurationId, type);
    }
}
Also used : Path(io.fabric8.annotations.Path) Utils.getFactoryMethodPath(io.fabric8.cdi.Utils.getFactoryMethodPath) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Configuration(io.fabric8.annotations.Configuration) ProcessInjectionPoint(javax.enterprise.inject.spi.ProcessInjectionPoint) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) Instance(javax.enterprise.inject.Instance) PortName(io.fabric8.annotations.PortName) ParameterizedType(java.lang.reflect.ParameterizedType) Annotated(javax.enterprise.inject.spi.Annotated) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Endpoint(io.fabric8.annotations.Endpoint) ServiceName(io.fabric8.annotations.ServiceName) Alias(io.fabric8.annotations.Alias) External(io.fabric8.annotations.External) ArrayList(java.util.ArrayList) List(java.util.List) Utils.getFactoryMethodProtocol(io.fabric8.cdi.Utils.getFactoryMethodProtocol) Protocol(io.fabric8.annotations.Protocol)

Example 8 with External

use of io.fabric8.annotations.External in project docker-maven-plugin by fabric8io.

the class PropertyConfigHandlerTest method resolveExternalImageConfig.

private ImageConfiguration resolveExternalImageConfig(String[] testData) {
    Map<String, String> external = new HashMap<>();
    external.put("type", "props");
    ImageConfiguration config = new ImageConfiguration.Builder().name("image").alias("alias").externalConfig(external).build();
    List<ImageConfiguration> resolvedImageConfigs = resolveImage(config, props(testData));
    assertEquals(1, resolvedImageConfigs.size());
    return resolvedImageConfigs.get(0);
}
Also used : BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration)

Example 9 with External

use of io.fabric8.annotations.External in project carbon-apimgt by wso2.

the class ServiceDiscovererKubernetesTestCase method testInitWhileExternalTokenFileNameGiven.

@Test(description = "Test init method with external service account token file name")
public void testInitWhileExternalTokenFileNameGiven() throws Exception {
    OpenShiftClient openShiftClient = Mockito.mock(OpenShiftClient.class);
    ServiceDiscovererKubernetes sdKubernetes = new ServiceDiscovererKubernetes();
    sdKubernetes.setClient(openShiftClient);
    try {
        sdKubernetes.initImpl(createImplParametersMap("TestK8Token"));
    } catch (ServiceDiscoveryException e) {
        Assert.assertEquals(e.getCause().getMessage(), "File to decrypt does not exist");
    }
}
Also used : OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) ServiceDiscoveryException(org.wso2.carbon.apimgt.core.exception.ServiceDiscoveryException) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 10 with External

use of io.fabric8.annotations.External in project fabric8 by jboss-fuse.

the class DummyBatchingProgressMonitor method activateInternal.

private void activateInternal() throws Exception {
    LOGGER.info("Starting up GitDataStore " + this);
    // Call the bootstrap {@link DataStoreTemplate}
    DataStoreTemplate template = runtimeProperties.get().removeRuntimeAttribute(DataStoreTemplate.class);
    if (template != null) {
        // Do the initial commit and set the root tag
        Ref rootTag = getGit().getRepository().getRef(GitHelpers.ROOT_TAG);
        if (rootTag == null) {
            getGit().commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
            getGit().tag().setName(GitHelpers.ROOT_TAG).setMessage("Tag the root commit").call();
        }
        LOGGER.debug("Running datastore bootstrap template: " + template);
        template.doWith(this, dataStore.get());
    }
    // Setup proxy service
    GitProxyService proxyService = gitProxyService.get();
    defaultProxySelector = ProxySelector.getDefault();
    // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
    // Authenticator.setDefault(new FabricGitLocalHostAuthenticator(proxyService));
    ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector, proxyService);
    ProxySelector.setDefault(fabricProxySelector);
    LOGGER.debug("Setting up FabricProxySelector: {}", fabricProxySelector);
    if (gitRemoteUrl != null) {
        gitListener.runRemoteUrlChanged(gitRemoteUrl);
        remoteUrl = gitRemoteUrl;
    } else {
        gitService.get().addGitListener(gitListener);
        remoteUrl = gitService.get().getRemoteUrl();
        if (remoteUrl != null) {
            gitListener.runRemoteUrlChanged(remoteUrl);
        }
    }
    // Get initial versions
    getInitialVersions();
    // poll logic in case of remote git repo
    if (gitRemoteUrl != null) {
        // i need this old logic in case of remote repos
        LOGGER.info("Starting to pull from remote git repository every {} millis", gitRemotePollInterval);
        threadPool.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                LockHandle writeLock = aquireWriteLock();
                try {
                    LOGGER.trace("Performing timed pull");
                    doPullInternal();
                    LOGGER.debug("Performed timed pull from external git repo");
                } catch (Throwable e) {
                    LOGGER.debug("Error during performed timed pull/push due " + e.getMessage(), e);
                    LOGGER.warn("Error during performed timed pull/push due " + e.getMessage() + ". This exception is ignored.");
                } finally {
                    writeLock.unlock();
                }
            }

            @Override
            public String toString() {
                return "TimedPushTask";
            }
        }, 1000, gitRemotePollInterval, TimeUnit.MILLISECONDS);
    }
    LOGGER.info("Using ZooKeeper SharedCount to react when master git repo is changed, so we can do a git pull to the local git repo.");
    counter = new SharedCount(curator.get(), ZkPath.GIT_TRIGGER.getPath(), 0);
    counter.addListener(new SharedCountListener() {

        @Override
        public void countHasChanged(final SharedCountReader sharedCountReader, final int value) throws Exception {
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    doPullInternal();
                }
            };
            if (gitRandomFetchDelay == 0) {
                LOGGER.debug("Watch counter updated to " + value + ", scheduling immediate pull");
                threadPool.submit(task);
            } else {
                int delay = RND.nextInt(gitRandomFetchDelay) + 1;
                LOGGER.debug("Watch counter updated to " + value + ", scheduling pull with random delay=" + delay + "s");
                threadPool.schedule(task, delay, TimeUnit.SECONDS);
            }
        }

        @Override
        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
            switch(connectionState) {
                case SUSPENDED:
                case READ_ONLY:
                case LOST:
                    // do nothing
                    break;
                case CONNECTED:
                case RECONNECTED:
                    LOGGER.info("Shared Counter (Re)connected, doing a pull");
                    doPullInternal();
                    break;
            }
        }
    });
    try {
        counter.start();
    } catch (KeeperException.NotReadOnlyException ex) {
    // In read only mode the counter is not going to start.
    // If the connection is reestablished the component will reactivate.
    // We need to catch this error so that the component gets activated.
    }
    if (gitGcOnLoad) {
        LockHandle writeLock = aquireWriteLock();
        try {
            GitOperation<Void> gitop = new GitOperation<Void>() {

                public Void call(Git git, GitContext context) throws Exception {
                    long before = System.currentTimeMillis();
                    try {
                        git.gc().call();
                        LOGGER.debug("git gc took " + ((System.currentTimeMillis() - before)) + " ms.");
                    } catch (GitAPIException e) {
                        LOGGER.debug("git gc threw an exception!", e);
                    }
                    return null;
                }
            };
            executeInternal(new GitContext(), null, gitop);
        } finally {
            writeLock.unlock();
        }
    }
    // failing to activate the component
    if (readWriteLock.isWriteLockedByCurrentThread() || readWriteLock.getWriteHoldCount() == 0) {
        try {
            // let's delegate to other thread in order to free MCF thread
            // ENTESB-7843: there's a problem when jetty is configured with TLS and keystore location using
            // profile: URI. while Jetty continues to be configured if profile:jetty.xml isn't available
            // (and it isn't initially), it fails trying to access keystore via profile: URI.
            // we should optimistically assume we can pull, but there's nothing wrong if we can't
            // - we'll be able to pull later
            threadPoolInitial.execute(new Runnable() {

                @Override
                public void run() {
                    doPullInternal(5);
                }
            });
        } catch (IllegalStateException e) {
            LOGGER.info("Another thread acquired write lock and GitDataStore can't pull from remote repository.");
        }
    } else {
        LOGGER.info("Another thread is keeping git write lock. GitDataStore will continue activation.");
    }
}
Also used : SharedCount(org.apache.curator.framework.recipes.shared.SharedCount) ProxySelector(java.net.ProxySelector) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) CuratorFramework(org.apache.curator.framework.CuratorFramework) DataStoreTemplate(io.fabric8.api.DataStoreTemplate) SharedCountListener(org.apache.curator.framework.recipes.shared.SharedCountListener) GitProxyService(io.fabric8.git.GitProxyService) LockHandle(io.fabric8.api.LockHandle) SharedCountReader(org.apache.curator.framework.recipes.shared.SharedCountReader) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FabricException(io.fabric8.api.FabricException) KeeperException(org.apache.zookeeper.KeeperException) MalformedURLException(java.net.MalformedURLException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) GitContext(io.fabric8.api.GitContext) ConnectionState(org.apache.curator.framework.state.ConnectionState) KeeperException(org.apache.zookeeper.KeeperException)

Aggregations

ArrayList (java.util.ArrayList)4 External (io.fabric8.annotations.External)3 PortName (io.fabric8.annotations.PortName)3 Protocol (io.fabric8.annotations.Protocol)3 ServiceName (io.fabric8.annotations.ServiceName)3 LockHandle (io.fabric8.api.LockHandle)3 Alias (io.fabric8.annotations.Alias)2 Configuration (io.fabric8.annotations.Configuration)2 Endpoint (io.fabric8.annotations.Endpoint)2 Path (io.fabric8.annotations.Path)2 Service (io.fabric8.kubernetes.api.model.Service)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)2 IOException (java.io.IOException)2 Type (java.lang.reflect.Type)2 List (java.util.List)2 Set (java.util.Set)2 DeploymentEndpoints (com.liveperson.ephemerals.deploy.DeploymentEndpoints)1 ResourceUtils.addIdentityRequirement (io.fabric8.agent.resolver.ResourceUtils.addIdentityRequirement)1 DataStoreTemplate (io.fabric8.api.DataStoreTemplate)1