Search in sources :

Example 1 with StreamTaskListener

use of hudson.util.StreamTaskListener in project hudson-2.x by hudson.

the class WindowsInstallerLink method doDoInstall.

/**
     * Performs installation.
     */
public void doDoInstall(StaplerRequest req, StaplerResponse rsp, @QueryParameter("dir") String _dir) throws IOException, ServletException {
    if (installationDir != null) {
        // installation already complete
        sendError("Installation is already complete", req, rsp);
        return;
    }
    if (!DotNet.isInstalled(2, 0)) {
        sendError(".NET Framework 2.0 or later is required for this feature", req, rsp);
        return;
    }
    Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
    File dir = new File(_dir).getAbsoluteFile();
    dir.mkdirs();
    if (!dir.exists()) {
        sendError("Failed to create installation directory: " + dir, req, rsp);
        return;
    }
    try {
        // copy files over there
        copy(req, rsp, dir, getClass().getResource("/windows-service/hudson.exe"), "hudson.exe");
        copy(req, rsp, dir, getClass().getResource("/windows-service/hudson.xml"), "hudson.xml");
        if (!hudsonWar.getCanonicalFile().equals(new File(dir, "hudson.war").getCanonicalFile()))
            copy(req, rsp, dir, hudsonWar.toURI().toURL(), "hudson.war");
        // install as a service
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamTaskListener task = new StreamTaskListener(baos);
        task.getLogger().println("Installing a service");
        int r = WindowsSlaveInstaller.runElevated(new File(dir, "hudson.exe"), "install", task, dir);
        if (r != 0) {
            sendError(baos.toString(), req, rsp);
            return;
        }
        // installation was successful
        installationDir = dir;
        rsp.sendRedirect(".");
    } catch (AbortException e) {
    // this exception is used as a signal to terminate processing. the error should have been already reported
    } catch (InterruptedException e) {
        throw new ServletException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) StreamTaskListener(hudson.util.StreamTaskListener) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) File(java.io.File) AbortException(hudson.AbortException)

Example 2 with StreamTaskListener

use of hudson.util.StreamTaskListener in project hudson-2.x by hudson.

the class SlaveComputer method setChannel.

/**
     * Creates a {@link Channel} from the given stream and sets that to this slave.
     *
     * @param in
     *      Stream connected to the remote "slave.jar". It's the caller's responsibility to do
     *      buffering on this stream, if that's necessary.
     * @param out
     *      Stream connected to the remote peer. It's the caller's responsibility to do
     *      buffering on this stream, if that's necessary.
     * @param launchLog
     *      If non-null, receive the portion of data in <tt>is</tt> before
     *      the data goes into the "binary mode". This is useful
     *      when the established communication channel might include some data that might
     *      be useful for debugging/trouble-shooting.
     * @param listener
     *      Gets a notification when the channel closes, to perform clean up. Can be null.
     *      By the time this method is called, the cause of the termination is reported to the user,
     *      so the implementation of the listener doesn't need to do that again.
     */
public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException {
    if (this.channel != null)
        throw new IllegalStateException("Already connected");
    final TaskListener taskListener = new StreamTaskListener(launchLog);
    PrintStream log = taskListener.getLogger();
    Channel channel = new Channel(nodeName, threadPoolForRemoting, Channel.Mode.NEGOTIATE, in, out, launchLog);
    channel.addListener(new Channel.Listener() {

        @Override
        public void onClosed(Channel c, IOException cause) {
            SlaveComputer.this.channel = null;
            // Orderly shutdown will have null exception
            if (cause != null) {
                offlineCause = new ChannelTermination(cause);
                cause.printStackTrace(taskListener.error("Connection terminated"));
            } else {
                taskListener.getLogger().println("Connection terminated");
            }
            launcher.afterDisconnect(SlaveComputer.this, taskListener);
        }
    });
    if (listener != null)
        channel.addListener(listener);
    String slaveVersion = channel.call(new SlaveVersion());
    log.println("Slave.jar version: " + slaveVersion);
    boolean _isUnix = channel.call(new DetectOS());
    log.println(_isUnix ? hudson.model.Messages.Slave_UnixSlave() : hudson.model.Messages.Slave_WindowsSlave());
    String defaultCharsetName = channel.call(new DetectDefaultCharset());
    String remoteFs = getNode().getRemoteFS();
    if (_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
        log.println("WARNING: " + remoteFs + " looks suspiciously like Windows path. Maybe you meant " + remoteFs.replace('\\', '/') + "?");
    FilePath root = new FilePath(channel, getNode().getRemoteFS());
    channel.call(new SlaveInitializer());
    channel.call(new WindowsSlaveInstaller(remoteFs));
    for (ComputerListener cl : ComputerListener.all()) cl.preOnline(this, channel, root, taskListener);
    offlineCause = null;
    // update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet
    synchronized (channelLock) {
        if (this.channel != null) {
            // check again. we used to have this entire method in a big sycnhronization block,
            // but Channel constructor blocks for an external process to do the connection
            // if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream.
            // so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch,
            // we'll end up queuing the lot of threads in a pseudo deadlock.
            // This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this.
            channel.close();
            throw new IllegalStateException("Already connected");
        }
        isUnix = _isUnix;
        numRetryAttempt = 0;
        this.channel = channel;
        defaultCharset = Charset.forName(defaultCharsetName);
    }
    for (ComputerListener cl : ComputerListener.all()) cl.onOnline(this, taskListener);
    log.println("Slave successfully connected and online");
    Hudson.getInstance().getQueue().scheduleMaintenance();
}
Also used : FilePath(hudson.FilePath) PrintStream(java.io.PrintStream) StreamTaskListener(hudson.util.StreamTaskListener) Channel(hudson.remoting.Channel) VirtualChannel(hudson.remoting.VirtualChannel) IOException(java.io.IOException) WindowsSlaveInstaller(hudson.lifecycle.WindowsSlaveInstaller) StreamTaskListener(hudson.util.StreamTaskListener) ChannelTermination(hudson.slaves.OfflineCause.ChannelTermination)

Example 3 with StreamTaskListener

use of hudson.util.StreamTaskListener in project hudson-2.x by hudson.

the class ZFSInstaller method init.

@Extension
public static AdministrativeMonitor init() {
    String migrationTarget = System.getProperty(ZFSInstaller.class.getName() + ".migrate");
    if (migrationTarget != null) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamTaskListener listener = new StreamTaskListener(new ForkOutputStream(System.out, out));
        try {
            if (migrate(listener, migrationTarget)) {
                // completed successfully
                return new MigrationCompleteNotice();
            }
        } catch (Exception e) {
            // if we let any exception from here, it will prevent Hudson from starting.
            e.printStackTrace(listener.error("Migration failed"));
        }
        // migration failed
        return new MigrationFailedNotice(out);
    }
    // install the monitor if applicable
    ZFSInstaller zi = new ZFSInstaller();
    if (zi.isActivated())
        return zi;
    return null;
}
Also used : ForkOutputStream(hudson.util.ForkOutputStream) StreamTaskListener(hudson.util.StreamTaskListener) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) ZFSException(org.jvnet.solaris.libzfs.ZFSException) IOException(java.io.IOException) Extension(hudson.Extension)

