Search in sources :

Example 11 with External

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

the class DummyBatchingProgressMonitor method doPush.

@Override
public Iterable<PushResult> doPush(Git git, GitContext context) throws Exception {
    IllegalArgumentAssertion.assertNotNull(git, "git");
    IllegalArgumentAssertion.assertNotNull(context, "context");
    LockHandle writeLock = aquireWriteLock();
    try {
        assertValid();
        LOGGER.debug("External call to push");
        PushPolicyResult pushResult = doPushInternal(context, getCredentialsProvider());
        return pushResult.getPushResults();
    } finally {
        writeLock.unlock();
    }
}
Also used : LockHandle(io.fabric8.api.LockHandle) PushPolicyResult(io.fabric8.git.PullPushPolicy.PushPolicyResult)

Example 12 with External

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

the class CreateAction method doExecute.

protected Object doExecute() throws Exception {
    String adminRole = "admin";
    String administratorRole = "administrator";
    String superUserRole = "superuser";
    boolean adminExists = hasRole(adminRole, superUserRole, administratorRole);
    if (!adminExists) {
        System.out.println("The fabric:create command can be executed only by admin user");
        return null;
    }
    Path propsPath = runtimeProperties.getConfPath().resolve("users.properties");
    Properties userProps = new Properties(propsPath.toFile());
    if (!adminExists && !usersPropertiesFileContainsRole(userProps, adminRole, superUserRole, administratorRole)) {
        System.out.println("The etc/user.properties file must contain at least one admin user, if no other admin exists");
        return null;
    }
    // prevent creating fabric if already created
    ServiceReference<FabricService> sref = bundleContext.getServiceReference(FabricService.class);
    FabricService fabricService = sref != null ? bundleContext.getService(sref) : null;
    if (!force && (fabricService != null && fabricService.getCurrentContainer().isEnsembleServer())) {
        System.out.println("Current container " + fabricService.getCurrentContainerName() + " is already in the current fabric ensemble. Cannot create fabric.");
        System.out.println("You can use the --force option, if you want to force re-create the fabric.");
        return null;
    }
    Configuration bootConfiguration = configAdmin.getConfiguration(BootstrapConfiguration.COMPONENT_PID, null);
    Dictionary<String, Object> bootProperties = bootConfiguration.getProperties();
    if (bootProperties == null) {
        bootProperties = new Hashtable<>();
    }
    String runtimeIdentity = runtimeProperties.getRuntimeIdentity();
    CreateEnsembleOptions.Builder<?> builder = CreateEnsembleOptions.builder().zooKeeperServerTickTime(zooKeeperTickTime).zooKeeperServerInitLimit(zooKeeperInitLimit).zooKeeperServerSyncLimit(zooKeeperSyncLimit).zooKeeperServerDataDir(zooKeeperDataDir).zookeeperSnapRetainCount(zookeeperSnapRetainCount).zookeeperPurgeInterval(zookeeperPurgeInterval).fromRuntimeProperties(runtimeProperties).bootstrapTimeout(bootstrapTimeout).waitForProvision(waitForProvisioning).autoImportEnabled(!noImport).clean(clean);
    builder.version(version);
    if (containers == null || containers.isEmpty()) {
        containers = Arrays.asList(runtimeIdentity);
    }
    if (!noImport && importDir != null) {
        builder.autoImportEnabled(true);
        builder.importPath(importDir);
    }
    if (globalResolver != null) {
        if (!isInEnum(globalResolver, ResolverPolicyEnum.class)) {
            System.out.println("The globalResolver value must be one of the following: localip, localhostname, publicip, publichostname, manualip");
            return null;
        }
        builder.globalResolver(globalResolver);
        bootProperties.put(ZkDefs.GLOBAL_RESOLVER_PROPERTY, globalResolver);
    }
    if (resolver != null) {
        if (!isInEnum(resolver, ResolverPolicyEnum.class)) {
            System.out.println("The resolver value must be one of the following: localip, localhostname, publicip, publichostname, manualip");
            return null;
        }
        builder.resolver(resolver);
        bootProperties.put(ZkDefs.LOCAL_RESOLVER_PROPERTY, resolver);
    }
    if (manualIp != null) {
        builder.manualIp(manualIp);
        bootProperties.put(ZkDefs.MANUAL_IP, manualIp);
    }
    if (bindAddress != null) {
        if (!bindAddress.contains(":")) {
            builder.bindAddress(bindAddress);
            bootProperties.put(ZkDefs.BIND_ADDRESS, bindAddress);
        } else {
            String[] parts = bindAddress.split(":");
            builder.bindAddress(parts[0]);
            builder.zooKeeperServerPort(Integer.parseInt(parts[1]));
            bootProperties.put(ZkDefs.BIND_ADDRESS, parts[0]);
        }
    }
    if (zooKeeperServerPort > 0) {
        // --zookeeper-server-port option has higher priority than
        // CreateEnsembleOptions.ZOOKEEPER_SERVER_PORT and CreateEnsembleOptions.ZOOKEEPER_SERVER_CONNECTION_PORT
        // system/runtime properties
        builder.setZooKeeperServerPort(zooKeeperServerPort);
        builder.setZooKeeperServerConnectionPort(zooKeeperServerPort);
    } else {
        int shiftedPort = Ports.mapPortToRange(2181, minimumPort, maximumPort);
        builder.setZooKeeperServerPort(shiftedPort);
        builder.setZooKeeperServerConnectionPort(shiftedPort);
    }
    // Configure External Git Repository.
    if (externalGitUrl != null) {
        builder.dataStoreProperty(Constants.GIT_REMOTE_URL, externalGitUrl);
    }
    if (externalGitUser != null) {
        builder.dataStoreProperty(GIT_REMOTE_USER, externalGitUser);
    }
    if (externalGitPassword != null) {
        builder.dataStoreProperty(GIT_REMOTE_PASSWORD, externalGitPassword);
    }
    if ((externalGitUrl != null) || (externalGitUser != null) || (externalGitPassword != null)) {
        Configuration configuration = configAdmin.getConfiguration(Constants.DATASTORE_PID);
        Dictionary<String, Object> existingProperties = configuration.getProperties();
        Map<String, String> changedProperties = builder.getDataStoreProperties();
        for (String key : changedProperties.keySet()) {
            existingProperties.put(key, changedProperties.get(key));
        }
        configuration.update(existingProperties);
    }
    if (profiles != null && profiles.size() > 0) {
        builder.profiles(profiles);
    }
    if (nonManaged) {
        builder.agentEnabled(false);
    } else {
        builder.agentEnabled(true);
    }
    builder.minimumPort(minimumPort);
    builder.maximumPort(maximumPort);
    bootProperties.put(ZkDefs.MINIMUM_PORT, String.valueOf(minimumPort));
    bootProperties.put(ZkDefs.MAXIMUM_PORT, String.valueOf(maximumPort));
    newUser = newUser != null ? newUser : ShellUtils.retrieveFabricUser(session);
    newUserPassword = newUserPassword != null ? newUserPassword : ShellUtils.retrieveFabricUserPassword(session);
    if (userProps.isEmpty()) {
        String[] credentials = promptForNewUser(newUser, newUserPassword);
        newUser = credentials[0];
        newUserPassword = credentials[1];
    } else {
        if (newUser == null || newUserPassword == null) {
            newUser = "" + userProps.keySet().iterator().next();
            newUserPassword = "" + userProps.get(newUser);
            if (newUserPassword.contains(ROLE_DELIMITER)) {
                newUserPassword = newUserPassword.substring(0, newUserPassword.indexOf(ROLE_DELIMITER));
            }
        }
        String passwordWithroles = userProps.get(newUser);
        if (passwordWithroles != null && passwordWithroles.contains(ROLE_DELIMITER)) {
            String[] infos = passwordWithroles.split(",");
            String oldUserRole = "";
            if (newUserIsAdmin(infos)) {
                newUserRole = "_g_:admin";
                oldUserRole = newUserRole;
            }
            for (int i = 1; i < infos.length; i++) {
                if (infos[i].trim().startsWith(BackingEngine.GROUP_PREFIX)) {
                    // it's a group reference
                    String groupInfo = (String) userProps.get(infos[i].trim());
                    if (groupInfo != null) {
                        String[] roles = groupInfo.split(",");
                        for (int j = 1; j < roles.length; j++) {
                            if (!roles[j].trim().equals(oldUserRole)) {
                                if (!newUserRole.isEmpty()) {
                                    newUserRole = newUserRole + ROLE_DELIMITER + roles[j].trim();
                                } else {
                                    newUserRole = roles[j].trim();
                                }
                            }
                        }
                    }
                } else {
                    // it's an user reference
                    if (!infos[i].trim().equals(oldUserRole)) {
                        if (!newUserRole.isEmpty()) {
                            newUserRole = newUserRole + ROLE_DELIMITER + infos[i].trim();
                        } else {
                            newUserRole = infos[i].trim();
                        }
                    }
                }
            }
        }
    }
    if (Strings.isNullOrEmpty(newUser)) {
        System.out.println("No user specified. Cannot create a new fabric ensemble.");
        return null;
    }
    StringBuilder sb = new StringBuilder();
    // session is unset when this is called from FMC
    if (session != null) {
        ShellUtils.storeFabricCredentials(session, newUser, newUserPassword);
    }
    if (generateZookeeperPassword) {
    // do nothing use the generated password.
    } else if (zookeeperPassword == null) {
        zookeeperPassword = PasswordEncoder.decode(runtimeProperties.getProperty(CreateEnsembleOptions.ZOOKEEPER_PASSWORD, PasswordEncoder.encode(newUserPassword)));
        builder.zookeeperPassword(zookeeperPassword);
    } else {
        builder.zookeeperPassword(zookeeperPassword);
    }
    OsgiUtils.updateCmConfigurationAndWait(bundleContext, bootConfiguration, bootProperties, bootstrapTimeout, TimeUnit.MILLISECONDS);
    String roleToAssign = newUserRole.isEmpty() ? "_g_:admin" : newUserRole;
    CreateEnsembleOptions options = builder.users(userProps).withUser(newUser, newUserPassword, roleToAssign).build();
    if (containers.size() == 1 && containers.contains(runtimeIdentity)) {
        bootstrap.create(options);
    } else {
        ServiceProxy<ZooKeeperClusterService> serviceProxy = ServiceProxy.createServiceProxy(bundleContext, ZooKeeperClusterService.class);
        try {
            serviceProxy.getService().createCluster(containers, options);
        } finally {
            serviceProxy.close();
        }
    }
    ShellUtils.storeZookeeperPassword(session, options.getZookeeperPassword());
    if (zookeeperPassword == null && !generateZookeeperPassword) {
        sb.append("Zookeeper password: (reusing users ").append(newUser).append(" password:").append(options.getZookeeperPassword()).append(")\n");
        sb.append("(You can use the --zookeeper-password / --generate-zookeeper-password option to specify one.)\n");
    } else if (generateZookeeperPassword) {
        sb.append("Generated zookeeper password:").append(options.getZookeeperPassword());
    }
    System.out.println(sb.toString());
    if (!nonManaged && !waitForProvisioning) {
        System.out.println("It may take a couple of seconds for the container to provision...");
        System.out.println("You can use the --wait-for-provisioning option, if you want this command to block until the container is provisioned.");
    }
    return null;
}
Also used : Path(java.nio.file.Path) Configuration(org.osgi.service.cm.Configuration) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) ResolverPolicyEnum(io.fabric8.boot.commands.support.ResolverPolicyEnum) Properties(org.apache.felix.utils.properties.Properties)

