Search in sources :

Example 61 with Group

use of io.fabric8.groups.Group in project fabric8 by jboss-fuse.

the class MQServiceImpl method createOrUpdateMQClientProfile.

@Override
public Profile createOrUpdateMQClientProfile(String versionId, String profileId, String group, String parentProfileName) {
    Version version = profileService.getRequiredVersion(versionId);
    Profile parentProfile = null;
    if (Strings.isNotBlank(parentProfileName)) {
        parentProfile = version.getRequiredProfile(parentProfileName);
    }
    if (group == null || profileId == null)
        return parentProfile;
    ProfileBuilder builder;
    // create a profile if it doesn't exist
    boolean create = !version.hasProfile(profileId);
    if (create) {
        builder = ProfileBuilder.Factory.create(versionId, profileId);
    } else {
        Profile profile = version.getRequiredProfile(profileId);
        builder = ProfileBuilder.Factory.createFrom(profile);
    }
    // set the parent if its specified
    if (parentProfile != null) {
        builder.addParent(parentProfile.getId());
    }
    Map<String, String> config = builder.getConfiguration(MQ_CONNECTION_FACTORY_PID);
    config.put(GROUP, group);
    builder.addConfiguration(MQ_CONNECTION_FACTORY_PID, config);
    Profile profile = builder.getProfile();
    return create ? profileService.createProfile(profile) : profileService.updateProfile(profile);
}
Also used : Version(io.fabric8.api.Version) ProfileBuilder(io.fabric8.api.ProfileBuilder) Profile(io.fabric8.api.Profile)

Example 62 with Group

use of io.fabric8.groups.Group 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 63 with Group

use of io.fabric8.groups.Group in project fabric8 by jboss-fuse.

the class AbstractManagedContainer method create.

@Override
public final synchronized void create(T configuration) throws LifecycleException {
    if (state != null)
        throw new IllegalStateException("Cannot create container in state: " + state);
    this.configuration = configuration;
    // [TODO] [FABRIC-929] No connector available to access repository jboss-public-repository-group
    // Remove this hack. It shouldbe possible to use the shrinkwrap maven resolver
    boolean useShrinkwrap = System.getProperty("shrinkwrap.resolver") != null;
    for (MavenCoordinates artefact : configuration.getMavenCoordinates()) {
        File zipfile = useShrinkwrap ? shrinkwrapResolve(artefact) : localResolve(artefact);
        GenericArchive archive = ShrinkWrap.createFromZipFile(GenericArchive.class, zipfile);
        ExplodedExporter exporter = archive.as(ExplodedExporter.class);
        File targetdir = configuration.getTargetDirectory();
        if (!targetdir.isDirectory() && !targetdir.mkdirs())
            throw new IllegalStateException("Cannot create target dir: " + targetdir);
        if (containerHome == null) {
            exporter.exportExploded(targetdir, "");
            File[] childDirs = targetdir.listFiles();
            if (childDirs.length != 1)
                throw new IllegalStateException("Expected one child directory, but was: " + Arrays.asList(childDirs));
            containerHome = childDirs[0];
        } else {
            exporter.exportExploded(containerHome, "");
        }
    }
    state = State.CREATED;
    try {
        doConfigure(configuration);
    } catch (Exception ex) {
        throw new LifecycleException("Cannot configure container", ex);
    }
}
Also used : MavenCoordinates(io.fabric8.api.gravia.MavenCoordinates) LifecycleException(io.fabric8.runtime.container.LifecycleException) GenericArchive(org.jboss.shrinkwrap.api.GenericArchive) ExplodedExporter(org.jboss.shrinkwrap.api.exporter.ExplodedExporter) File(java.io.File) LifecycleException(io.fabric8.runtime.container.LifecycleException) IOException(java.io.IOException)

Example 64 with Group

use of io.fabric8.groups.Group in project fabric8 by jboss-fuse.

the class OpenShiftDeployAgent method groupEvent.

@Override
public void groupEvent(Group<ControllerNode> group, GroupEvent event) {
    if (isValid()) {
        if (group.isMaster()) {
            LOGGER.info("OpenShiftDeployAgent is the master");
        } else {
            LOGGER.info("OpenShiftDeployAgent is not the master");
        }
        try {
            DataStore dataStore = null;
            if (fabricService != null) {
                dataStore = fabricService.get().adapt(DataStore.class);
            } else {
                LOGGER.warn("No fabricService yet!");
            }
            if (group.isMaster()) {
                ControllerNode state = createState();
                group.update(state);
            }
            if (dataStore != null) {
                if (group.isMaster()) {
                    dataStore.trackConfiguration(runnable);
                    onConfigurationChanged();
                } else {
                    dataStore.untrackConfiguration(runnable);
                }
            }
        } catch (IllegalStateException e) {
        // Ignore
        }
    }
}
Also used : DataStore(io.fabric8.api.DataStore)

