Search in sources :

Example 6 with Channel

use of hudson.remoting.Channel in project hudson-2.x by hudson.

the class ChannelTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    final FastPipedInputStream p1i = new FastPipedInputStream();
    final FastPipedInputStream p2i = new FastPipedInputStream();
    final FastPipedOutputStream p1o = new FastPipedOutputStream(p1i);
    final FastPipedOutputStream p2o = new FastPipedOutputStream(p2i);
    Future<Channel> f1 = executors.submit(new Callable<Channel>() {

        public Channel call() throws Exception {
            return new Channel("This side of the channel", executors, p1i, p2o);
        }
    });
    Future<Channel> f2 = executors.submit(new Callable<Channel>() {

        public Channel call() throws Exception {
            return new Channel("The other side of the channel", executors, p2i, p1o);
        }
    });
    french = f1.get();
    british = f2.get();
}
Also used : Channel(hudson.remoting.Channel) FastPipedOutputStream(hudson.remoting.FastPipedOutputStream) IOException(java.io.IOException) FastPipedInputStream(hudson.remoting.FastPipedInputStream)

Example 7 with Channel

use of hudson.remoting.Channel in project hudson-2.x by hudson.

the class FilePath method readObject.

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    Channel channel = Channel.current();
    assert channel != null;
    ois.defaultReadObject();
    if (ois.readBoolean()) {
        this.channel = channel;
    } else {
        this.channel = null;
    }
}
Also used : VirtualChannel(hudson.remoting.VirtualChannel) Channel(hudson.remoting.Channel)

Example 8 with Channel

use of hudson.remoting.Channel in project hudson-2.x by hudson.

the class FilePath method writeObject.

private void writeObject(ObjectOutputStream oos) throws IOException {
    Channel target = Channel.current();
    if (channel != null && channel != target)
        throw new IllegalStateException("Can't send a remote FilePath to a different remote channel");
    oos.defaultWriteObject();
    oos.writeBoolean(channel == null);
}
Also used : VirtualChannel(hudson.remoting.VirtualChannel) Channel(hudson.remoting.Channel)

Example 9 with Channel

use of hudson.remoting.Channel in project hudson-2.x by hudson.

the class ManagedWindowsServiceLauncher method launch.

