Search in sources :

Example 1 with User

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

the class ContainerConnectAction method executSshCommand.

/**
 * Executes the ssh command.
 */
private void executSshCommand(CommandSession session, String username, String password, String hostname, String port, String cmd) throws Exception {
    if (cmd == null || cmd.length() == 0) {
        // ENTESB-6826: we're connecting in "shell" mode, which isn't wise when running from bin/client or ssh
        if (session.getKeyboard().getClass().getName().equals("org.apache.sshd.common.channel.ChannelPipedInputStream")) {
            System.err.println("When connecting to remote container using \"fabric:container-connect\" using ssh or bin/client, please establish SSH session (run bin/client) first and then run \"fabric:container-connect\"");
            return;
        }
    }
    // Create the client from prototype
    SshClient client = createClient();
    String agentSocket;
    if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
        agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
        client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, agentSocket);
    }
    try {
        ConnectFuture future = client.connect(hostname, Integer.parseInt(port));
        future.await();
        sshSession = future.getSession();
        Object oldIgnoreInterrupts = this.session.get(Console.IGNORE_INTERRUPTS);
        this.session.put(Console.IGNORE_INTERRUPTS, Boolean.TRUE);
        try {
            System.out.println("Connected");
            boolean authed = false;
            if (!authed) {
                if (username == null) {
                    throw new FabricAuthenticationException("No username specified.");
                }
                log.debug("Prompting user for password");
                String pwd = password != null ? password : ShellUtils.readLine(session, "Password: ", true);
                sshSession.authPassword(username, pwd);
                int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                if ((ret & ClientSession.AUTHED) == 0) {
                    System.err.println("Password authentication failed");
                } else {
                    authed = true;
                }
            }
            if (!authed) {
                throw new FabricAuthenticationException("Failed to authenticate.");
            }
            // If user is authenticated credentials to session for future use.
            ShellUtils.storeFabricCredentials(session, username, password);
            ClientChannel channel;
            if (cmd != null && cmd.length() > 0) {
                channel = sshSession.createChannel("exec", cmd);
                channel.setIn(new ByteArrayInputStream(new byte[0]));
            } else {
                channel = sshSession.createChannel("shell");
                channel.setIn(new NoCloseInputStream(System.in));
                ((ChannelShell) channel).setPtyColumns(ShellUtils.getTermWidth(session));
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
            }
            channel.setOut(new NoCloseOutputStream(System.out));
            channel.setErr(new NoCloseOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
        } finally {
            session.put(Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
            sshSession.close(false);
        }
    } finally {
        client.stop();
    }
}
Also used : NoCloseInputStream(org.apache.sshd.common.util.NoCloseInputStream) SshClient(org.apache.sshd.SshClient) FabricAuthenticationException(io.fabric8.api.FabricAuthenticationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) ChannelShell(org.apache.sshd.client.channel.ChannelShell) NoCloseOutputStream(org.apache.sshd.common.util.NoCloseOutputStream) ClientChannel(org.apache.sshd.ClientChannel)

Example 2 with User

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

the class JolokiaFabricConnector method connect.

/**
 * connects to a fabric
 */
public void connect() {
    if (this.j4p != null || this.fabricServiceFacade != null) {
        disconnect();
    }
    this.j4p = J4pClient.url(this.url).user(this.userName).password(this.password).build();
    /* This needs further investigation...
        DefaultHttpClient httpClient = (DefaultHttpClient) j4p.getHttpClient();
        httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
                return true;
            }
        });
        */
    this.fabricServiceFacade = new FabricServiceFacade(this);
    this.fabricMBeanFacade = new FabricMBean(this);
}
Also used : FabricMBean(io.fabric8.jolokia.facade.mbeans.FabricMBean) FabricServiceFacade(io.fabric8.jolokia.facade.facades.FabricServiceFacade)

Example 3 with User

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

the class ProjectDeployerTest method setUp.

@Before
public void setUp() throws Exception {
    URL.setURLStreamHandlerFactory(new CustomBundleURLStreamHandlerFactory());
    basedir = System.getProperty("basedir", ".");
    String karafRoot = basedir + "/target/karaf";
    System.setProperty("karaf.root", karafRoot);
    System.setProperty("karaf.data", karafRoot + "/data");
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());
    delete(sfb.getDataLogDir());
    sfb.setPort(9123);
    sfb.afterPropertiesSet();
    int zkPort = sfb.getClientPortAddress().getPort();
    LOG.info("Connecting to ZK on port: " + zkPort);
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().connectString("localhost:" + zkPort).retryPolicy(new RetryOneTime(1000)).connectionTimeoutMs(360000);
    curator = builder.build();
    curator.start();
    curator.getZookeeperClient().blockUntilConnectedOrTimedOut();
    // setup a local and remote git repo
    File root = new File(basedir + "/target/git").getCanonicalFile();
    delete(root);
    new File(root, "remote").mkdirs();
    remote = Git.init().setDirectory(new File(root, "remote")).setGitDir(new File(root, "remote/.git")).call();
    remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();
    new File(root, "local").mkdirs();
    git = Git.init().setDirectory(new File(root, "local")).setGitDir(new File(root, "local/.git")).call();
    git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();
    runtimeProperties = EasyMock.createMock(RuntimeProperties.class);
    EasyMock.expect(runtimeProperties.getRuntimeIdentity()).andReturn("root").anyTimes();
    EasyMock.expect(runtimeProperties.getHomePath()).andReturn(Paths.get("target")).anyTimes();
    EasyMock.expect(runtimeProperties.getDataPath()).andReturn(Paths.get("target/data")).anyTimes();
    EasyMock.expect(runtimeProperties.getProperty(EasyMock.eq(SystemProperties.FABRIC_ENVIRONMENT))).andReturn("").anyTimes();
    EasyMock.expect(runtimeProperties.removeRuntimeAttribute(DataStoreTemplate.class)).andReturn(null).anyTimes();
    EasyMock.replay(runtimeProperties);
    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.bindRuntimeProperties(runtimeProperties);
    gitService.activate();
    gitService.setGitForTesting(git);
    /*
        dataStore = new GitDataStoreImpl();
        dataStore.bindCurator(curator);
        dataStore.bindGitService(gitService);
        dataStore.bindRuntimeProperties(runtimeProperties);
        dataStore.bindConfigurer(new Configurer() {
        

            @Override
            public <T> Map<String, ?> configure(Map<String, ?> configuration, T target, String... ignorePrefix) throws Exception {
                return null;
            }

            @Override
            public <T> Map<String, ?> configure(Dictionary<String, ?> configuration, T target, String... ignorePrefix) throws Exception {
                return null;
            }
        });
        Map<String, Object> datastoreProperties = new HashMap<String, Object>();
        datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl);
        dataStore.activate(datastoreProperties);
        */
    fabricService = new FabricServiceImpl();
    // fabricService.bindDataStore(dataStore);
    fabricService.bindRuntimeProperties(runtimeProperties);
    fabricService.bindPlaceholderResolver(new DummyPlaceholerResolver("port"));
    fabricService.bindPlaceholderResolver(new DummyPlaceholerResolver("zk"));
    fabricService.bindPlaceholderResolver(new ProfilePropertyPointerResolver());
    fabricService.bindPlaceholderResolver(new ChecksumPlaceholderResolver());
    fabricService.bindPlaceholderResolver(new VersionPropertyPointerResolver());
    fabricService.bindPlaceholderResolver(new EnvPlaceholderResolver());
    fabricService.activateComponent();
    projectDeployer = new ProjectDeployerImpl();
    projectDeployer.bindFabricService(fabricService);
    projectDeployer.bindMBeanServer(ManagementFactory.getPlatformMBeanServer());
    // dataStore.getDefaultVersion();
    String defaultVersion = null;
    assertEquals("defaultVersion", "1.0", defaultVersion);
    // now lets import some data - using the old non-git file layout...
    String importPath = basedir + "/../fabric8-karaf/src/main/resources/distro/fabric/import";
    assertFolderExists(importPath);
    dataStore.importFromFileSystem(importPath);
    assertHasVersion(defaultVersion);
}
Also used : ProfilePropertyPointerResolver(io.fabric8.service.ProfilePropertyPointerResolver) RetryOneTime(org.apache.curator.retry.RetryOneTime) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) FabricGitServiceImpl(io.fabric8.git.internal.FabricGitServiceImpl) ZKServerFactoryBean(io.fabric8.zookeeper.spring.ZKServerFactoryBean) VersionPropertyPointerResolver(io.fabric8.service.VersionPropertyPointerResolver) EnvPlaceholderResolver(io.fabric8.service.EnvPlaceholderResolver) FabricServiceImpl(io.fabric8.service.FabricServiceImpl) StoredConfig(org.eclipse.jgit.lib.StoredConfig) DataStoreTemplate(io.fabric8.api.DataStoreTemplate) ChecksumPlaceholderResolver(io.fabric8.service.ChecksumPlaceholderResolver) File(java.io.File) RuntimeProperties(io.fabric8.api.RuntimeProperties) Before(org.junit.Before)

