hudson.remoting.VirtualChannel Java Examples

The following examples show how to use hudson.remoting.VirtualChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DockerBuildImageStepFileCallable.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
public List<String> invoke(File f, VirtualChannel channel) throws IOException {
    PrintStream llog = taskListener.getLogger();
    llog.println("Creating connection to docker daemon...");
    try (DockerClient client = connector.getClient()) {
        BuildImageCmd buildImageCmd = client.buildImageCmd();
        buildImage.fillSettings(buildImageCmd);
        llog.println("Pulling image ");
        String imageId = buildImageCmd.exec(new MyBuildImageResultCallback(llog))
                .awaitImageId();
        llog.println(imageId);
        llog.println("Image tagging during build isn't support atm, no tags applied.");
    } catch (Exception ex) {
        LOG.error("Can't get client", ex);
        throw new IOException("Can't get docker client", ex);
    }

    return null;
}
 
Example #2
Source File: ZipStepExecution.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Override
public Integer invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
    String canonicalZip = zipFile.getRemote();
    if (overwrite && !Files.deleteIfExists(Paths.get(canonicalZip))) {
        throw new IOException("Failed to delete " + canonicalZip);
    }

    Archiver archiver = ArchiverFactory.ZIP.create(zipFile.write());
    FileSet fs = Util.createFileSet(dir, glob);
    DirectoryScanner scanner = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
    try {
        for (String path : scanner.getIncludedFiles()) {
            File toArchive = new File(dir, path).getCanonicalFile();
            if (!toArchive.getPath().equals(canonicalZip)) {
                archiver.visit(toArchive, path);
            }
        }
    } finally {
        archiver.close();
    }
    return archiver.countEntries();
}
 
Example #3
Source File: DockerServerEndpoint.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
/**
 * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters
 * needed to access it.
 * 
 * @deprecated Call {@link #newKeyMaterialFactory(Run, VirtualChannel)}
 */
@Deprecated
public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Item context, @Nonnull VirtualChannel target) throws IOException, InterruptedException {
    // as a build step, your access to credentials are constrained by what the build
    // can access, hence Jenkins.getAuthentication()
    DockerServerCredentials creds=null;
    if (credentialsId!=null) {
        List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build();
        domainRequirements.add(new DockerServerDomainRequirement());
        creds = CredentialsMatchers.firstOrNull(
                CredentialsProvider.lookupCredentials(
                        DockerServerCredentials.class, context, Jenkins.getAuthentication(),
                        domainRequirements),
                CredentialsMatchers.withId(credentialsId)
        );
    }

    // the directory needs to be outside workspace to avoid prying eyes
    FilePath dotDocker = dotDocker(target);
    dotDocker.mkdirs();
    // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed:
    return newKeyMaterialFactory(dotDocker, creds);
}
 
Example #4
Source File: DockerServerEndpoint.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
/**
 * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters
 * needed to access it.
 */
public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Run context, @Nonnull VirtualChannel target) throws IOException, InterruptedException {
    DockerServerCredentials creds=null;
    if (credentialsId!=null) {
        List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build();
        domainRequirements.add(new DockerServerDomainRequirement());
        creds = CredentialsProvider.findCredentialById(credentialsId, DockerServerCredentials.class, context,
                domainRequirements);
    }

    // the directory needs to be outside workspace to avoid prying eyes
    FilePath dotDocker = dotDocker(target);
    dotDocker.mkdirs();
    // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed:
    return newKeyMaterialFactory(dotDocker, creds);
}
 
Example #5
Source File: JUnitParser.java    From junit-plugin with MIT License 6 votes vote down vote up
public TestResult invoke(File ws, VirtualChannel channel) throws IOException {
    final long nowSlave = System.currentTimeMillis();

    FileSet fs = Util.createFileSet(ws, testResults);
    DirectoryScanner ds = fs.getDirectoryScanner();
    TestResult result = null;

    String[] files = ds.getIncludedFiles();
    if (files.length > 0) {
        result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio, pipelineTestDetails);
        result.tally();
    } else {
        if (this.allowEmptyResults) {
            result = new TestResult();
        } else {
            // no test result. Most likely a configuration
            // error or fatal problem
            throw new AbortException(Messages.JUnitResultArchiver_NoTestReportFound());
        }
    }
    return result;
}
 
