Search in sources :

Example 46 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class ZooKeeperClusterServiceImpl method publicPort.

private String publicPort(String containerName, final String port) {
    FabricService fabric = fabricService.get();
    Container container = fabric.getContainer(containerName);
    String user = ZooKeeperUtils.getContainerLogin(runtimeProperties.get());
    String password = "";
    try {
        Properties containerTokens = ZooKeeperUtils.getContainerTokens(obtainValid(curator));
        password = containerTokens.getProperty(user);
    } catch (Exception e) {
        LOGGER.error("Unable to get temp ZK user/pass for administrative purposes", e);
    }
    ContainerTemplate containerTemplate = new ContainerTemplate(container, user, password, false);
    return containerTemplate.execute(new JmxTemplateSupport.JmxConnectorCallback<String>() {

        @Override
        public String doWithJmxConnector(JMXConnector connector) throws Exception {
            return connector.getMBeanServerConnection().invoke(new ObjectName("io.fabric8:type=Fabric"), "getPublicPortOnCurrentContainer", new Object[] { new Integer(port) }, new String[] { "int" }).toString();
        }
    });
}
Also used : ContainerTemplate(io.fabric8.service.ContainerTemplate) JmxTemplateSupport(io.fabric8.service.JmxTemplateSupport) JMXConnector(javax.management.remote.JMXConnector) Properties(java.util.Properties) ObjectName(javax.management.ObjectName)

Example 47 with User

use of io.fabric8.openshift.api.model.User 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 48 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class InsightRequestLog method log.

@Override
public void log(Request request, Response response) {
    try {
        if (!enabled) {
            return;
        }
        StorageService s = storage.getService();
        if (s == null) {
            return;
        }
        if (ignorePathMap != null && ignorePathMap.getMatch(request.getRequestURI()) != null)
            return;
        String output = "{ " + "\"host\": \"" + host + "\", " + "\"@timestamp\": \"" + InsightUtils.formatDate(request.getTimeStamp()) + "\", " + "\"remote\": \"" + request.getRemoteAddr() + "\", " + "\"user\": \"" + (request.getAuthentication() instanceof Authentication.User ? ((Authentication.User) request.getAuthentication()).getUserIdentity().getUserPrincipal().getName() : "") + "\", " + "\"method\": \"" + request.getMethod() + "\", " + "\"uri\": \"" + request.getUri().toString() + "\", " + "\"protocol\": \"" + request.getProtocol() + "\", " + "\"status\": \"" + response.getStatus() + "\", " + "\"responseLength\": \"" + response.getContentCount() + "\" " + " }";
        s.store(type, request.getTimeStamp(), output);
    } catch (Exception e) {
        LOG.warn(e);
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) StorageService(io.fabric8.insight.storage.StorageService)

Example 49 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class OpenshiftContainerProvider method createNameValidator.

/**
 * Creates a name validator that checks there isn't an application of the given name already
 */
NameValidator createNameValidator(CreateOpenshiftContainerOptions options) {
    IUser user = getOrCreateConnection(options).getUser();
    final IDomain domain = getOrCreateDomain(user, options);
    return new NameValidator() {

        @Override
        public boolean isValid(String name) {
            IApplication application = domain.getApplicationByName(name);
            return application == null;
        }
    };
}
Also used : IDomain(com.openshift.client.IDomain) IApplication(com.openshift.client.IApplication) NameValidator(io.fabric8.api.NameValidator) IUser(com.openshift.client.IUser)

Example 50 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class MQProfileTest method testMQCreateBasic.

@Test
public void testMQCreateBasic() throws Exception {
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    System.out.println(executeCommand("mq-create --no-ssl --jmx-user admin --jmx-password admin --minimumInstances 1 mq"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("child").withProfiles("default").assertProvisioningResult().build();
        try {
            LinkedList<Container> containerList = new LinkedList<Container>(containers);
            Container broker = containerList.removeLast();
            Profile brokerProfile = broker.getVersion().getRequiredProfile("mq-broker-default.mq");
            broker.setProfiles(new Profile[] { brokerProfile });
            Provision.provisioningSuccess(Arrays.asList(broker), PROVISION_TIMEOUT);
            waitForBroker("default");
            final BrokerViewMBean bean = (BrokerViewMBean) Provision.getMBean(broker, new ObjectName("org.apache.activemq:type=Broker,brokerName=mq"), BrokerViewMBean.class, 120000);
            Assert.assertNotNull("Cannot get BrokerViewMBean from JMX", bean);
            System.out.println(executeCommand("container-list"));
            for (Container c : containerList) {
                Profile exampleProfile = broker.getVersion().getRequiredProfile("example-mq");
                c.setProfiles(new Profile[] { exampleProfile });
            }
            Provision.provisioningSuccess(containers, PROVISION_TIMEOUT);
            Provision.waitForCondition(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    while (bean.getTotalProducerCount() == 0 || bean.getTotalConsumerCount() == 0) {
                        Thread.sleep(1000);
                    }
                    return true;
                }
            }, 120000L);
            Assert.assertEquals("Producer not present", 1, bean.getTotalProducerCount());
            Assert.assertEquals("Consumer not present", 1, bean.getTotalConsumerCount());
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : LinkedList(java.util.LinkedList) Profile(io.fabric8.api.Profile) ObjectName(javax.management.ObjectName) BrokerViewMBean(org.apache.activemq.broker.jmx.BrokerViewMBean) Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)31 File (java.io.File)19 IOException (java.io.IOException)17 HashMap (java.util.HashMap)16 Git (org.eclipse.jgit.api.Git)12 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)10 Map (java.util.Map)10 LinkedList (java.util.LinkedList)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 ObjectId (org.eclipse.jgit.lib.ObjectId)7 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)6 ArrayList (java.util.ArrayList)6 PatchException (io.fabric8.patch.management.PatchException)5 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)5 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)4 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)4 URL (java.net.URL)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)4 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)3