Example 4 with User

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

the class OpenshiftContainerProvider method create.

@Override
public CreateOpenshiftContainerMetadata create(CreateOpenshiftContainerOptions options, CreationStateListener listener) throws Exception {
    assertValid();
    IUser user = getOrCreateConnection(options).getUser();
    IDomain domain = getOrCreateDomain(user, options);
    String cartridgeUrl = null;
    Set<String> profiles = options.getProfiles();
    String versionId = options.getVersion();
    Map<String, String> openshiftConfigOverlay = new HashMap<String, String>();
    if (profiles != null && versionId != null) {
        ProfileService profileService = fabricService.get().adapt(ProfileService.class);
        Version version = profileService.getVersion(versionId);
        if (version != null) {
            for (String profileId : profiles) {
                Profile profile = version.getRequiredProfile(profileId);
                if (profile != null) {
                    Profile overlay = profileService.getOverlayProfile(profile);
                    Map<String, String> openshiftConfig = overlay.getConfiguration(OpenShiftConstants.OPENSHIFT_PID);
                    if (openshiftConfig != null) {
                        openshiftConfigOverlay.putAll(openshiftConfig);
                    }
                }
            }
        }
        cartridgeUrl = openshiftConfigOverlay.get("cartridge");
    }
    if (cartridgeUrl == null) {
        cartridgeUrl = defaultCartridgeUrl;
    }
    String[] cartridgeUrls = cartridgeUrl.split(" ");
    LOG.info("Creating cartridges: " + cartridgeUrl);
    String standAloneCartridgeUrl = cartridgeUrls[0];
    StandaloneCartridge cartridge;
    if (standAloneCartridgeUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
        cartridge = new StandaloneCartridge(standAloneCartridgeUrl.substring(PREFIX_CARTRIDGE_ID.length()));
    } else {
        cartridge = new StandaloneCartridge(new URL(standAloneCartridgeUrl));
    }
    String zookeeperUrl = fabricService.get().getZookeeperUrl();
    String zookeeperPassword = fabricService.get().getZookeeperPassword();
    Map<String, String> userEnvVars = null;
    if (!options.isEnsembleServer()) {
        userEnvVars = new HashMap<String, String>();
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_URL", zookeeperUrl);
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD", zookeeperPassword);
        String zkPasswordEncode = System.getProperty("zookeeper.password.encode", "true");
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD_ENCODE", zkPasswordEncode);
        userEnvVars.put("OPENSHIFT_FUSE_CREATED_FROM_FABRIC", "true");
    }
    String initGitUrl = null;
    int timeout = IHttpClient.NO_TIMEOUT;
    ApplicationScale scale = null;
    String containerName = options.getName();
    long t0 = System.currentTimeMillis();
    IApplication application;
    try {
        application = domain.createApplication(containerName, cartridge, scale, new GearProfile(options.getGearProfile()), initGitUrl, timeout, userEnvVars);
    } catch (OpenShiftTimeoutException e) {
        long t1;
        do {
            Thread.sleep(5000);
            domain.refresh();
            application = domain.getApplicationByName(containerName);
            if (application != null) {
                break;
            }
            t1 = System.currentTimeMillis();
        } while (t1 - t0 < TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES));
    }
    LOG.info("Created application " + containerName);
    // now lets add all the embedded cartridges
    List<IEmbeddableCartridge> list = new ArrayList<IEmbeddableCartridge>();
    for (int idx = 1, size = cartridgeUrls.length; idx < size; idx++) {
        String embeddedUrl = cartridgeUrls[idx];
        LOG.info("Adding embedded cartridge: " + embeddedUrl);
        if (embeddedUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
            list.add(new EmbeddableCartridge(embeddedUrl.substring(PREFIX_CARTRIDGE_ID.length())));
        } else {
            list.add(new EmbeddableCartridge(new URL(embeddedUrl)));
        }
    }
    if (!list.isEmpty()) {
        application.addEmbeddableCartridges(list);
    }
    String gitUrl = application.getGitUrl();
    // in case of OpenShiftTimeoutException, application resource doesn't contain getCreationLog().
    // actually this method throws NPE
    CreateOpenshiftContainerMetadata metadata = new CreateOpenshiftContainerMetadata(domain.getId(), application.getUUID(), application.getMessages() == null ? "" : application.getCreationLog(), gitUrl);
    metadata.setContainerName(containerName);
    metadata.setCreateOptions(options);
    return metadata;
}
Also used : HashMap(java.util.HashMap) ApplicationScale(com.openshift.client.ApplicationScale) OpenShiftTimeoutException(com.openshift.client.OpenShiftTimeoutException) ArrayList(java.util.ArrayList) GearProfile(com.openshift.internal.client.GearProfile) Profile(io.fabric8.api.Profile) IGearProfile(com.openshift.client.IGearProfile) URL(java.net.URL) IDomain(com.openshift.client.IDomain) IApplication(com.openshift.client.IApplication) ProfileService(io.fabric8.api.ProfileService) Version(io.fabric8.api.Version) GearProfile(com.openshift.internal.client.GearProfile) IGearProfile(com.openshift.client.IGearProfile) IUser(com.openshift.client.IUser) EmbeddableCartridge(com.openshift.client.cartridge.EmbeddableCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge) StandaloneCartridge(com.openshift.client.cartridge.StandaloneCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge)

