org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint Java Examples

The following examples show how to use org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint. 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: DockerBuilderPublisher.java    From docker-plugin with MIT License 6 votes vote down vote up
@DataBoundConstructor
public DockerBuilderPublisher(String dockerFileDirectory,
                              @Nullable DockerRegistryEndpoint fromRegistry,
                              @Nullable String cloud,
                              @Nullable String tagsString,
                              boolean pushOnSuccess,
                              @Nullable String pushCredentialsId,
                              boolean cleanImages,
                              boolean cleanupWithJenkinsJobDelete) {
    this.dockerFileDirectory = dockerFileDirectory;
    this.fromRegistry = fromRegistry;
    setTagsString(tagsString);
    this.tag = null;
    this.cloud = cloud;
    this.pushOnSuccess = pushOnSuccess;
    this.pushCredentialsId = pushCredentialsId;
    this.cleanImages = cleanImages;
    this.cleanupWithJenkinsJobDelete = cleanupWithJenkinsJobDelete;
}
 
Example #2
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test
public void directParentNotSystem() throws Exception {
    GlobalConfig.get().setDockerLabel("config_docker");
    GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
    Folder folder = j.createProject(Folder.class);
    getFolderStore(folder).addCredentials(Domain.global(), folderCred);
    folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .inFolder(folder)
            .runFromRepo(false)
            .logContains("Docker Label is: folder_docker",
                    "Registry URL is: https://folder.registry",
                    "Registry Creds ID is: " + folderCred.getId())
            .logNotContains("Docker Label is: config_docker",
                    "Registry URL is: https://docker.registry",
                    "Registry Creds ID is: " + globalCred.getId()).go();
}
 
Example #3
Source File: ConfigTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test public void configRoundTrip() throws Exception {
    CredentialsStore store = CredentialsProvider.lookupStores(r.jenkins).iterator().next();
    IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate");
    store.addCredentials(Domain.global(), serverCredentials);
    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    store.addCredentials(Domain.global(), registryCredentials);
    SampleDockerBuilder b1 = new SampleDockerBuilder(new DockerServerEndpoint("", ""), new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId()));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    b1 = new SampleDockerBuilder(new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), new DockerRegistryEndpoint("", ""));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList()));
    b1.setToolName("Docker 1.5");
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
}
 
Example #4
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
private Object readResolve() {
    if (pushCredentialsId == null && registry != null) {
        pushCredentialsId = registry.getCredentialsId();
    }
    if (pullCredentialsId != null) {
        fromRegistry = new DockerRegistryEndpoint(null, pullCredentialsId);
    }
    return this;
}
 
Example #5
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
private void pushImages() throws IOException {
    for (String tagToUse : tagsToUse) {
        Identifier identifier = Identifier.fromCompoundString(tagToUse);
        PushImageResultCallback resultCallback = new PushImageResultCallback() {
            @Override
            public void onNext(PushResponseItem item) {
                if (item == null) {
                    // docker-java not happy if you pass it nulls.
                    log("Received NULL Push Response. Ignoring");
                    return;
                }
                printResponseItemToListener(listener, item);
                super.onNext(item);
            }
        };
        try(final DockerClient client = getClientWithNoTimeout()) {
            PushImageCmd cmd = client.pushImageCmd(identifier);

            int i = identifier.repository.name.indexOf('/');
            String regName = i >= 0 ?
                    identifier.repository.name.substring(0,i) : null;

            DockerCloud.setRegistryAuthentication(cmd,
                    new DockerRegistryEndpoint(regName, getPushCredentialsId()),
                    run.getParent().getParent());
            cmd.exec(resultCallback).awaitSuccess();
        } catch (DockerException ex) {
            // Private Docker registries fall over regularly. Tell the user so they
            // have some clue as to what to do as the exception gives no hint.
            log("Exception pushing docker image. Check that the destination registry is running.");
            throw ex;
        }
    }
}
 
Example #6
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
@Nonnull
private String buildImage() throws IOException, InterruptedException {
    final AuthConfigurations auths = new AuthConfigurations();
    final DockerRegistryEndpoint pullRegistry = getFromRegistry();
    if (pullRegistry != null && pullRegistry.getCredentialsId() != null) {
        auths.addConfig(DockerCloud.getAuthConfig(pullRegistry, run.getParent().getParent()));
    }
    log("Docker Build: building image at path " + fpChild.getRemote());
    final InputStream tar = fpChild.act(new DockerBuildCallable());
    BuildImageResultCallback resultCallback = new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
            String text = item.getStream();
            if (text != null) {
                listener.getLogger().println(text);
            }
            super.onNext(item);
        }
    };
    final String imageId;
    try(final DockerClient client = getClientWithNoTimeout()) {
        imageId = client.buildImageCmd(tar)
                .withNoCache(noCache)
                .withPull(pull)
                .withBuildAuthConfigs(auths)
                .exec(resultCallback)
                .awaitImageId();
        if (imageId == null) {
            throw new AbortException("Built image id is null. Some error occured");
        }
        // tag built image with tags
        for (String thisTag : tagsToUse) {
            final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(thisTag);
            final String commitTag = isEmpty(reposTag.tag) ? "latest" : reposTag.tag;
            log("Tagging built image with " + reposTag.repos + ":" + commitTag);
            client.tagImageCmd(imageId, reposTag.repos, commitTag).withForce().exec();
        }
    }
    return imageId;
}
 
