Search in sources :

Example 16 with FabricException

use of io.fabric8.api.FabricException in project fabric8 by jboss-fuse.

the class ZooKeeperUtils method generateContainerToken.

public static String generateContainerToken(RuntimeProperties sysprops, CuratorFramework curator) {
    String container = sysprops.getRuntimeIdentity();
    long time = System.currentTimeMillis();
    String password = null;
    try {
        if (time - lastTokenGenerationTime < 60 * 1000) {
            try {
                password = getStringData(curator, CONTAINERS_NODE + "/" + container);
            } catch (KeeperException.NoNodeException ex) {
            // Node hasn't been created yet. It's safe to ignore.
            }
        }
        if (password == null) {
            password = generatePassword();
            setData(curator, CONTAINERS_NODE + "/" + container, password);
            lastTokenGenerationTime = time;
        }
    } catch (KeeperException.NotReadOnlyException e) {
        throw new FabricException("ZooKeeper server is partitioned. Currently working in read-only mode!");
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception ex) {
        throw new IllegalStateException("Cannot generate container token", ex);
    }
    return password;
}
Also used : FabricException(io.fabric8.api.FabricException) KeeperException(org.apache.zookeeper.KeeperException) URISyntaxException(java.net.URISyntaxException) FabricException(io.fabric8.api.FabricException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 17 with FabricException

use of io.fabric8.api.FabricException in project fabric8 by jboss-fuse.

the class FabricPatchServiceImpl method synchronize.

@Override
public String synchronize(final boolean verbose) throws Exception {
    final String[] remoteUrl = new String[] { null };
    patchManagement.pushPatchInfo(verbose);
    GitOperation operation = new GitOperation() {

        @Override
        public Object call(Git git, GitContext context) throws Exception {
            ProfileRegistry registry = fabricService.adapt(ProfileRegistry.class);
            Map<String, String> properties = registry.getDataStoreProperties();
            String username;
            String password;
            if (properties != null && properties.containsKey("gitRemoteUser") && properties.containsKey("gitRemotePassword")) {
                username = properties.get("gitRemoteUser");
                password = properties.get("gitRemotePassword");
            } else {
                username = ZooKeeperUtils.getContainerLogin(runtimeProperties);
                password = ZooKeeperUtils.generateContainerToken(runtimeProperties, curator);
            }
            remoteUrl[0] = git.getRepository().getConfig().getString("remote", "origin", "url");
            Iterable<PushResult> results = git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).setPushTags().setPushAll().call();
            logPushResult(results, git.getRepository(), verbose);
            return null;
        }
    };
    try {
        gitDataStore.gitOperation(new GitContext(), operation, null);
    } catch (FabricException e) {
        if (e.getCause() != null && e.getCause() instanceof TransportException) {
            LOG.warn("Problem when synchronizing patch information: " + e.getCause().getMessage());
        } else {
            throw e;
        }
    }
    return remoteUrl[0];
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitOperation(io.fabric8.git.internal.GitOperation) Git(org.eclipse.jgit.api.Git) GitContext(io.fabric8.api.GitContext) FabricException(io.fabric8.api.FabricException) ProfileRegistry(io.fabric8.api.ProfileRegistry) PushResult(org.eclipse.jgit.transport.PushResult) TransportException(org.eclipse.jgit.api.errors.TransportException)

Example 18 with FabricException

use of io.fabric8.api.FabricException in project fabric8 by jboss-fuse.

the class FabricServiceImpl method substituteConfigurations.

/**
 * Performs substitution to configuration based on the registered {@link PlaceholderResolver} instances.
 */
public Map<String, Map<String, String>> substituteConfigurations(final Map<String, Map<String, String>> configurations) {
    final Map<String, PlaceholderResolver> resolversSnapshot = new HashMap<String, PlaceholderResolver>(placeholderResolvers);
    // Check that all resolvers are available
    Set<String> requiredSchemes = getSchemesForProfileConfigurations(configurations);
    Set<String> availableSchemes = resolversSnapshot.keySet();
    if (!availableSchemes.containsAll(requiredSchemes)) {
        StringBuilder sb = new StringBuilder();
        sb.append("Missing Placeholder Resolvers:");
        for (String scheme : requiredSchemes) {
            if (!availableSchemes.contains(scheme)) {
                sb.append(" ").append(scheme);
            }
        }
        throw new FabricException(sb.toString());
    }
    final Map<String, Map<String, String>> mutableConfigurations = new HashMap<>();
    for (Entry<String, Map<String, String>> entry : configurations.entrySet()) {
        String key = entry.getKey();
        Map<String, String> value = new HashMap<>(entry.getValue());
        mutableConfigurations.put(key, value);
    }
    final FabricService fabricService = this;
    for (Map.Entry<String, Map<String, String>> entry : mutableConfigurations.entrySet()) {
        final String pid = entry.getKey();
        Map<String, String> props = entry.getValue();
        Map<String, String> original = new HashMap<>(props);
        for (Map.Entry<String, String> e : original.entrySet()) {
            final String key = e.getKey();
            final String value = e.getValue();
            try {
                props.put(key, InterpolationHelper.substVars(value, key, null, props, new InterpolationHelper.SubstitutionCallback() {

                    public String getValue(String toSubstitute) {
                        if (toSubstitute != null && toSubstitute.contains(":")) {
                            String scheme = toSubstitute.substring(0, toSubstitute.indexOf(":"));
                            return resolversSnapshot.get(scheme).resolve(fabricService, mutableConfigurations, pid, key, toSubstitute);
                        }
                        return substituteBundleProperty(toSubstitute, bundleContext);
                    }
                }));
            } catch (EncryptionOperationNotPossibleException exception) {
                LOGGER.warn("Error resolving " + key, exception);
            }
        }
    }
    return mutableConfigurations;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) FabricException(io.fabric8.api.FabricException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricService(io.fabric8.api.FabricService) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) PlaceholderResolver(io.fabric8.api.PlaceholderResolver)

Example 19 with FabricException

use of io.fabric8.api.FabricException in project fabric8 by jboss-fuse.

the class FabricServiceImpl method destroyContainer.

public void destroyContainer(Container container, boolean force) {
    assertValid();
    String containerId = container.getId();
    Exception providerException = null;
    LOGGER.info("Destroying container {}", containerId);
    boolean destroyed = false;
    try {
        ContainerProvider provider = getProvider(container, true);
        if (provider != null) {
            try {
                provider.stop(container);
            } catch (Exception ex) {
                // Ignore error while stopping and try to destroy.
                // and if its already stopped then ignore the exception and do not rethrow later
                boolean stopped = "Instance already stopped".equals(ex.getMessage());
                if (!stopped) {
                    providerException = ex;
                }
            }
            provider.destroy(container);
            destroyed = true;
        } else {
            throw new FabricException("Container's lifecycle not managed by Fabric8 (the container was not created by Fabric8).");
        }
    } finally {
        try {
            if (destroyed || force) {
                try {
                    portService.get().unregisterPort(container);
                } catch (Exception e) {
                    LOGGER.warn("Failed to cleanup container {} entries due to: {}. This will be ignored.", containerId, e.getMessage());
                }
                dataStore.get().deleteContainer(this, container.getId());
            }
        } catch (Exception e) {
            LOGGER.warn("Failed to cleanup container {} entries due to: {}. This will be ignored.", containerId, e.getMessage());
        }
        if (providerException != null) {
            throw FabricException.launderThrowable(providerException);
        }
    }
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) FabricException(io.fabric8.api.FabricException) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 20 with FabricException

use of io.fabric8.api.FabricException in project fabric8 by jboss-fuse.

the class FabricServiceImpl method createContainers.

@Override
public CreateContainerMetadata[] createContainers(CreateContainerOptions options, CreationStateListener listener) {
    assertValid();
    try {
        final ContainerProvider provider = getProvider(options.getProviderType());
        if (provider == null) {
            throw new FabricException("Unable to find a container provider supporting '" + options.getProviderType() + "'");
        }
        if (!provider.isValidProvider()) {
            throw new FabricException("The provider '" + options.getProviderType() + "' is not valid in current environment");
        }
        String originalName = options.getName();
        if (originalName == null || originalName.length() == 0) {
            throw new FabricException("A name must be specified when creating containers");
        }
        // Only allow containers with valid names to get created.
        FabricValidations.validateContainerName(originalName);
        if (listener == null) {
            listener = new NullCreationStateListener();
        }
        validateProfileDependencies(options);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Map optionsMap = mapper.readValue(mapper.writeValueAsString(options), Map.class);
        String versionId = options.getVersion() != null ? options.getVersion() : dataStore.get().getDefaultVersion();
        Set<String> profileIds = options.getProfiles();
        if (profileIds == null || profileIds.isEmpty()) {
            profileIds = new LinkedHashSet<String>();
            profileIds.add("default");
        }
        optionsMap.put("version", versionId);
        optionsMap.put("profiles", profileIds);
        optionsMap.put("number", 0);
        // assign parent resolver if it's a child container, else assign global resolver policy
        if (bootstrapConfig != null) {
            String configuredGlobalResolver = bootstrapConfig.getGlobalResolver();
            if (!Strings.isNullOrEmpty(configuredGlobalResolver)) {
                optionsMap.put("globalResolver", configuredGlobalResolver);
                if (optionsMap.get("resolver") == null) {
                    if (optionsMap.get("parent") == null) {
                        optionsMap.put("resolver", configuredGlobalResolver);
                    }
                }
            }
        }
        final List<CreateContainerMetadata> metadatas = new CopyOnWriteArrayList<CreateContainerMetadata>();
        int orgNumber = options.getNumber();
        int number = Math.max(orgNumber, 1);
        if (orgNumber > 1) {
            originalName = originalName + "1";
        }
        final CountDownLatch latch = new CountDownLatch(number);
        Set<String> ignoreContainerNames = new HashSet<>();
        Container[] containers = getContainers();
        // check that there is no container with the given name
        for (Container container : containers) {
            if (container.getId().equals(options.getName())) {
                throw new IllegalArgumentException("A container with name " + options.getName() + " already exists.");
            }
        }
        for (int i = 1; i <= number; i++) {
            NameValidator validator = Containers.createNameValidator(containers, ignoreContainerNames);
            final String containerName = Containers.createUniqueContainerName(containers, originalName, validator);
            ignoreContainerNames.add(containerName);
            optionsMap.put("name", containerName);
            // Check if datastore configuration has been specified and fallback to current container settings.
            if (!hasValidDataStoreProperties(optionsMap)) {
                optionsMap.put("dataStoreProperties", profileRegistry.get().getDataStoreProperties());
            }
            Class cl = options.getClass().getClassLoader().loadClass(options.getClass().getName() + "$Builder");
            CreateContainerBasicOptions.Builder builder = (CreateContainerBasicOptions.Builder) mapper.readValue(mapper.writeValueAsString(optionsMap), cl);
            // We always want to pass the obfuscated version of the password to the container provider.
            builder = (CreateContainerBasicOptions.Builder) builder.zookeeperPassword(PasswordEncoder.encode(getZookeeperPassword()));
            final CreateContainerOptions containerOptions = builder.build();
            final CreationStateListener containerListener = listener;
            final FabricService fabricService = this;
            new Thread("Creating container " + containerName) {

                public void run() {
                    try {
                        if (dataStore.get().hasContainer(containerName)) {
                            CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                            metadata.setContainerName(containerName);
                            metadata.setCreateOptions(containerOptions);
                            metadata.setFailure(new IllegalArgumentException("A container with name " + containerName + " already exists."));
                            metadatas.add(metadata);
                            return;
                        }
                        dataStore.get().createContainerConfig(containerOptions);
                        CreateContainerMetadata metadata = provider.create(containerOptions, containerListener);
                        if (metadata.isSuccess()) {
                            Container parent = containerOptions.getParent() != null ? getContainer(containerOptions.getParent()) : null;
                            // TODO: We need to make sure that this entries are somehow added even to ensemble servers.
                            if (!containerOptions.isEnsembleServer()) {
                                dataStore.get().createContainerConfig(metadata);
                            }
                            ContainerImpl container = new ContainerImpl(parent, metadata.getContainerName(), FabricServiceImpl.this);
                            metadata.setContainer(container);
                            LOGGER.info("The container " + metadata.getContainerName() + " has been successfully created");
                        } else {
                            LOGGER.warn("The creation of the container " + metadata.getContainerName() + " has failed", metadata.getFailure());
                            dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                        }
                        metadatas.add(metadata);
                    } catch (Throwable t) {
                        CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                        metadata.setContainerName(containerName);
                        metadata.setCreateOptions(containerOptions);
                        metadata.setFailure(t);
                        metadatas.add(metadata);
                        dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                    } finally {
                        latch.countDown();
                    }
                }
            }.start();
        }
        if (!latch.await(30, TimeUnit.MINUTES)) {
            throw new FabricException("Timeout waiting for container creation");
        }
        return metadatas.toArray(new CreateContainerMetadata[metadatas.size()]);
    } catch (Exception e) {
        LOGGER.error("Failed to create containers " + e, e);
        throw FabricException.launderThrowable(e);
    }
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) NameValidator(io.fabric8.api.NameValidator) ProfileBuilder(io.fabric8.api.ProfileBuilder) FabricException(io.fabric8.api.FabricException) CreateContainerOptions(io.fabric8.api.CreateContainerOptions) Container(io.fabric8.api.Container) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) CountDownLatch(java.util.concurrent.CountDownLatch) CreateContainerBasicMetadata(io.fabric8.api.CreateContainerBasicMetadata) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) CreationStateListener(io.fabric8.api.CreationStateListener) FabricService(io.fabric8.api.FabricService) ContainerImpl(io.fabric8.internal.ContainerImpl) CreateContainerBasicOptions(io.fabric8.api.CreateContainerBasicOptions) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

FabricException (io.fabric8.api.FabricException)29 IOException (java.io.IOException)10 Container (io.fabric8.api.Container)7 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)6 Lease (org.apache.curator.framework.recipes.locks.Lease)6 HashSet (java.util.HashSet)5 EncryptionOperationNotPossibleException (org.jasypt.exceptions.EncryptionOperationNotPossibleException)5 Session (com.jcraft.jsch.Session)4 FabricService (io.fabric8.api.FabricService)3 Profile (io.fabric8.api.Profile)3 ProfileDependencyException (io.fabric8.api.ProfileDependencyException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 SortedMap (java.util.SortedMap)3 TreeMap (java.util.TreeMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ContainerProvider (io.fabric8.api.ContainerProvider)2 ProfileBuilder (io.fabric8.api.ProfileBuilder)2