Example #6
Source File: FlakyTestResultAction.java    From flaky-test-handler-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a FlakyTestResultAction object with Run and BuildListener
 *
 * @param build this build
 * @param listener listener of this build
 */
public FlakyTestResultAction(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
  this.build = build;
  // TODO consider the possibility that there is >1 such action
  AbstractTestResultAction action = build.getAction(AbstractTestResultAction.class);
  if (action != null) {
    Object latestResult = action.getResult();
    if (latestResult != null && latestResult instanceof TestResult) {
      VirtualChannel channel = launcher.getChannel();
      if(channel == null) {
        throw new InterruptedException("Could not get channel to run a program remotely.");
      }
      FlakyTestResult flakyTestResult = channel.call(new FlakyTestResultCollector((TestResult) latestResult));

      flakyTestResult.freeze(action, build);
      FlakyRunStats stats = new FlakyRunStats(flakyTestResult.getTestFlakyStatsMap());
      setFlakyRunStats(stats, listener);
    }
  } else {
    logger.log(Level.WARNING, "No test result found, please publish junit report first");
  }
}
 
Example #7
Source File: TeeStep.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
/** @see FilePath#write() */
private static OutputStream append(FilePath fp, OutputStream stream) throws IOException, InterruptedException {
    if (stream == null) {
        return fp.act(new MasterToSlaveFileCallable<OutputStream>() {
            private static final long serialVersionUID = 1L;
            @Override
            public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
                f = f.getAbsoluteFile();
                if (!f.getParentFile().exists() && !f.getParentFile().mkdirs()) {
                    throw new IOException("Failed to create directory " + f.getParentFile());
                }
                try {
                    return new RemoteOutputStream(Files.newOutputStream(f.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND/*, StandardOpenOption.DSYNC*/));
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }
            }
        });
    }
    return stream;
}
 
Example #8
Source File: ZAProxy.java    From zaproxy-plugin with MIT License 6 votes vote down vote up
public File[] invoke(File f, VirtualChannel channel) {
	File[] listFiles = {};
	
	Path pathAuthenticationScriptsDir = Paths.get(zapDefaultDir, NAME_SCRIPTS_DIR_ZAP, NAME_AUTHENTICATION_SCRIPTS_DIR_ZAP);
	 
	if(Files.isDirectory(pathAuthenticationScriptsDir)) {
		File zapAuthenticationScriptsDir =  pathAuthenticationScriptsDir.toFile() ;
		// create new filename filter (the filter returns true as all the extensions are accepted)
		FilenameFilter policyFilter = new FilenameFilter() {

			@Override
			
			public boolean accept(File dir, String name) {
				return true;
				 
			}
		};
		
		// returns pathnames for files and directory
		listFiles = zapAuthenticationScriptsDir.listFiles(policyFilter);
	}
	return listFiles;
}
 
Example #9
Source File: DeployerRunner.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
public boolean perform() throws Exception {
    FilePath rootFileObject = new FilePath(this.workspace, config.getRootObject());

    final DeployerContext
            deployerContext = new DeployerContext(config, rootFileObject, listener);

    final VirtualChannel channel = launcher.getChannel();

    if (null == channel)
        throw new IllegalStateException("Null Channel (?)");

    final Future<Boolean>
            booleanFuture =
            channel.callAsync(new SlaveDeployerCallable(deployerContext));

    return booleanFuture.get();
}
 
Example #10
Source File: Git.java    From git-client-plugin with MIT License 6 votes vote down vote up
public GitClient invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
    if (listener == null) listener = TaskListener.NULL;
    if (env == null) env = new EnvVars();

    if (Main.isUnitTest && System.getProperty(Git.class.getName() + ".mockClient") != null) {
        return initMockClient(System.getProperty(Git.class.getName() + ".mockClient"),
                exe, env, f, listener);
    }

    if (exe == null || JGitTool.MAGIC_EXENAME.equalsIgnoreCase(exe)) {
        return new JGitAPIImpl(f, listener);
    }

    if (JGitApacheTool.MAGIC_EXENAME.equalsIgnoreCase(exe)) {
        final PreemptiveAuthHttpClientConnectionFactory factory = new PreemptiveAuthHttpClientConnectionFactory();
        return new JGitAPIImpl(f, listener, factory);
    }
    // Ensure we return a backward compatible GitAPI, even API only claim to provide a GitClient
    return new GitAPI(exe, f, listener, env);
}
 
