Search in sources :

Example 11 with Block

use of io.fabric8.utils.Block in project docker-maven-plugin by fabric8io.

the class LogsMojo method executeInternal.

@Override
protected void executeInternal(ServiceHub hub) throws MojoExecutionException, DockerAccessException {
    QueryService queryService = hub.getQueryService();
    LogDispatcher logDispatcher = getLogDispatcher(hub);
    for (ImageConfiguration image : getResolvedImages()) {
        String imageName = image.getName();
        if (logAll) {
            for (Container container : queryService.getContainersForImage(imageName)) {
                doLogging(logDispatcher, image, container.getId());
            }
        } else {
            Container container = queryService.getLatestContainerForImage(imageName);
            if (container != null) {
                doLogging(logDispatcher, image, container.getId());
            }
        }
    }
    if (follow) {
        // Block forever ....
        waitForEver();
    }
}
Also used : Container(io.fabric8.maven.docker.model.Container) QueryService(io.fabric8.maven.docker.service.QueryService) ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) LogDispatcher(io.fabric8.maven.docker.log.LogDispatcher)

Example 12 with Block

use of io.fabric8.utils.Block 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 Block

use of io.fabric8.utils.Block in project fabric8 by fabric8io.

the class ExampleTest method testNavigationAssertions.

@Test
public void testNavigationAssertions() throws Exception {
    String expectedId = "abc";
    Map<String, String> expectedLabels = new HashMap<>();
    expectedLabels.put("foo", "bar");
    final Pod pod = new Pod();
    pod.setMetadata(new ObjectMeta());
    pod.getMetadata().setName(expectedId);
    pod.getMetadata().setLabels(expectedLabels);
    assertThat(pod).metadata().name().isEqualTo(expectedId);
    assertThat(pod).metadata().labels().isEqualTo(expectedLabels);
    assertAssertionError(new Block() {

        @Override
        public void invoke() throws Exception {
            assertThat(pod).metadata().name().isEqualTo("cheese");
        }
    });
    assertAssertionError(new Block() {

        @Override
        public void invoke() throws Exception {
            assertThat(pod).describedAs("my pod").metadata().name().isEqualTo("cheese");
        }
    });
    assertAssertionError(new Block() {

        @Override
        public void invoke() throws Exception {
            Map<String, String> wrongLabels = new HashMap<>();
            wrongLabels.put("bar", "whatnot");
            assertThat(pod).metadata().labels().isEqualTo(wrongLabels);
        }
    });
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) Pod(io.fabric8.kubernetes.api.model.Pod) HashMap(java.util.HashMap) Block(io.fabric8.utils.Block) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

Block (io.fabric8.utils.Block)11 Test (org.junit.Test)7 Pod (io.fabric8.kubernetes.api.model.Pod)4 IOException (java.io.IOException)3 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)2 JobWithDetails (com.offbytwo.jenkins.model.JobWithDetails)1 ResolverPolicyEnum (io.fabric8.boot.commands.support.ResolverPolicyEnum)1 PodList (io.fabric8.kubernetes.api.model.PodList)1 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)1 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)1 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)1 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)1 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)1 LogDispatcher (io.fabric8.maven.docker.log.LogDispatcher)1 Container (io.fabric8.maven.docker.model.Container)1 QueryService (io.fabric8.maven.docker.service.QueryService)1 Asserts.assertAssertionError (io.fabric8.utils.Asserts.assertAssertionError)1 BootstrapConfiguration (io.fabric8.zookeeper.bootstrap.BootstrapConfiguration)1