Example #7
Source File: DockerTemplate.java    From docker-plugin with MIT License 5 votes vote down vote up
@Nonnull
InspectImageResponse pullImage(DockerAPI api, TaskListener listener) throws IOException, InterruptedException {
    final String image = getFullImageId();

    final boolean shouldPullImage;
    try(final DockerClient client = api.getClient()) {
        shouldPullImage = getPullStrategy().shouldPullImage(client, image);
    }
    if (shouldPullImage) {
        // TODO create a FlyWeightTask so end-user get visibility on pull operation progress
        LOGGER.info("Pulling image '{}'. This may take awhile...", image);

        long startTime = System.currentTimeMillis();

        try(final DockerClient client = api.getClient(pullTimeout)) {
            final PullImageCmd cmd =  client.pullImageCmd(image);
            final DockerRegistryEndpoint registry = getRegistry();
            DockerCloud.setRegistryAuthentication(cmd, registry, Jenkins.getInstance());
            cmd.exec(new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    super.onNext(item);
                    listener.getLogger().println(item.getStatus());
                }
            }).awaitCompletion();
        }

        long pullTime = System.currentTimeMillis() - startTime;
        LOGGER.info("Finished pulling image '{}', took {} ms", image, pullTime);
    }

    final InspectImageResponse result;
    try(final DockerClient client = api.getClient()) {
        result = client.inspectImageCmd(image).exec();
    } catch (NotFoundException e) {
        throw new DockerClientException("Could not pull image: " + image, e);
    }
    return result;
}
 
Example #8
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static AuthConfig getAuthConfig(DockerRegistryEndpoint registry, ItemGroup context) {
    AuthConfig auth = new AuthConfig();

    // we can't use DockerRegistryEndpoint#getToken as this one do check domainRequirement based on registry URL
    // but in some context (typically, passing registry auth for `docker build`) we just can't guess this one.

    final Credentials c = firstOrNull(CredentialsProvider.lookupCredentials(
            IdCredentials.class, context, ACL.SYSTEM, Collections.EMPTY_LIST),
            withId(registry.getCredentialsId()));
    final DockerRegistryToken t = c == null ? null : AuthenticationTokens.convert(DockerRegistryToken.class, c);
    if (t == null) {
        throw new IllegalArgumentException("Invalid Credential ID " + registry.getCredentialsId());
    }
    final String token = t.getToken();
    // What docker-commons claim to be a "token" is actually configuration storage
    // see https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/cli/config/configfile/file.go#L214
    // i.e base64 encoded username : password
    final String decode = new String(Base64.decodeBase64(token), StandardCharsets.UTF_8);
    int i = decode.indexOf(':');
    if (i > 0) {
        String username = decode.substring(0, i);
        auth.withUsername(username);
    }
    auth.withPassword(decode.substring(i+1));
    if (registry.getUrl() != null) {
        auth.withRegistryAddress(registry.getUrl());
    }
    return auth;
}
 
Example #9
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static void setRegistryAuthentication(PushImageCmd cmd, DockerRegistryEndpoint registry, ItemGroup context) {
    if (registry != null && registry.getCredentialsId() != null) {
        AuthConfig auth = getAuthConfig(registry, context);
        cmd.withAuthConfig(auth);
    }
}
 
Example #10
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static void setRegistryAuthentication(PullImageCmd cmd, DockerRegistryEndpoint registry, ItemGroup context) {
    if (registry != null && registry.getCredentialsId() != null) {
        AuthConfig auth = getAuthConfig(registry, context);
        cmd.withAuthConfig(auth);
    }
}
 
Example #11
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 #12
Source File: DockerSwarmAgentTemplate.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillPullCredentialsIdItems(@AncestorInPath Item item,
        @QueryParameter String pullCredentialsId) {
    if (item == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)
            || item != null && !item.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel();
    }

    final DockerRegistryEndpoint.DescriptorImpl descriptor = (DockerRegistryEndpoint.DescriptorImpl) Jenkins
            .getInstance().getDescriptorOrDie(DockerRegistryEndpoint.class);
    return descriptor.doFillCredentialsIdItems(item);
}
 
Example #13
Source File: SampleDockerBuilder.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public SampleDockerBuilder(DockerServerEndpoint server, DockerRegistryEndpoint registry) {
    if (server == null || registry == null) {
        throw new IllegalArgumentException();
    }
    this.server = server;
    this.registry = registry;
}
 
