Search in sources :

Example 1 with Terminal

use of org.apache.karaf.shell.api.console.Terminal in project karaf by apache.

the class BundleHelpProvider method getHelp.

@Override
public String getHelp(Session session, String path) {
    if (path.indexOf('|') > 0) {
        if (path.startsWith("bundle|")) {
            path = path.substring("bundle|".length());
        } else {
            return null;
        }
    }
    if (path.matches("[0-9]*")) {
        long id = Long.parseLong(path);
        BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
        Bundle bundle = bundleContext.getBundle(id);
        if (bundle != null) {
            String title = ShellUtil.getBundleName(bundle);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            ps.println("\n" + title);
            ps.println(ShellUtil.getUnderlineString(title));
            URL bundleInfo = bundle.getEntry("OSGI-INF/bundle.info");
            if (bundleInfo != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(bundleInfo.openStream()))) {
                    int maxSize = 80;
                    Terminal terminal = session.getTerminal();
                    if (terminal != null) {
                        maxSize = terminal.getWidth();
                    }
                    WikiVisitor visitor = new AnsiPrintingWikiVisitor(ps, maxSize);
                    WikiParser parser = new WikiParser(visitor);
                    parser.parse(reader);
                } catch (Exception e) {
                // ignore
                }
            }
            ps.close();
            return baos.toString();
        }
    }
    return null;
}
Also used : PrintStream(java.io.PrintStream) InputStreamReader(java.io.InputStreamReader) Bundle(org.osgi.framework.Bundle) AnsiPrintingWikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.AnsiPrintingWikiVisitor) WikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiVisitor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WikiParser(org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiParser) Terminal(org.apache.karaf.shell.api.console.Terminal) URL(java.net.URL) AnsiPrintingWikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.AnsiPrintingWikiVisitor) BufferedReader(java.io.BufferedReader) BundleContext(org.osgi.framework.BundleContext)

Example 2 with Terminal

use of org.apache.karaf.shell.api.console.Terminal in project karaf by apache.

the class Main method run.

private void run(final SessionFactory sessionFactory, String command, final InputStream in, final PrintStream out, final PrintStream err, ClassLoader cl) throws Exception {
    try (org.jline.terminal.Terminal jlineTerminal = TerminalBuilder.terminal()) {
        final Terminal terminal = new JLineTerminal(jlineTerminal);
        try (Session session = createSession(sessionFactory, command.length() > 0 ? null : in, out, err, terminal)) {
            session.put("USER", user);
            session.put("APPLICATION", application);
            discoverCommands(session, cl, getDiscoveryResource());
            if (command.length() > 0) {
                // Shell is directly executing a sub/command, we don't setup a console
                // in this case, this avoids us reading from stdin un-necessarily.
                session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
                session.put(Session.PRINT_STACK_TRACES, "execution");
                try {
                    session.execute(command);
                } catch (Throwable t) {
                    ShellUtil.logException(session, t);
                }
            } else {
                // We are going into full blown interactive shell mode.
                session.run();
            }
        }
    }
}
Also used : JLineTerminal(org.apache.karaf.shell.impl.console.JLineTerminal) JLineTerminal(org.apache.karaf.shell.impl.console.JLineTerminal) Terminal(org.apache.karaf.shell.api.console.Terminal) Session(org.apache.karaf.shell.api.console.Session)

Example 3 with Terminal

use of org.apache.karaf.shell.api.console.Terminal in project karaf by apache.

the class SshAction method execute.