Example #11
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
public void test_clone_refspecs() throws Exception {
    List<RefSpec> refspecs = Arrays.asList(
            new RefSpec("+refs/heads/master:refs/remotes/origin/master"),
            new RefSpec("+refs/heads/1.4.x:refs/remotes/origin/1.4.x")
    );
    testGitClient.clone_().url(workspace.localMirror()).refspecs(refspecs).repositoryName("origin").execute();
    testGitClient.withRepository((Repository workRepo, VirtualChannel channel) -> {
        String[] fetchRefSpecs = workRepo.getConfig().getStringList(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
        assertThat(fetchRefSpecs.length, is(2));
        assertThat(fetchRefSpecs[0], is("+refs/heads/master:refs/remotes/origin/master"));
        assertThat(fetchRefSpecs[1], is("+refs/heads/1.4.x:refs/remotes/origin/1.4.x"));
        return null;
    });
    Set<Branch> remoteBranches = testGitClient.getRemoteBranches();
    assertBranchesExist(remoteBranches, "origin/master");
    assertBranchesExist(remoteBranches, "origin/1.4.x");
    assertThat(remoteBranches.size(), is(2));
}
 
Example #12
Source File: FilesScanner.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@Override
public Report invoke(final File workspace, final VirtualChannel channel) {
    Report report = new Report();
    report.logInfo("Searching for all files in '%s' that match the pattern '%s'",
            workspace.getAbsolutePath(), filePattern);

    String[] fileNames = new FileFinder(filePattern, StringUtils.EMPTY, followSymbolicLinks).find(workspace);
    if (fileNames.length == 0) {
        report.logError("No files found for pattern '%s'. Configuration error?", filePattern);
    }
    else {
        report.logInfo("-> found %s", plural(fileNames.length, "file"));
        scanFiles(workspace, fileNames, report);
    }

    return report;
}
 
Example #13
Source File: ZAProxyBuilder.java    From zaproxy-plugin with MIT License 5 votes vote down vote up
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
	File fileCopiedDir = new File(zapDefaultDir, ZAProxy.NAME_POLICIES_DIR_ZAP);
	File fileCopied = new File(fileCopiedDir, copyFilename);
	
	FileUtils.writeStringToFile(fileCopied, data);
	stringForLogger += "[" + fileCopied.getAbsolutePath() + "]";
	return stringForLogger;
}
 
Example #14
Source File: DockerServerEndpointTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test
public void smokes() throws Exception {
    DumbSlave slave = j.createOnlineSlave();
    VirtualChannel channel = slave.getChannel();
    FreeStyleProject item = j.createFreeStyleProject();
    CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
    assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
    Domain domain = new Domain("docker", "A domain for docker credentials",
            Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
    DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c");
    store.addDomain(domain, credentials);
    DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId());
    FilePath dotDocker = DockerServerEndpoint.dotDocker(channel);
    List<FilePath> dotDockerKids = dotDocker.list();
    int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size();
    KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel);
    KeyMaterial keyMaterial = factory.materialize();
    FilePath path = null;
    try {
        assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736"));
        assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1"));
        assertThat(keyMaterial.env().get("DOCKER_CERT_PATH", "missing"), not("missing"));
        path = new FilePath(channel, keyMaterial.env().get("DOCKER_CERT_PATH", "missing"));
        if (!Functions.isWindows()) {
            assertThat(path.mode() & 0777, is(0700));
        }
        assertThat(path.child("key.pem").readToString(), is("a"));
        assertThat(path.child("cert.pem").readToString(), is("b"));
        assertThat(path.child("ca.pem").readToString(), is("c"));
    } finally {
        keyMaterial.close();
    }
    assertThat(path.child("key.pem").exists(), is(false));
    assertThat(path.child("cert.pem").exists(), is(false));
    assertThat(path.child("ca.pem").exists(), is(false));
    assertThat(dotDocker.list().size(), is(initialSize));
}
 