Example 4 with StreamTaskListener

use of hudson.util.StreamTaskListener in project hudson-2.x by hudson.

the class JDK method isDefaultJDKValid.

/**
     * Checks if "java" is in PATH on the given node.
     *
     * <p>
     * If it's not, then the user must specify a configured JDK,
     * so this is often useful for form field validation.
     */
public static boolean isDefaultJDKValid(Node n) {
    try {
        TaskListener listener = new StreamTaskListener(new NullStream());
        Launcher launcher = n.createLauncher(listener);
        return launcher.launch().cmds("java", "-fullversion").stdout(listener).join() == 0;
    } catch (IOException e) {
        return false;
    } catch (InterruptedException e) {
        return false;
    }
}
Also used : StreamTaskListener(hudson.util.StreamTaskListener) NullStream(hudson.util.NullStream) StreamTaskListener(hudson.util.StreamTaskListener) Launcher(hudson.Launcher) IOException(java.io.IOException)

Example 5 with StreamTaskListener

use of hudson.util.StreamTaskListener in project hudson-2.x by hudson.

the class AsyncPeriodicWork method doRun.

/**
     * Schedules this periodic work now in a new thread, if one isn't already running.
     */
public final void doRun() {
    try {
        if (thread != null && thread.isAlive()) {
            logger.log(Level.INFO, name + " thread is still running. Execution aborted.");
            return;
        }
        thread = new Thread(new Runnable() {

            public void run() {
                logger.log(Level.INFO, "Started " + name);
                long startTime = System.currentTimeMillis();
                StreamTaskListener l = createListener();
                try {
                    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
                    execute(l);
                } catch (IOException e) {
                    e.printStackTrace(l.fatalError(e.getMessage()));
                } catch (InterruptedException e) {
                    e.printStackTrace(l.fatalError("aborted"));
                } finally {
                    l.closeQuietly();
                }
                logger.log(Level.INFO, "Finished " + name + ". " + (System.currentTimeMillis() - startTime) + " ms");
            }
        }, name + " thread");
        thread.start();
    } catch (Throwable t) {
        logger.log(Level.SEVERE, name + " thread failed with error", t);
    }
}
Also used : StreamTaskListener(hudson.util.StreamTaskListener) IOException(java.io.IOException)

Aggregations

StreamTaskListener (hudson.util.StreamTaskListener)11 IOException (java.io.IOException)8 File (java.io.File)5 ByteArrayOutputStream (org.apache.commons.io.output.ByteArrayOutputStream)5 ServletException (javax.servlet.ServletException)3 AbortException (hudson.AbortException)2 ZFSException (org.jvnet.solaris.libzfs.ZFSException)2 JavaVMArguments (com.sun.akuma.JavaVMArguments)1 Extension (hudson.Extension)1 FilePath (hudson.FilePath)1 Launcher (hudson.Launcher)1 LocalLauncher (hudson.Launcher.LocalLauncher)1 WindowsSlaveInstaller (hudson.lifecycle.WindowsSlaveInstaller)1 EnvironmentSpecific (hudson.model.EnvironmentSpecific)1 Executor (hudson.model.Executor)1 Hudson (hudson.model.Hudson)1 Node (hudson.model.Node)1 Run (hudson.model.Run)1 Channel (hudson.remoting.Channel)1 VirtualChannel (hudson.remoting.VirtualChannel)1