Example 13 with External

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

the class AbstractLiveEnricher method getExternalServiceURL.

/**
 * Returns the external access to the given service name
 *
 * @param serviceName name of the service
 * @param protocol URL protocol such as <code>http</code>
 */
protected String getExternalServiceURL(String serviceName, String protocol) {
    if (!isOnline()) {
        getLog().info("Not looking for service " + serviceName + " as we are in offline mode");
        return null;
    } else {
        try {
            KubernetesClient kubernetes = getKubernetes();
            String ns = kubernetes.getNamespace();
            if (Strings.isNullOrBlank(ns)) {
                ns = getNamespace();
            }
            Service service = kubernetes.services().inNamespace(ns).withName(serviceName).get();
            return service != null ? KubernetesHelper.getServiceURL(kubernetes, serviceName, ns, protocol, true) : null;
        } catch (Throwable e) {
            Throwable cause = e;
            boolean notFound = false;
            boolean connectError = false;
            Stack<Throwable> stack = unfoldExceptions(e);
            while (!stack.isEmpty()) {
                Throwable t = stack.pop();
                if (t instanceof ConnectException || "No route to host".equals(t.getMessage())) {
                    getLog().warn("Cannot connect to Kubernetes to find URL for service %s : %s", serviceName, cause.getMessage());
                    return null;
                } else if (t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().matches("^No.*found.*$")) {
                    getLog().warn("%s", cause.getMessage());
                    return null;
                }
                ;
            }
            getLog().warn("Cannot find URL for service %s : %s", serviceName, cause.getMessage());
            return null;
        }
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Service(io.fabric8.kubernetes.api.model.Service) Stack(java.util.Stack) ConnectException(java.net.ConnectException)

Example 14 with External

use of io.fabric8.annotations.External in project ephemerals by LivePersonInc.

the class KubernetesDeploymentEndpointWaiter method getDeploymentEndpoint.

@Override
protected DeploymentEndpoints.Endpoint getDeploymentEndpoint() {
    String ip = null;
    int port = 0;
    String serviceType = kubernetesClient.services().withName(deployment.getId()).get().getSpec().getType();
    logger.debug("Kubernetes service type: " + serviceType);
    if (serviceType.equals("LoadBalancer")) {
        ip = kubernetesClient.services().withName(deployment.getId()).get().getStatus().getLoadBalancer().getIngress().get(0).getIp();
    } else {
        // nodeport
        List<ServicePort> servicePortList = kubernetesClient.services().withName(deployment.getId()).get().getSpec().getPorts();
        for (ServicePort servicePort : servicePortList) {
            if (servicePort.getPort().equals(deploymentPort.getPort())) {
                port = servicePort.getNodePort();
            }
        }
        /**
         * Fetch Node IP address:
         *  - External IP takes precedence over internal IP
         *  - If external IP isn't found, return internal IP
         *  - If both IPs not found, return null
         */
        // Since node port is shared across all nodes, use first node
        List<NodeAddress> nodeAddressList = kubernetesClient.nodes().list().getItems().get(0).getStatus().getAddresses();
        String nodeInternalIp = null, nodeExternalIp = null;
        for (NodeAddress nodeAddress : nodeAddressList) {
            if (nodeAddress.getType().equals("ExternalIP")) {
                nodeExternalIp = nodeAddress.getAddress();
            } else if (nodeAddress.getType().equals("InternalIP")) {
                nodeInternalIp = nodeAddress.getAddress();
            }
        }
        // External IP takes precedence over internal IP
        if (nodeExternalIp != null) {
            ip = nodeExternalIp;
            logger.debug("Using node ExternalIP: " + nodeExternalIp);
        } else if (nodeInternalIp != null) {
            ip = nodeInternalIp;
            logger.debug("Using node InternalIP: " + nodeInternalIp);
        }
    }
    if (ip == null) {
        logger.info("Endpoint not found");
        return null;
    } else {
        logger.info("Endpoint found...");
        logger.info(String.format("Checking connection to endpoint IP %s and port %d", ip, port));
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, port), 2 * 1000);
            logger.info("Endpoint is reachable");
            endpoint = new DeploymentEndpoints.Endpoint(deploymentPort.getName(), ip, port);
            return endpoint;
        } catch (IOException e) {
            logger.warn("Endpoint is unreachable");
            // Either timeout or unreachable or failed DNS lookup.
            return null;
        }
    }
}
Also used : ServicePort(io.fabric8.kubernetes.api.model.ServicePort) DeploymentEndpoints(com.liveperson.ephemerals.deploy.DeploymentEndpoints) InetSocketAddress(java.net.InetSocketAddress) NodeAddress(io.fabric8.kubernetes.api.model.NodeAddress) IOException(java.io.IOException) Socket(java.net.Socket)