Example #15
Source File: ZAProxy.java    From zaproxy-plugin with MIT License 5 votes vote down vote up
public File[] invoke(File f, VirtualChannel channel) {
	File[] listFiles = {};
	
	Path pathPolicyDir = Paths.get(zapDefaultDir, NAME_POLICIES_DIR_ZAP);
	
	if(Files.isDirectory(pathPolicyDir)) {
		File zapPolicyDir = new File(zapDefaultDir, NAME_POLICIES_DIR_ZAP);
		// create new filename filter (get only file with FILE_POLICY_EXTENSION extension)
		FilenameFilter policyFilter = new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.lastIndexOf('.') > 0) {
					// get last index for '.' char
					int lastIndex = name.lastIndexOf('.');

					// get extension
					String str = name.substring(lastIndex);

					// match path name extension
					if (str.equals(FILE_POLICY_EXTENSION)) {
						return true;
					}
				}
				return false;
			}
		};
		
		// returns pathnames for files and directory
		listFiles = zapPolicyDir.listFiles(policyFilter);
	}
	return listFiles;
}
 
Example #16
Source File: DockerImageComboStepFileCallable.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public DockerImageComboStepResponse invoke(File f, VirtualChannel channel) throws IOException {
    PrintStream llog = taskListener.getLogger();
    llog.println("Creating connection to docker daemon...");
    try (DockerClient client = connector.getClient()) {
        return invoke(client);
    } catch (Exception ex) {
        Throwables.propagate(ex);
    }

    return null;
}
 
Example #17
Source File: DockerImageCleanupFileCallable.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
    PrintStream llog = taskListener.getLogger();
    llog.println("Creating connection to docker daemon...");
    try (DockerClient client = connector.getClient()) {
        return invoke(client);
    } catch (Exception ex) {
        Throwables.propagate(ex);
    }

    return null;
}
 
Example #18
Source File: DockerRegistryEndpoint.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
/**
 * @deprecated Call {@link #newKeyMaterialFactory(Run, FilePath, Launcher, EnvVars, TaskListener, String)}
 */
@Deprecated
public KeyMaterialFactory newKeyMaterialFactory(@CheckForNull Item context, @Nonnull VirtualChannel target, @CheckForNull Launcher launcher, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    if (credentialsId == null) {
        return KeyMaterialFactory.NULL; // nothing needed to be done
    }
    DockerRegistryToken token = getToken(context);
    if (token == null) {
        throw new AbortException("Could not find credentials matching " + credentialsId);
    }
    return token.newKeyMaterialFactory(getEffectiveUrl(), target, launcher, listener);
}
 
Example #19
Source File: SSHStepExecution.java    From ssh-steps-plugin with Apache License 2.0 5 votes vote down vote up
protected VirtualChannel getChannel() {
  final VirtualChannel channel = getLauncher().getChannel();
  if (channel == null) {
    throw new IllegalArgumentException(
        "Unable to get the channel, Perhaps you forgot to surround the code with a step that provides this, such as: node, dockerNode");
  }
  return channel;
}
 
Example #20
Source File: S3UploadAllCallable.java    From jobcacher-plugin with MIT License 5 votes vote down vote up
/**
 * Upload from slave
 */
@Override
public Integer invoke(final TransferManager transferManager, File base, VirtualChannel channel) throws IOException, InterruptedException {
    if(!base.exists())  return 0;

    final AtomicInteger count = new AtomicInteger(0);
    final Uploads uploads = new Uploads();

    final Map<String, S3ObjectSummary> summaries = lookupExistingCacheEntries(transferManager.getAmazonS3Client());

    // Find files to upload that match scan
    scanner.scan(base, new FileVisitor() {
        @Override
        public void visit(File f, String relativePath) throws IOException {
            if (f.isFile()) {
                String key = pathPrefix + "/" + relativePath;

                S3ObjectSummary summary = summaries.get(key);
                if (summary == null || f.lastModified() > summary.getLastModified().getTime()) {
                    final ObjectMetadata metadata = buildMetadata(f);

                    uploads.startUploading(transferManager, f, IOUtils.toBufferedInputStream(FileUtils.openInputStream(f)), new Destination(bucketName, key), metadata);

                    if (uploads.count() > 20) {
                        waitForUploads(count, uploads);
                    }
                }
            }
        }
    });

    // Wait for each file to complete before returning
    waitForUploads(count, uploads);

    return uploads.count();
}
 