Example 65 with Group

use of io.fabric8.groups.Group in project fabric8 by jboss-fuse.

the class MQProfileTest method testMQCreateNetwork.

@Test
public void testMQCreateNetwork() 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"));
    executeCommand("mq-create --no-ssl --group us-east --network us-west --jmx-user admin --jmx-password admin --networks-username admin --networks-password admin --minimumInstances 1 us-east");
    executeCommand("mq-create --no-ssl --group us-west --network us-east --jmx-user admin --jmx-password admin --networks-username admin --networks-password admin --minimumInstances 1 us-west");
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 4).withName("child").withProfiles("default").assertProvisioningResult().build();
        try {
            LinkedList<Container> containerList = new LinkedList<Container>(containers);
            Container eastBroker = containerList.removeLast();
            Container westBroker = containerList.removeLast();
            Profile eastBrokerProfile = eastBroker.getVersion().getRequiredProfile("mq-broker-us-east.us-east");
            eastBroker.setProfiles(new Profile[] { eastBrokerProfile });
            Profile westBrokerProfile = eastBroker.getVersion().getRequiredProfile("mq-broker-us-west.us-west");
            westBroker.setProfiles(new Profile[] { westBrokerProfile });
            Provision.provisioningSuccess(Arrays.asList(westBroker, eastBroker), PROVISION_TIMEOUT);
            waitForBroker("us-east");
            waitForBroker("us-west");
            final BrokerViewMBean brokerEast = (BrokerViewMBean) Provision.getMBean(eastBroker, new ObjectName("org.apache.activemq:type=Broker,brokerName=us-east"), BrokerViewMBean.class, 120000);
            final BrokerViewMBean brokerWest = (BrokerViewMBean) Provision.getMBean(westBroker, new ObjectName("org.apache.activemq:type=Broker,brokerName=us-west"), BrokerViewMBean.class, 120000);
            Assert.assertNotNull("Cannot get BrokerViewMBean from JMX", brokerEast);
            Assert.assertNotNull("Cannot get BrokerViewMBean from JMX", brokerWest);
            Container eastProducer = containerList.removeLast();
            executeCommand("container-add-profile " + eastProducer.getId() + " example-mq-producer mq-client-us-east");
            Container westConsumer = containerList.removeLast();
            executeCommand("container-add-profile " + westConsumer.getId() + " example-mq-consumer mq-client-us-west");
            Provision.provisioningSuccess(Arrays.asList(eastProducer, westConsumer), PROVISION_TIMEOUT);
            System.out.println(executeCommand("fabric:container-list"));
            Provision.waitForCondition(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    while (brokerEast.getTotalEnqueueCount() == 0 || brokerWest.getTotalDequeueCount() == 0) {
                        Thread.sleep(1000);
                    }
                    return true;
                }
            }, 120000L);
            System.out.println(executeCommand("fabric:container-connect -u admin -p admin " + eastBroker.getId() + " bstat"));
            System.out.println(executeCommand("fabric:container-connect -u admin -p admin " + westBroker.getId() + " bstat"));
            Assert.assertFalse("Messages not sent", brokerEast.getTotalEnqueueCount() == 0);
            Assert.assertFalse("Messages not received", brokerWest.getTotalDequeueCount() == 0);
        } 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

Group (org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group)50 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)27 FlowCapableNode (org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode)18 ActionGroup (org.opendaylight.genius.mdsalutil.actions.ActionGroup)15 GroupKey (org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey)15 CuratorFramework (org.apache.curator.framework.CuratorFramework)12 Bucket (org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket)11 RpcResult (org.opendaylight.yangtools.yang.common.RpcResult)11 IOException (java.io.IOException)9 StaleGroup (org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup)9 Nodes (org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes)9 ZooKeeperGroup (io.fabric8.groups.internal.ZooKeeperGroup)8 RetryNTimes (org.apache.curator.retry.RetryNTimes)8 NodeState (io.fabric8.groups.NodeState)7 Map (java.util.Map)7 ItemSyncBox (org.opendaylight.openflowplugin.applications.frsync.util.ItemSyncBox)7 BigInteger (java.math.BigInteger)6 HashMap (java.util.HashMap)6 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)6