Example #14
Source File: FolderConfig.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Override
public String getRegistryCredentialsId(@Nullable Run run) {
    if (run != null) {
        Job job = run.getParent();
        ItemGroup parent = job.getParent();
        while (parent != null) {

            if (parent instanceof AbstractFolder) {
                AbstractFolder folder = (AbstractFolder) parent;
                FolderConfig config = (FolderConfig) folder.getProperties().get(FolderConfig.class);
                if (config != null) {
                    DockerRegistryEndpoint registry = config.getRegistry();
                    if (registry != null && !StringUtils.isBlank(registry.getCredentialsId())) {
                        return registry.getCredentialsId();
                    }
                }
            }

            if (parent instanceof Item) {
                parent = ((Item) parent).getParent();
            } else {
                parent = null;
            }
        }
    }
    return null;
}
 
Example #15
Source File: FolderConfig.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Override
public String getRegistryUrl(@Nullable Run run) {
    if (run != null) {
        Job job = run.getParent();
        ItemGroup parent = job.getParent();
        while (parent != null) {

            if (parent instanceof AbstractFolder) {
                AbstractFolder folder = (AbstractFolder) parent;
                FolderConfig config = (FolderConfig) folder.getProperties().get(FolderConfig.class);
                if (config != null) {
                    DockerRegistryEndpoint registry = config.getRegistry();
                    if (registry != null && !StringUtils.isBlank(registry.getUrl())) {
                        return registry.getUrl();
                    }
                }
            }

            if (parent instanceof Item) {
                parent = ((Item) parent).getParent();
            } else {
                parent = null;
            }
        }
    }
    return null;
}
 
Example #16
Source File: RegistryEndpointStep.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Override public Step newInstance(Map<String, Object> arguments) throws Exception {
    arguments = new HashMap<>(arguments);
    if (arguments.containsKey("url") || arguments.containsKey("credentialsId")) {
        if (arguments.containsKey("registry")) {
            throw new IllegalArgumentException("cannot mix url/credentialsId with registry");
        }
        arguments.put("registry", new DockerRegistryEndpoint((String) arguments.remove("url"), (String) arguments.remove("credentialsId")));
    } else if (!arguments.containsKey("registry")) {
        throw new IllegalArgumentException("must specify url/credentialsId (or registry)");
    }
    return super.newInstance(arguments);
}
 
Example #17
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void plainSystemConfig() throws Exception {
    GlobalConfig.get().setDockerLabel("config_docker");
    GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .logContains("Docker Label is: config_docker",
                    "Registry URL is: https://docker.registry",
                    "Registry Creds ID is: " + globalCred.getId()).go();
}
 
Example #18
Source File: DockerTemplate.java    From docker-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return dockerTemplateBase.getRegistry();
}
 
Example #19
Source File: RegistryEndpointStep.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@DataBoundConstructor public RegistryEndpointStep(@Nonnull DockerRegistryEndpoint registry) {
    assert registry != null;
    this.registry = registry;
}
 
Example #20
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 4 votes vote down vote up
private ListBoxModel doFillRegistryCredentialsIdItems(@AncestorInPath Item item) {
    final DockerRegistryEndpoint.DescriptorImpl descriptor =
            (DockerRegistryEndpoint.DescriptorImpl)
            Jenkins.getInstance().getDescriptorOrDie(DockerRegistryEndpoint.class);
    return descriptor.doFillCredentialsIdItems(item);
}
 
Example #21
Source File: RegistryEndpointStep.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return registry;
}
 
Example #22
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 4 votes vote down vote up
@CheckForNull
public DockerRegistryEndpoint getFromRegistry() {
    return fromRegistry;
}
 
Example #23
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 4 votes vote down vote up
public ListBoxModel doFillPullCredentialsIdItems(@AncestorInPath Item context) {
    final DockerRegistryEndpoint.DescriptorImpl descriptor =
            (DockerRegistryEndpoint.DescriptorImpl)
                    Jenkins.getInstance().getDescriptorOrDie(DockerRegistryEndpoint.class);
    return descriptor.doFillCredentialsIdItems(context);
}
 
Example #24
Source File: FolderConfig.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return registry;
}
 
Example #25
Source File: DockerJobProperty.java    From docker-plugin with MIT License 4 votes vote down vote up
@DataBoundSetter
public void setRegistry(DockerRegistryEndpoint registry) {
    this.pushOnSuccess = true;
    this.registry = registry;
}
 
Example #26
Source File: DockerJobProperty.java    From docker-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return registry;
}
 
Example #27
Source File: FolderConfig.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@DataBoundSetter
public void setRegistry(DockerRegistryEndpoint registry) {
    this.registry = registry;
}
 
Example #28
Source File: GlobalConfig.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return registry;
}
 
Example #29
Source File: GlobalConfig.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@DataBoundSetter
public void setRegistry(DockerRegistryEndpoint registry) {
    this.registry = registry;
}
 
Example #30
Source File: SampleDockerBuilder.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
public DockerRegistryEndpoint getRegistry() {
    return registry;
}