@Override
public Object execute() throws Exception {
    if (hostname.indexOf('@') >= 0) {
        if (username == null) {
            username = hostname.substring(0, hostname.indexOf('@'));
        }
        hostname = hostname.substring(hostname.indexOf('@') + 1, hostname.length());
    }
    System.out.println("Connecting to host " + hostname + " on port " + port);
    // If not specified, assume the current user name
    if (username == null) {
        username = (String) this.session.get("USER");
    }
    // If the username was not configured via cli, then prompt the user for the values
    if (username == null) {
        log.debug("Prompting user for login");
        if (username == null) {
            username = session.readLine("Login: ", null);
        }
    }
    SshClient client = SshClient.setUpDefaultClient();
    if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
        client.setAgentFactory(KarafAgentFactory.getInstance());
        String agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
        client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, agentSocket);
    }
    KnownHostsManager knownHostsManager = new KnownHostsManager(new File(System.getProperty("user.home"), ".sshkaraf/known_hosts"));
    ServerKeyVerifier serverKeyVerifier = new ServerKeyVerifierImpl(knownHostsManager, quiet);
    client.setServerKeyVerifier(serverKeyVerifier);
    client.setKeyPairProvider(new FileKeyPairProvider());
    log.debug("Created client: {}", client);
    client.setUserInteraction(new UserInteraction() {

        @Override
        public void welcome(ClientSession session, String banner, String lang) {
            System.out.println(banner);
        }

        @Override
        public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
            String[] answers = new String[prompt.length];
            try {
                for (int i = 0; i < prompt.length; i++) {
                    answers[i] = session.readLine(prompt[i] + " ", echo[i] ? null : '*');
                }
            } catch (IOException e) {
            }
            return answers;
        }

        @Override
        public boolean isInteractionAllowed(ClientSession session) {
            return true;
        }

        @Override
        public void serverVersionInfo(ClientSession session, List<String> lines) {
        }

        @Override
        public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
            return null;
        }
    });
    client.start();
    try {
        ClientSession sshSession = connectWithRetries(client, username, hostname, port, retries);
        Object oldIgnoreInterrupts = this.session.get(Session.IGNORE_INTERRUPTS);
        try {
            if (password != null) {
                sshSession.addPasswordIdentity(password);
            }
            sshSession.auth().verify();
            System.out.println("Connected");
            this.session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE);
            StringBuilder sb = new StringBuilder();
            if (command != null) {
                for (String cmd : command) {
                    if (sb.length() > 0) {
                        sb.append(' ');
                    }
                    sb.append(cmd);
                }
            }
            if (sb.length() > 0) {
                ClientChannel channel = sshSession.createChannel("exec", sb.append("\n").toString());
                channel.setIn(new ByteArrayInputStream(new byte[0]));
                channel.setOut(new NoCloseOutputStream(System.out));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify();
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
            } else if (session.getTerminal() != null) {
                final ChannelShell channel = sshSession.createShellChannel();
                final org.jline.terminal.Terminal terminal = (org.jline.terminal.Terminal) session.get(".jline.terminal");
                Attributes attributes = terminal.enterRawMode();
                try {
                    Map<PtyMode, Integer> modes = new HashMap<>();
                    // Control chars
                    modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
                    modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
                    modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
                    modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
                    modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
                    modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
                    modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
                    modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
                    modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
                    modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
                    modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
                    modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
                    modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
                    modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
                    modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
                    modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
                    // Input flags
                    modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
                    modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
                    modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
                    modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
                    modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
                    modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
                    modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
                    modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
                    modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
                    modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
                    // Local flags
                    modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
                    modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
                    modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
                    modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
                    modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
                    modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
                    modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
                    modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
                    modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
                    // Output flags
                    modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
                    modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
                    modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
                    modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
                    modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
                    channel.setPtyModes(modes);
                    channel.setPtyColumns(getTermWidth());
                    channel.setPtyLines(getTermHeight());
                    channel.setAgentForwarding(true);
                    channel.setEnv("TERM", session.getTerminal().getType());
                    String ctype = (String) session.get("LC_CTYPE");
                    if (ctype == null) {
                        ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
                    }
                    channel.setEnv("LC_CTYPE", ctype);
                    channel.setIn(new NoCloseInputStream(terminal.input()));
                    channel.setOut(new NoCloseOutputStream(terminal.output()));
                    channel.setErr(new NoCloseOutputStream(terminal.output()));
                    channel.open().verify();
                    org.jline.terminal.Terminal.SignalHandler prevWinchHandler = terminal.handle(org.jline.terminal.Terminal.Signal.WINCH, signal -> {
                        try {
                            Size size = terminal.getSize();
                            channel.sendWindowChange(size.getColumns(), size.getRows());
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    org.jline.terminal.Terminal.SignalHandler prevQuitHandler = terminal.handle(org.jline.terminal.Terminal.Signal.QUIT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VQUIT));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    org.jline.terminal.Terminal.SignalHandler prevIntHandler = terminal.handle(org.jline.terminal.Terminal.Signal.INT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VINTR));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    org.jline.terminal.Terminal.SignalHandler prevStopHandler = terminal.handle(org.jline.terminal.Terminal.Signal.TSTP, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VDSUSP));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    try {
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                    } finally {
                        terminal.handle(org.jline.terminal.Terminal.Signal.WINCH, prevWinchHandler);
                        terminal.handle(org.jline.terminal.Terminal.Signal.INT, prevIntHandler);
                        terminal.handle(org.jline.terminal.Terminal.Signal.TSTP, prevStopHandler);
                        terminal.handle(org.jline.terminal.Terminal.Signal.QUIT, prevQuitHandler);
                    }
                } finally {
                    terminal.setAttributes(attributes);
                }
            } else {
                throw new IllegalStateException("No terminal for interactive ssh session");
            }
        } finally {
            session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
            sshSession.close(false);
        }
    } finally {
        client.stop();
    }
    return null;
}
Also used : ChannelShell(org.apache.sshd.client.channel.ChannelShell) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) InputFlag(org.jline.terminal.Attributes.InputFlag) LoggerFactory(org.slf4j.LoggerFactory) OutputFlag(org.jline.terminal.Attributes.OutputFlag) HashMap(java.util.HashMap) Attributes(org.jline.terminal.Attributes) Command(org.apache.karaf.shell.api.action.Command) Action(org.apache.karaf.shell.api.action.Action) Reference(org.apache.karaf.shell.api.action.lifecycle.Reference) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Locale(java.util.Locale) Map(java.util.Map) NoCloseOutputStream(org.apache.sshd.common.util.io.NoCloseOutputStream) EnumSet(java.util.EnumSet) ControlChar(org.jline.terminal.Attributes.ControlChar) PtyMode(org.apache.sshd.common.channel.PtyMode) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) Size(org.jline.terminal.Size) Session(org.apache.karaf.shell.api.console.Session) ClientSession(org.apache.sshd.client.session.ClientSession) Logger(org.slf4j.Logger) IOException(java.io.IOException) Argument(org.apache.karaf.shell.api.action.Argument) ClientChannelEvent(org.apache.sshd.client.channel.ClientChannelEvent) Terminal(org.apache.karaf.shell.api.console.Terminal) File(java.io.File) ServerKeyVerifier(org.apache.sshd.client.keyverifier.ServerKeyVerifier) List(java.util.List) ClientChannel(org.apache.sshd.client.channel.ClientChannel) SshAgent(org.apache.sshd.agent.SshAgent) SshClient(org.apache.sshd.client.SshClient) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) Service(org.apache.karaf.shell.api.action.lifecycle.Service) LocalFlag(org.jline.terminal.Attributes.LocalFlag) Option(org.apache.karaf.shell.api.action.Option) SshClient(org.apache.sshd.client.SshClient) Size(org.jline.terminal.Size) Attributes(org.jline.terminal.Attributes) ChannelShell(org.apache.sshd.client.channel.ChannelShell) ClientSession(org.apache.sshd.client.session.ClientSession) ServerKeyVerifier(org.apache.sshd.client.keyverifier.ServerKeyVerifier) IOException(java.io.IOException) Terminal(org.apache.karaf.shell.api.console.Terminal) ClientChannel(org.apache.sshd.client.channel.ClientChannel) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) File(java.io.File) NoCloseOutputStream(org.apache.sshd.common.util.io.NoCloseOutputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with Terminal

use of org.apache.karaf.shell.api.console.Terminal in project karaf by apache.

the class CommandListHelpProvider method printMethodList.

protected void printMethodList(Session session, PrintStream out, SortedMap<String, String> commands, Collection<String> modes) {
    boolean list = false;
    boolean cyan = false;
    int indent = 0;
    for (String mode : modes) {
        if (mode.equals("list")) {
            list = true;
        } else if (mode.equals("cyan")) {
            cyan = true;
        } else if (mode.equals("indent")) {
            indent = 3;
        } else if (mode.startsWith("indent=")) {
            indent = Integer.parseInt(mode.substring("indent=".length())) - 1;
        }
    }
    Terminal term = session.getTerminal();
    int termWidth = term != null ? term.getWidth() : 80;
    ShellTable table = new ShellTable().noHeaders().separator(" ").size(termWidth - 1);
    Col col = new Col("Command").maxSize(64);
    if (indent > 0 || list) {
        table.column(new Col(""));
    }
    if (cyan) {
        col.cyan();
    } else {
        col.bold();
    }
    table.column(col);
    table.column(new Col("Description").wrap());
    for (Map.Entry<String, String> entry : commands.entrySet()) {
        String key = NameScoping.getCommandNameWithoutGlobalPrefix(session, entry.getKey());
        String prefix = "";
        for (int i = 0; i < indent; i++) {
            prefix += " ";
        }
        if (list) {
            prefix += " *";
        }
        if (indent > 0 || list) {
            table.addRow().addContent(prefix, key, entry.getValue());
        } else {
            table.addRow().addContent(key, entry.getValue());
        }
    }
    table.print(out, true);
}
Also used : Col(org.apache.karaf.shell.support.table.Col) ShellTable(org.apache.karaf.shell.support.table.ShellTable) Terminal(org.apache.karaf.shell.api.console.Terminal) TreeMap(java.util.TreeMap) Map(java.util.Map) SortedMap(java.util.SortedMap)

Example 5 with Terminal

use of org.apache.karaf.shell.api.console.Terminal in project karaf by apache.

the class ShellHelpProvider method getHelp.

public String getHelp(Session session, String path) {
    if (path.indexOf('|') > 0) {
        if (path.startsWith("shell|")) {
            path = path.substring("shell|".length());
        } else {
            return null;
        }
    }
    // Retrieve matching commands
    Set<Command> commands = getCommands(session, path);
    // Compute the scopes and matching bundles
    Set<Bundle> bundles = new HashSet<>();
    Set<String> scopes = new HashSet<>();
    for (Command command : commands) {
        if (command instanceof ActionCommand) {
            Class<? extends Action> action = ((ActionCommand) command).getActionClass();
            bundles.add(FrameworkUtil.getBundle(action));
        }
        scopes.add(command.getScope());
    }
    // use that one instead
    if (scopes.size() == 1 && bundles.size() == 1 && path.equals(scopes.iterator().next())) {
        Bundle bundle = bundles.iterator().next();
        URL resource = bundle.getResource("OSGI-INF/shell-" + path + ".info");
        if (resource != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream()))) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                int maxSize = 80;
                Terminal terminal = session.getTerminal();
                if (terminal != null) {
                    maxSize = terminal.getWidth();
                }
                WikiVisitor visitor = new AnsiPrintingWikiVisitor(ps, maxSize);
                WikiParser parser = new WikiParser(visitor);
                parser.parse(reader);
                return baos.toString();
            } catch (IOException e) {
            // ignore
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        printShellHelp(session, new PrintStream(baos), path);
        return baos.toString();
    }
    return null;
}
Also used : PrintStream(java.io.PrintStream) InputStreamReader(java.io.InputStreamReader) Bundle(org.osgi.framework.Bundle) AnsiPrintingWikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.AnsiPrintingWikiVisitor) WikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiVisitor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) WikiParser(org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiParser) Terminal(org.apache.karaf.shell.api.console.Terminal) URL(java.net.URL) AnsiPrintingWikiVisitor(org.apache.karaf.shell.impl.console.commands.help.wikidoc.AnsiPrintingWikiVisitor) ActionCommand(org.apache.karaf.shell.impl.action.command.ActionCommand) Command(org.apache.karaf.shell.api.console.Command) ActionCommand(org.apache.karaf.shell.impl.action.command.ActionCommand) BufferedReader(java.io.BufferedReader) HashSet(java.util.HashSet)

Aggregations

Terminal (org.apache.karaf.shell.api.console.Terminal)5 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 InputStreamReader (java.io.InputStreamReader)2 PrintStream (java.io.PrintStream)2 URL (java.net.URL)2 Map (java.util.Map)2 Session (org.apache.karaf.shell.api.console.Session)2 AnsiPrintingWikiVisitor (org.apache.karaf.shell.impl.console.commands.help.wikidoc.AnsiPrintingWikiVisitor)2 WikiParser (org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiParser)2 WikiVisitor (org.apache.karaf.shell.impl.console.commands.help.wikidoc.WikiVisitor)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 Charset (java.nio.charset.Charset)1 EnumSet (java.util.EnumSet)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Locale (java.util.Locale)1