Example #21
Source File: RegistryKeyMaterialFactoryTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Before
   public void setup() throws Exception {
// fake launcher for the docker login invocation
FakeLauncher faker = new FakeLauncher() {
    @Override
    public Proc onLaunch(final ProcStarter p) throws IOException {
	return new FinishedProc(0);
    }
};

PretendSlave slave = j.createPretendSlave(faker);
// VirtualChannel channel = slave.getChannel();
// FreeStyleProject project = j.createFreeStyleProject();

TaskListener listener = TaskListener.NULL;
Launcher launcher = slave.createLauncher(listener);
launcher = new Launcher.DecoratedLauncher(launcher) {
    @Override
    public VirtualChannel getChannel() {
	return new LocalChannel(null) {
	    @Override
	    public <V, T extends Throwable> V call(final Callable<V, T> callable) throws T {
		// ugly as hell, but we need a way to mock fetching the home directory
		return (V) new FilePath(tempFolder.getRoot());
	    }
	};
    }
};

URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl();
EnvVars env = new EnvVars();
String dockerExecutable = DockerTool.getExecutable(null, null, listener, env);

factory = new RegistryKeyMaterialFactory("username", "password", endpoint, launcher, env, listener,
	dockerExecutable).contextualize(new KeyMaterialContext(new FilePath(tempFolder.newFolder())));
   }
 
Example #22
Source File: IssuesScanner.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@Override
public AnnotatedReport invoke(final File workspace, final VirtualChannel channel) throws InterruptedException {
    resolvePaths(originalReport);
    resolveModuleNames(originalReport, workspace);
    resolvePackageNames(originalReport);

    Report filtered = filter(originalReport, filters, id);

    createFingerprints(filtered);

    FileLocations fileLocations = new ReportLocations().toFileLocations(filtered);
    return new AnnotatedReport(id, filtered,
            blame(filtered, fileLocations),
            mineRepository(filtered, fileLocations));
}
 
Example #23
Source File: DefaultTestResultParserImpl.java    From junit-plugin with MIT License 5 votes vote down vote up
@Override
public TestResult parseResult(final String testResultLocations, final Run<?,?> build, FilePath workspace, final Launcher launcher, final TaskListener listener) throws InterruptedException, IOException {
    return workspace.act(new MasterToSlaveFileCallable<TestResult>() {
        final boolean ignoreTimestampCheck = IGNORE_TIMESTAMP_CHECK; // so that the property can be set on the master
        final long buildTime = build.getTimestamp().getTimeInMillis();
        final long nowMaster = System.currentTimeMillis();

        public TestResult invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
            final long nowSlave = System.currentTimeMillis();

            // files older than this timestamp is considered stale
            long localBuildTime = buildTime + (nowSlave - nowMaster);

            FilePath[] paths = new FilePath(dir).list(testResultLocations);
            if (paths.length==0)
                throw new AbortException("No test reports that matches "+testResultLocations+" found. Configuration error?");

            // since dir is local, paths all point to the local files
            List<File> files = new ArrayList<File>(paths.length);
            for (FilePath path : paths) {
                File report = new File(path.getRemote());
                if (ignoreTimestampCheck || localBuildTime - 3000 /*error margin*/ < report.lastModified()) {
                    // this file is created during this build
                    files.add(report);
                }
            }

            if (files.isEmpty()) {
                // none of the files were new
                throw new AbortException(
                    String.format(
                    "Test reports were found but none of them are new. Did tests run? %n"+
                    "For example, %s is %s old%n", paths[0].getRemote(),
                    Util.getTimeSpanString(localBuildTime-paths[0].lastModified())));
            }

            return parse(files,launcher,listener);
        }
    });
}
 
Example #24
Source File: JUnitFlakyTestDataPublisher.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public TestResultAction.Data contributeTestData(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener, TestResult testResult)
    throws IOException, InterruptedException {
  VirtualChannel channel = launcher.getChannel();
  if(channel == null) {
        throw new InterruptedException("Could not get channel to run a program remotely.");
  }
  FlakyTestResult flakyTestResult = channel.call(new FlakyTestResultCollector(testResult));
  // TODO consider the possibility that there is >1 such action
  flakyTestResult.freeze(run.getAction(AbstractTestResultAction.class), run);
  return new JUnitFlakyTestData(flakyTestResult);
}
 