@Override
public void launch(final SlaveComputer computer, final TaskListener listener) throws IOException, InterruptedException {
    try {
        final PrintStream logger = listener.getLogger();
        final String name = determineHost(computer);
        logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name));
        InetAddress host = InetAddress.getByName(name);
        try {
            Socket s = new Socket();
            s.connect(new InetSocketAddress(host, 135), 5000);
            s.close();
        } catch (IOException e) {
            logger.println("Failed to connect to port 135 of " + name + ". Is Windows firewall blocking this port? Or did you disable DCOM service?");
        // again, let it continue.
        }
        JIDefaultAuthInfoImpl auth = createAuth();
        JISession session = JISession.createSession(auth);
        session.setGlobalSocketTimeout(60000);
        SWbemServices services = WMI.connect(session, name);
        String path = computer.getNode().getRemoteFS();
        if (path.indexOf(':') == -1)
            throw new IOException("Remote file system root path of the slave needs to be absolute: " + path);
        SmbFile remoteRoot = new SmbFile("smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth());
        if (!remoteRoot.exists())
            remoteRoot.mkdirs();
        try {
            // does Java exist?
            logger.println("Checking if Java exists");
            WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth);
            Process proc = wrpl.launch("java -fullversion", "c:\\");
            proc.getOutputStream().close();
            IOUtils.copy(proc.getInputStream(), logger);
            proc.getInputStream().close();
            int exitCode = proc.waitFor();
            if (exitCode == 1) {
                // we'll get this error code if Java is not found
                //TODO enable me when JDK installer based on REST API will be ready
                logger.println("No JDK found on slave node. Please install JDK");
                throw new InterruptedException("No JDK found on slave node. Please install JDK");
            //                    logger.println("No Java found. Downloading JDK");
            //                    JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer",true);
            //                    URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386);
            //
            //                    listener.getLogger().println("Installing JDK");
            //                    copyStreamAndClose(jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream());
            //
            //                    String javaDir = path + "\\jdk"; // this is where we install Java to
            //
            //                    WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth());
            //                    fs.mkdirs(javaDir);
            //
            //                    jdki.install(new WindowsRemoteLauncher(listener,wrpl), Platform.WINDOWS,
            //                            fs, listener, javaDir ,path+"\\jdk.exe");
            }
        } catch (Exception e) {
            e.printStackTrace(listener.error("Failed to prepare Java"));
        }
        String id = WindowsSlaveInstaller.generateServiceId(path);
        Win32Service slaveService = services.getService(id);
        if (slaveService == null) {
            logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService());
            if (!DotNet.isInstalled(2, 0, name, auth)) {
                // abort the launch
                logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired());
                return;
            }
            // copy exe
            logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe());
            copyStreamAndClose(getClass().getResource("/windows-service/hudson.exe").openStream(), new SmbFile(remoteRoot, "hudson-slave.exe").getOutputStream());
            copySlaveJar(logger, remoteRoot);
            // copy hudson-slave.xml
            logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml());
            String xml = WindowsSlaveInstaller.generateSlaveXml(id, "javaw.exe", "-tcp %BASE%\\port.txt");
            copyStreamAndClose(new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "hudson-slave.xml").getOutputStream());
            // install it as a service
            logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService());
            Document dom = new SAXReader().read(new StringReader(xml));
            Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class);
            int r = svc.Create(id, dom.selectSingleNode("/service/name").getText() + " at " + path, path + "\\hudson-slave.exe", Win32OwnProcess, 0, "Manual", true);
            if (r != 0) {
                listener.error("Failed to create a service: " + svc.getErrorMessage(r));
                return;
            }
            slaveService = services.getService(id);
        } else {
            copySlaveJar(logger, remoteRoot);
        }
        logger.println(Messages.ManagedWindowsServiceLauncher_StartingService());
        slaveService.start();
        // wait until we see the port.txt, but don't do so forever
        logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService());
        SmbFile portFile = new SmbFile(remoteRoot, "port.txt");
        for (int i = 0; !portFile.exists(); i++) {
            if (i >= 30) {
                listener.error(Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond());
                return;
            }
            Thread.sleep(1000);
        }
        int p = readSmbFile(portFile);
        // connect
        logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p));
        final Socket s = new Socket(name, p);
        // ready
        computer.setChannel(new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() {

            @Override
            public void onClosed(Channel channel, IOException cause) {
                afterDisconnect(computer, listener);
            }
        });
    } catch (SmbException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } catch (JIException e) {
        if (e.getErrorCode() == 5)
            // access denied error
            e.printStackTrace(listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
        else
            e.printStackTrace(listener.error(e.getMessage()));
    } catch (DocumentException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    }
}
Also used : Listener(hudson.remoting.Channel.Listener) TaskListener(hudson.model.TaskListener) InetSocketAddress(java.net.InetSocketAddress) SAXReader(org.dom4j.io.SAXReader) Win32OwnProcess(org.jvnet.hudson.wmi.Win32Service.Win32OwnProcess) Document(org.dom4j.Document) Win32Service(org.jvnet.hudson.wmi.Win32Service) SmbException(jcifs.smb.SmbException) JISession(org.jinterop.dcom.core.JISession) BufferedInputStream(java.io.BufferedInputStream) DocumentException(org.dom4j.DocumentException) StringReader(java.io.StringReader) BufferedOutputStream(java.io.BufferedOutputStream) JIException(org.jinterop.dcom.common.JIException) PrintStream(java.io.PrintStream) SocketOutputStream(hudson.remoting.SocketOutputStream) JIDefaultAuthInfoImpl(org.jinterop.dcom.common.JIDefaultAuthInfoImpl) Channel(hudson.remoting.Channel) IOException(java.io.IOException) SocketInputStream(hudson.remoting.SocketInputStream) WindowsRemoteProcessLauncher(org.jvnet.hudson.remcom.WindowsRemoteProcessLauncher) SmbException(jcifs.smb.SmbException) DocumentException(org.dom4j.DocumentException) JIException(org.jinterop.dcom.common.JIException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SmbFile(jcifs.smb.SmbFile) ByteArrayInputStream(java.io.ByteArrayInputStream) SWbemServices(org.jvnet.hudson.wmi.SWbemServices) InetAddress(java.net.InetAddress) Socket(java.net.Socket)

Example 10 with Channel

use of hudson.remoting.Channel in project hudson-2.x by hudson.

the class CommandLauncher method launch.

@Override
public void launch(SlaveComputer computer, final TaskListener listener) {
    EnvVars _cookie = null;
    Process _proc = null;
    try {
        listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp()));
        if (getCommand().trim().length() == 0) {
            listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand());
            return;
        }
        listener.getLogger().println("$ " + getCommand());
        ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand()));
        final EnvVars cookie = _cookie = EnvVars.createCookie();
        pb.environment().putAll(cookie);
        {
            // system defined variables
            String rootUrl = Hudson.getInstance().getRootUrl();
            if (rootUrl != null) {
                pb.environment().put("HUDSON_URL", rootUrl);
                pb.environment().put("SLAVEJAR_URL", rootUrl + "/jnlpJars/slave.jar");
            }
        }
        if (env != null) {
            pb.environment().putAll(env);
        }
        final Process proc = _proc = pb.start();
        // capture error information from stderr. this will terminate itself
        // when the process is killed.
        new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start();
        computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(), new Channel.Listener() {

            @Override
            public void onClosed(Channel channel, IOException cause) {
                try {
                    int exitCode = proc.exitValue();
                    if (exitCode != 0) {
                        listener.error("Process terminated with exit code " + exitCode);
                    }
                } catch (IllegalThreadStateException e) {
                // hasn't terminated yet
                }
                try {
                    ProcessTree.get().killAll(proc, cookie);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.INFO, "interrupted", e);
                }
            }
        });
        LOGGER.info("slave agent launched for " + computer.getDisplayName());
    } catch (InterruptedException e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
    } catch (RuntimeException e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
    } catch (Error e) {
        e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
    } catch (IOException e) {
        Util.displayIOException(e, listener);
        String msg = Util.getWin32ErrorMessage(e);
        if (msg == null) {
            msg = "";
        } else {
            msg = " : " + msg;
        }
        msg = hudson.model.Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg);
        LOGGER.log(Level.SEVERE, msg, e);
        e.printStackTrace(listener.error(msg));
        if (_proc != null)
            try {
                ProcessTree.get().killAll(_proc, _cookie);
            } catch (InterruptedException x) {
                x.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
            }
    }
}
Also used : StreamCopyThread(hudson.util.StreamCopyThread) Channel(hudson.remoting.Channel) IOException(java.io.IOException) EnvVars(hudson.EnvVars)

Aggregations

Channel (hudson.remoting.Channel)12 VirtualChannel (hudson.remoting.VirtualChannel)7 IOException (java.io.IOException)7 StreamCopyThread (hudson.util.StreamCopyThread)2 PrintStream (java.io.PrintStream)2 EnvVars (hudson.EnvVars)1 FilePath (hudson.FilePath)1 CliEntryPoint (hudson.cli.CliEntryPoint)1 CliManagerImpl (hudson.cli.CliManagerImpl)1 WindowsSlaveInstaller (hudson.lifecycle.WindowsSlaveInstaller)1 Computer (hudson.model.Computer)1 TaskListener (hudson.model.TaskListener)1 Listener (hudson.remoting.Channel.Listener)1 FastPipedInputStream (hudson.remoting.FastPipedInputStream)1 FastPipedOutputStream (hudson.remoting.FastPipedOutputStream)1 LocalChannel (hudson.remoting.LocalChannel)1 PingThread (hudson.remoting.PingThread)1 SocketInputStream (hudson.remoting.SocketInputStream)1 SocketOutputStream (hudson.remoting.SocketOutputStream)1 ChannelTermination (hudson.slaves.OfflineCause.ChannelTermination)1