Search in sources :

Example 1 with SmbFile

use of jcifs.smb.SmbFile in project hudson-2.x by hudson.

the class WindowsRemoteFileSystem method pullUp.

public void pullUp(String from, String to) throws IOException, InterruptedException {
    SmbFile src = $(from);
    SmbFile dst = $(to);
    for (SmbFile e : src.listFiles()) {
        e.renameTo(new SmbFile(dst, e.getName()));
    }
    src.delete();
}
Also used : SmbFile(jcifs.smb.SmbFile)

Example 2 with SmbFile

use of jcifs.smb.SmbFile 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 3 with SmbFile

use of jcifs.smb.SmbFile in project opennms by OpenNMS.

the class JCifsMonitor method poll.

/**
     * This method queries the CIFS share.
     *
     * @param svc        the monitored service
     * @param parameters the parameter map
     * @return the poll status for this system
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    final String domain = parameters.containsKey("domain") ? (String) parameters.get("domain") : "";
    final String username = parameters.containsKey("username") ? (String) parameters.get("username") : "";
    final String password = parameters.containsKey("password") ? (String) parameters.get("password") : "";
    String mode = parameters.containsKey("mode") ? ((String) parameters.get("mode")).toUpperCase() : "PATH_EXIST";
    String path = parameters.containsKey("path") ? (String) parameters.get("path") : "";
    String smbHost = parameters.containsKey("smbHost") ? (String) parameters.get("smbHost") : "";
    final String folderIgnoreFiles = parameters.containsKey("folderIgnoreFiles") ? (String) parameters.get("folderIgnoreFiles") : "";
    // changing to Ip address of MonitoredService if no smbHost is given
    if ("".equals(smbHost)) {
        smbHost = svc.getIpAddr();
    }
    // Filename filter to give user the possibility to ignore specific files in folder for the folder check.
    SmbFilenameFilter smbFilenameFilter = new SmbFilenameFilter() {

        @Override
        public boolean accept(SmbFile smbFile, String s) throws SmbException {
            return !s.matches(folderIgnoreFiles);
        }
    };
    // Initialize mode with default as PATH_EXIST
    Mode enumMode = Mode.PATH_EXIST;
    try {
        enumMode = Mode.valueOf(mode);
    } catch (IllegalArgumentException exception) {
        logger.error("Mode '{}‘ does not exists. Valid candidates are {}", mode, modeCandidates);
        return PollStatus.unknown("Mode " + mode + " does not exists. Valid candidates are " + modeCandidates);
    }
    // Checking path parameter
    if (!path.startsWith("/")) {
        path = "/" + path;
        logger.debug("Added leading / to path.");
    }
    // Build authentication string for NtlmPasswordAuthentication: syntax: domain;username:password
    String authString = "";
    // Setting up authenticationString...
    if (domain != null && !"".equals(domain)) {
        authString += domain + ";";
    }
    authString += username + ":" + password;
    // ... and path
    String fullUrl = "smb://" + smbHost + path;
    logger.debug("Domain: [{}], Username: [{}], Password: [{}], Mode: [{}], Path: [{}], Authentication: [{}], Full Url: [{}]", new Object[] { domain, username, password, mode, path, authString, fullUrl });
    // Initializing TimeoutTracker with default values
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Setting default PollStatus
    PollStatus serviceStatus = PollStatus.unknown();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        NtlmPasswordAuthentication ntlmPasswordAuthentication = new NtlmPasswordAuthentication(authString);
        try {
            // Creating SmbFile object
            SmbFile smbFile = new SmbFile(fullUrl, ntlmPasswordAuthentication);
            // Setting the defined timeout
            smbFile.setConnectTimeout(tracker.getConnectionTimeout());
            // Does the file exists?
            boolean smbFileExists = smbFile.exists();
            switch(enumMode) {
                case PATH_EXIST:
                    if (smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case PATH_NOT_EXIST:
                    if (!smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should not exists but does!");
                    }
                    break;
                case FOLDER_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length == 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should be empty but isn't!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case FOLDER_NOT_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length > 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should not be empty but is!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                default:
                    logger.warn("There is no implementation for the specified mode '{}'", mode);
                    break;
            }
        } catch (MalformedURLException exception) {
            logger.error("Malformed URL on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        } catch (SmbException exception) {
            logger.error("SMB error on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        }
    }
    return serviceStatus;
}
Also used : SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) SmbFilenameFilter(jcifs.smb.SmbFilenameFilter) SmbFile(jcifs.smb.SmbFile)

Example 4 with SmbFile

use of jcifs.smb.SmbFile in project android-toolbox by Knickedi.

the class SmbUtils method listAvailableHosts.

/**
	 * Get list with available hosts from samba network.<br>
	 * <br>
	 * This method is time critical because it will contact the network. You could do that once and
	 * cache result. Do that on another thread. Be aware of the fact a network request could fail
	 * and give an empty or incomplete list although host should be available.<br>
	 * <br>
	 * <b>Note</b>: Don't forget to request for Internet permission in manifest!
	 * 
	 * @param withIp
	 *            {@code true} when IP of host should be listed too (does it anyway when found host
	 *            is not a name but an IP)
	 * 
	 * @return list with all available (found) hosts
	 */
public static String[] listAvailableHosts(boolean withIp) {
    List<String> hostNames = new ArrayList<String>();
    try {
        SmbFile[] workgroups = new SmbFile("smb://").listFiles();
        for (int i = 0; i < workgroups.length; i++) {
            try {
                SmbFile[] hosts = workgroups[i].listFiles();
                // check hosts in workgroup
                for (int j = 0; j < hosts.length; j++) {
                    String name = hosts[j].getName();
                    String nameWithoutSlash = name.substring(0, name.length() - 1);
                    hostNames.add(nameWithoutSlash);
                    if (withIp && !IP_PATTERN.matcher(nameWithoutSlash).matches()) {
                        try {
                            hostNames.add(InetAddress.getByName(nameWithoutSlash).getHostAddress());
                        } catch (UnknownHostException e) {
                        // could not resolve IP - skip it
                        }
                    }
                }
            } catch (SmbException e) {
            // can't retrieve list of host from workgroup - skip it
            }
        }
    } catch (SmbException e) {
    // smb:// should be valid - just skip on error
    } catch (MalformedURLException e) {
        // should never happen - smb:// is valid
        throw new RuntimeException(e);
    }
    String[] hosts = hostNames.toArray(new String[0]);
    return hosts;
}
Also used : SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) SmbFile(jcifs.smb.SmbFile)

Aggregations

SmbFile (jcifs.smb.SmbFile)4 SmbException (jcifs.smb.SmbException)3 MalformedURLException (java.net.MalformedURLException)2 UnknownHostException (java.net.UnknownHostException)2 TaskListener (hudson.model.TaskListener)1 Channel (hudson.remoting.Channel)1 Listener (hudson.remoting.Channel.Listener)1 SocketInputStream (hudson.remoting.SocketInputStream)1 SocketOutputStream (hudson.remoting.SocketOutputStream)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 StringReader (java.io.StringReader)1 InetAddress (java.net.InetAddress)1 InetSocketAddress (java.net.InetSocketAddress)1 Socket (java.net.Socket)1 ArrayList (java.util.ArrayList)1 NtlmPasswordAuthentication (jcifs.smb.NtlmPasswordAuthentication)1