Example 5 with User

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

the class DeployToProfileMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isIgnoreProject())
        return;
    try {
        ProjectRequirements requirements = new ProjectRequirements();
        if (isIncludeArtifact()) {
            DependencyDTO rootDependency = loadRootDependency();
            requirements.setRootDependency(rootDependency);
        }
        configureRequirements(requirements);
        // validate requirements
        if (requirements.getProfileId() != null) {
            // make sure the profile id is a valid name
            FabricValidations.validateProfileName(requirements.getProfileId());
        }
        boolean newUserAdded = false;
        fabricServer = mavenSettings.getServer(serverId);
        // we may have username and password from jolokiaUrl
        String jolokiaUsername = null;
        String jolokiaPassword = null;
        try {
            URL url = new URL(jolokiaUrl);
            String s = url.getUserInfo();
            if (Strings.isNotBlank(s) && s.indexOf(':') > 0) {
                int idx = s.indexOf(':');
                jolokiaUsername = s.substring(0, idx);
                jolokiaPassword = s.substring(idx + 1);
                customUsernameAndPassword = true;
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Option jolokiaUrl is invalid due " + e.getMessage());
        }
        // jolokia url overrides username/password configured in maven settings
        if (jolokiaUsername != null) {
            if (fabricServer == null) {
                fabricServer = new Server();
            }
            getLog().info("Using username: " + jolokiaUsername + " and password from provided jolokiaUrl option");
            fabricServer.setId(serverId);
            fabricServer.setUsername(jolokiaUsername);
            fabricServer.setPassword(jolokiaPassword);
        }
        if (fabricServer == null) {
            boolean create = false;
            if (mavenSettings.isInteractiveMode() && mavenSettingsWriter != null) {
                System.out.println("Maven settings file: " + mavenSettingsFile.getAbsolutePath());
                System.out.println();
                System.out.println();
                System.out.println("There is no <server> section in your ~/.m2/settings.xml file for the server id: " + serverId);
                System.out.println();
                System.out.println("You can enter the username/password now and have the settings.xml updated or you can do this by hand if you prefer.");
                System.out.println();
                while (true) {
                    String value = readInput("Would you like to update the settings.xml file now? (y/n): ").toLowerCase();
                    if (value.startsWith("n")) {
                        System.out.println();
                        System.out.println();
                        break;
                    } else if (value.startsWith("y")) {
                        create = true;
                        break;
                    }
                }
                if (create) {
                    System.out.println("Please let us know the login details for this server: " + serverId);
                    System.out.println();
                    String userName = readInput("Username: ");
                    String password = readPassword("Password: ");
                    String password2 = readPassword("Repeat Password: ");
                    while (!password.equals(password2)) {
                        System.out.println("Passwords do not match, please try again.");
                        password = readPassword("Password: ");
                        password2 = readPassword("Repeat Password: ");
                    }
                    System.out.println();
                    fabricServer = new Server();
                    fabricServer.setId(serverId);
                    fabricServer.setUsername(userName);
                    fabricServer.setPassword(password);
                    mavenSettings.addServer(fabricServer);
                    if (mavenSettingsFile.exists()) {
                        int counter = 1;
                        while (true) {
                            File backupFile = new File(mavenSettingsFile.getAbsolutePath() + ".backup-" + counter++ + ".xml");
                            if (!backupFile.exists()) {
                                System.out.println("Copied original: " + mavenSettingsFile.getAbsolutePath() + " to: " + backupFile.getAbsolutePath());
                                Files.copy(mavenSettingsFile, backupFile);
                                break;
                            }
                        }
                    }
                    Map<String, Object> config = new HashMap<String, Object>();
                    mavenSettingsWriter.write(mavenSettingsFile, config, mavenSettings);
                    System.out.println("Updated settings file: " + mavenSettingsFile.getAbsolutePath());
                    System.out.println();
                    newUserAdded = true;
                }
            }
        }
        if (fabricServer == null) {
            String message = "No <server> element can be found in ~/.m2/settings.xml for the server <id>" + serverId + "</id> so we cannot connect to fabric8!\n\n" + "Please add the following to your ~/.m2/settings.xml file (using the correct user/password values):\n\n" + "<servers>\n" + "  <server>\n" + "    <id>" + serverId + "</id>\n" + "    <username>admin</username>\n" + "    <password>admin</password>\n" + "  </server>\n" + "</servers>\n";
            getLog().error(message);
            throw new MojoExecutionException(message);
        }
        // now lets invoke the mbean
        J4pClient client = createJolokiaClient();
        if (upload) {
            uploadDeploymentUnit(client, newUserAdded || customUsernameAndPassword);
        } else {
            getLog().info("Uploading to the fabric8 maven repository is disabled");
        }
        DeployResults results = uploadRequirements(client, requirements);
        if (results != null) {
            uploadReadMeFile(client, results);
            uploadProfileConfigurations(client, results);
            refreshProfile(client, results);
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing", e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) DeployResults(io.fabric8.deployer.dto.DeployResults) Server(org.apache.maven.settings.Server) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) J4pClient(org.jolokia.client.J4pClient) DependencyDTO(io.fabric8.deployer.dto.DependencyDTO) URL(java.net.URL) MalformedObjectNameException(javax.management.MalformedObjectNameException) J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) ArtifactDeploymentException(org.apache.maven.artifact.deployer.ArtifactDeploymentException) J4pConnectException(org.jolokia.client.exception.J4pConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) J4pException(org.jolokia.client.exception.J4pException) ProjectRequirements(io.fabric8.deployer.dto.ProjectRequirements) File(java.io.File)

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