Example #25
Source File: AbstractGitTestCase.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException {
  return build.getWorkspace().act(new MasterToSlaveFileCallable<String>() {
    public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
      try {
        ObjectId oid = Git.with(null, null).in(f).getClient().getRepository().resolve("refs/heads/" + branch);
        return oid.name();
      } catch (GitException e) {
        throw new RuntimeException(e);
      }
    }
  });
}
 
Example #26
Source File: JenkinsUtils.java    From docker-plugin with MIT License 5 votes vote down vote up
/**
 * If the build was workflow, get the ID of that channel.
 */
@Restricted(NoExternalUse.class)
public static Optional<DockerCloud> getCloudForChannel(VirtualChannel channel) {
    if (channel instanceof Channel) {
        Channel c = (Channel) channel;
        Node node = Jenkins.getInstance().getNode(c.getName());
        if (node instanceof DockerTransientNode) {
            return Optional.of(((DockerTransientNode) node).getCloud());
        }
    }
    return Optional.empty();
}
 
Example #27
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
protected DockerAPI getDockerAPI(Launcher launcher) {
    DockerCloud theCloud;
    final VirtualChannel channel = launcher.getChannel();
    if (!Strings.isNullOrEmpty(cloud)) {
        theCloud = JenkinsUtils.getServer(cloud);
    } else {
        if(channel instanceof Channel) {
            final Node node = Jenkins.getInstance().getNode(((Channel)channel).getName() );
            if (node instanceof DockerTransientNode) {
                return ((DockerTransientNode) node).getDockerAPI();
            }
        }
        final Optional<DockerCloud> cloudForChannel = JenkinsUtils.getCloudForChannel(channel);
        if (!cloudForChannel.isPresent())
            throw new RuntimeException("Could not find the cloud this project was built on");
        theCloud = cloudForChannel.get();
    }

    // Triton can't do docker build. Ensure we're not trying to do that.
    if (theCloud.isTriton()) {
        LOGGER.warn("Selected cloud for build does not support this feature. Finding an alternative");
        for (DockerCloud dc : JenkinsUtils.getServers()) {
            if (!dc.isTriton()) {
                LOGGER.warn("Picked {} cloud instead", dc.getDisplayName());
                theCloud = dc;
                break;
            }
        }
    }
    return theCloud.getDockerApi();
}
 
Example #28
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_clone_refspec() throws Exception {
    testGitClient.clone_().url(workspace.localMirror()).repositoryName("origin").execute();

    WorkspaceWithRepo anotherWorkspace = new WorkspaceWithRepo(secondRepo.getRoot(), "git", listener);
    anotherWorkspace.launchCommand("git", "clone", anotherWorkspace.localMirror(), "./");
    anotherWorkspace.getGitClient().withRepository((final Repository realRepo, VirtualChannel channel) -> anotherWorkspace.getGitClient().withRepository((final Repository implRepo, VirtualChannel channel1) -> {
        final String realRefspec = realRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
        final String implRefspec = implRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
        assertThat("Refspecs vs. original clone", implRefspec, is(realRefspec));
        return null;
    }));
}
 
Example #29
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
private void assertSubmoduleRepository(File submoduleDir) throws Exception {
    /* Get a client directly on the submoduleDir */
    GitClient submoduleClient = setupGitAPI(submoduleDir);

    /* Assert that when we invoke the repository callback it gets a
     * functioning repository object
     */
    submoduleClient.withRepository((final Repository repo, VirtualChannel channel) -> {
        assertTrue(repo.getDirectory() + " is not a valid repository",
                repo.getObjectDatabase().exists());
        return null;
    });
}
 
Example #30
Source File: RemotingTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * Makes sure {@link GitClient} is remotable.
 */
@Test
public void testRemotability() throws Exception {
    DumbSlave agent = j.createSlave();

    GitClient jgit = new JGitAPIImpl(tempFolder.getRoot(), StreamBuildListener.fromStdout());

    Computer c = agent.toComputer();
    c.connect(false).get();
    VirtualChannel channel = c.getChannel();
    channel.call(new Work(jgit));
    channel.close();
}