Example 15 with External

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

the class FactoryMethodProducer method produce.

@Override
public T produce(CreationalContext<T> ctx) {
    List<Object> arguments = new ArrayList<>();
    for (AnnotatedParameter<X> parameter : factoryMethod.getParameters()) {
        Type type = parameter.getBaseType();
        ServiceName parameterServiceName = parameter.getAnnotation(ServiceName.class);
        Protocol parameterProtocol = parameter.getAnnotation(Protocol.class);
        PortName parameterPortName = parameter.getAnnotation(PortName.class);
        Path parameterPath = parameter.getAnnotation(Path.class);
        Endpoint paramEndpoint = parameter.getAnnotation(Endpoint.class);
        External paramExternal = parameter.getAnnotation(External.class);
        Configuration configuration = parameter.getAnnotation(Configuration.class);
        // A point without @ServiceName is invalid.
        // Even if method defines @ServiceName, the annotation on the injection point takes precedence
        String serviceName = pointName;
        String serviceProtocol = or(pointProtocol, parameterProtocol != null ? parameterProtocol.value() : null);
        String servicePort = or(pointPort, parameterPortName != null ? parameterPortName.value() : null);
        String servicePath = or(pointPath, parameterPath != null ? parameterPath.value() : null);
        Boolean serviceEndpoint = paramEndpoint != null ? paramEndpoint.value() : false;
        Boolean serviceExternal = paramExternal != null ? paramExternal.value() : false;
        // If the @ServiceName exists on the current String property
        if (parameterServiceName != null && String.class.equals(type)) {
            try {
                String serviceUrl = getServiceUrl(serviceName, serviceProtocol, servicePort, servicePath, serviceEndpoint, serviceExternal, ctx);
                arguments.add(serviceUrl);
            } catch (Throwable t) {
                throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
            }
        } else // If the @ServiceName exists on the current List property
        if (parameterServiceName != null && List.class.equals(Types.asClass(type))) {
            try {
                List<String> endpointList = getEndpointList(serviceName, serviceProtocol, servicePort, servicePath, serviceExternal, ctx);
                arguments.add(endpointList);
            } catch (Throwable t) {
                throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
            }
        } else // If the @ServiceName exists on the current List property
        if (parameterServiceName != null && Set.class.equals(Types.asClass(type))) {
            try {
                List<String> endpointList = getEndpointList(serviceName, serviceProtocol, servicePort, servicePath, serviceExternal, ctx);
                arguments.add(new HashSet<>(endpointList));
            } catch (Throwable t) {
                throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
            }
        } else // If the @ServiceName exists on the current property which is a non-String
        if (parameterServiceName != null && !String.class.equals(type)) {
            try {
                Object serviceBean = getServiceBean(serviceName, serviceProtocol, servicePort, servicePath, serviceEndpoint, serviceExternal, type, ctx);
                arguments.add(serviceBean);
            } catch (Throwable t) {
                throw new RuntimeException(String.format(BEAN_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), type, serviceName), t);
            }
        } else // If the current parameter is annotated with @Configuration
        if (configuration != null) {
            try {
                Object config = getConfiguration(serviceName, (Class<Object>) type, ctx);
                arguments.add(config);
            } catch (Throwable t) {
                throw new RuntimeException(String.format(CONF_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
            }
        } else {
            try {
                Object other = BeanProvider.getContextualReference(Types.asClass(type), true);
                arguments.add(other);
            } catch (Throwable t) {
                throw new RuntimeException(String.format(PARAMETER_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), parameter.getPosition()), t);
            }
        }
    }
    try {
        return (T) factoryMethod.getJavaMember().invoke(bean.create(ctx), arguments.toArray());
    } catch (Throwable t) {
        throw new RuntimeException(String.format(INVOCATION_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), arguments), t);
    }
}
Also used : Path(io.fabric8.annotations.Path) HashSet(java.util.HashSet) Set(java.util.Set) Configuration(io.fabric8.annotations.Configuration) ArrayList(java.util.ArrayList) PortName(io.fabric8.annotations.PortName) Type(java.lang.reflect.Type) Endpoint(io.fabric8.annotations.Endpoint) ServiceName(io.fabric8.annotations.ServiceName) External(io.fabric8.annotations.External) ArrayList(java.util.ArrayList) List(java.util.List) Protocol(io.fabric8.annotations.Protocol)

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