Search in sources :

Example 21 with User

use of io.fabric8.openshift.api.model.User in project strimzi by strimzi.

the class KafkaConnectClusterTest method testGenerateService.

@Test
public void testGenerateService() {
    Service svc = kc.generateService();
    assertEquals("ClusterIP", svc.getSpec().getType());
    Map<String, String> expectedLabels = ResourceUtils.labels(Labels.STRIMZI_CLUSTER_LABEL, this.cluster, Labels.STRIMZI_TYPE_LABEL, "kafka-connect", "my-user-label", "cromulent", Labels.STRIMZI_NAME_LABEL, kc.kafkaConnectClusterName(cluster));
    assertEquals(expectedLabels, svc.getMetadata().getLabels());
    assertEquals(expectedLabels, svc.getSpec().getSelector());
    assertEquals(1, svc.getSpec().getPorts().size());
    assertEquals(new Integer(KafkaConnectCluster.REST_API_PORT), svc.getSpec().getPorts().get(0).getPort());
    assertEquals(KafkaConnectCluster.REST_API_PORT_NAME, svc.getSpec().getPorts().get(0).getName());
    assertEquals("TCP", svc.getSpec().getPorts().get(0).getProtocol());
}
Also used : Service(io.fabric8.kubernetes.api.model.Service) Test(org.junit.Test)

Example 22 with User

use of io.fabric8.openshift.api.model.User in project syndesis by syndesisio.

the class UserHandlerTest method successfulWhoAmIWithoutFullName.

@Test
public void successfulWhoAmIWithoutFullName() {
    openShiftServer.expect().get().withPath("/oapi/v1/users/~").andReturn(200, new UserBuilder().withNewMetadata().withName("testuser").and().build()).once();
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("testuser", "doesn'tmatter"));
    UserHandler userHandler = new UserHandler(null, new OpenShiftServiceImpl(openShiftServer.getOpenshiftClient(), null));
    User user = userHandler.whoAmI();
    Assertions.assertThat(user).isNotNull();
    Assertions.assertThat(user.getUsername()).isEqualTo("testuser");
    Assertions.assertThat(user.getFullName()).isEmpty();
}
Also used : User(io.syndesis.common.model.user.User) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) OpenShiftServiceImpl(io.syndesis.server.openshift.OpenShiftServiceImpl) UserBuilder(io.fabric8.openshift.api.model.UserBuilder) Test(org.junit.Test)

Example 23 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by fabric8io.

the class DevOpsConnector method execute.

/**
 * For a given project this operation will try to update the associated DevOps resources
 *
 * @throws Exception
 */
public void execute() throws Exception {
    loadConfigFile();
    KubernetesClient kubernetes = getKubernetes();
    String name = projectName;
    if (Strings.isNullOrBlank(name)) {
        if (projectConfig != null) {
            name = projectConfig.getBuildName();
        }
        if (Strings.isNullOrBlank(name)) {
            name = jenkinsJob;
        }
        if (Strings.isNullOrBlank(name)) {
            name = ProjectRepositories.createBuildName(username, repoName);
            if (projectConfig != null) {
                projectConfig.setBuildName(name);
            }
        }
    }
    if (Strings.isNullOrBlank(projectName)) {
        projectName = name;
    }
    Map<String, String> labels = new HashMap<>();
    labels.put("user", username);
    labels.put("repo", repoName);
    getLog().info("build name " + name);
    taiga = null;
    taigaProject = null;
    try {
        taiga = createTaiga();
        taigaProject = createTaigaProject(taiga);
    } catch (Exception e) {
        getLog().error("Failed to load or lazily create the Taiga project: " + e, e);
    }
    getLog().info("taiga " + taiga);
    LetsChatClient letschat = null;
    try {
        letschat = createLetsChat();
    } catch (Exception e) {
        getLog().error("Failed to load or lazily create the LetsChat client: " + e, e);
    }
    getLog().info("letschat " + letschat);
    /*
         * Create Gerrit Git to if isGerritReview is enabled
         */
    if (projectConfig != null && projectConfig.hasCodeReview()) {
        try {
            createGerritRepo(repoName, gerritUser, gerritPwd, gerritGitInitialCommit, gerritGitRepoDesription);
        } catch (Exception e) {
            getLog().error("Failed to create GerritGit repo : " + e, e);
        }
    }
    Map<String, String> annotations = new HashMap<>();
    jenkinsJobUrl = null;
    String jenkinsUrl = null;
    try {
        jenkinsUrl = getJenkinsServiceUrl(true);
        if (Strings.isNotBlank(jenkinsUrl)) {
            if (Strings.isNotBlank(jenkinsMonitorView)) {
                String url = URLUtils.pathJoin(jenkinsUrl, "/view", jenkinsMonitorView);
                annotationLink(annotations, "fabric8.link.jenkins.monitor/", url, "Monitor");
            }
            if (Strings.isNotBlank(jenkinsPipelineView)) {
                String url = URLUtils.pathJoin(jenkinsUrl, "/view", jenkinsPipelineView);
                annotationLink(annotations, "fabric8.link.jenkins.pipeline/", url, "Pipeline");
            }
            if (Strings.isNotBlank(name)) {
                jenkinsJobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name);
                annotationLink(annotations, "fabric8.link.jenkins.job/", jenkinsJobUrl, "Job");
            }
        }
    } catch (Exception e) {
        getLog().warn("Could not find the Jenkins URL!: " + e, e);
    }
    getLog().info("jenkins " + jenkinsUrl);
    if (!annotationLink(annotations, "fabric8.link.issues/", issueTrackerUrl, issueTrackerLabel)) {
        String taigaLink = getProjectPageLink(taiga, taigaProject, this.taigaProjectLinkPage);
        annotationLink(annotations, "fabric8.link.taiga/", taigaLink, taigaProjectLinkLabel);
    }
    if (!annotationLink(annotations, "fabric8.link.team/", teamUrl, teamLabel)) {
        String taigaTeamLink = getProjectPageLink(taiga, taigaProject, this.taigaTeamLinkPage);
        annotationLink(annotations, "fabric8.link.taiga.team/", taigaTeamLink, taigaTeamLinkLabel);
    }
    annotationLink(annotations, "fabric8.link.releases/", releasesUrl, releasesLabel);
    String chatRoomLink = getChatRoomLink(letschat);
    annotationLink(annotations, "fabric8.link.letschat.room/", chatRoomLink, letschatRoomLinkLabel);
    annotationLink(annotations, "fabric8.link.repository.browse/", repositoryBrowseLink, repositoryBrowseLabel);
    ProjectConfigs.defaultEnvironments(projectConfig, namespace);
    String consoleUrl = getServiceUrl(ServiceNames.FABRIC8_CONSOLE, namespace, fabric8ConsoleNamespace);
    if (projectConfig != null) {
        Map<String, String> environments = projectConfig.getEnvironments();
        updateEnvironmentConfigMap(environments, kubernetes, annotations, consoleUrl);
    }
    addLink("Git", getGitUrl());
    Controller controller = createController();
    OpenShiftClient openShiftClient = controller.getOpenShiftClientOrJenkinshift();
    BuildConfig buildConfig = null;
    if (openShiftClient != null) {
        try {
            buildConfig = openShiftClient.buildConfigs().withName(projectName).get();
        } catch (Exception e) {
            log.error("Failed to load build config for " + namespace + "/" + projectName + ". " + e, e);
        }
        log.info("Loaded build config for " + namespace + "/" + projectName + " " + buildConfig);
    }
    // if we have loaded a build config then lets assume its correct!
    boolean foundExistingGitUrl = false;
    if (buildConfig != null) {
        BuildConfigSpec spec = buildConfig.getSpec();
        if (spec != null) {
            BuildSource source = spec.getSource();
            if (source != null) {
                GitBuildSource git = source.getGit();
                if (git != null) {
                    gitUrl = git.getUri();
                    log.info("Loaded existing BuildConfig git url: " + gitUrl);
                    foundExistingGitUrl = true;
                }
                LocalObjectReference sourceSecret = source.getSourceSecret();
                if (sourceSecret != null) {
                    gitSourceSecretName = sourceSecret.getName();
                }
            }
        }
        if (!foundExistingGitUrl) {
            log.warn("Could not find a git url in the loaded BuildConfig: " + buildConfig);
        }
        log.info("Loaded gitSourceSecretName: " + gitSourceSecretName);
    }
    log.info("gitUrl is: " + gitUrl);
    if (buildConfig == null) {
        buildConfig = new BuildConfig();
    }
    ObjectMeta metadata = getOrCreateMetadata(buildConfig);
    metadata.setName(projectName);
    metadata.setLabels(labels);
    putAnnotations(metadata, annotations);
    Map<String, String> currentAnnotations = metadata.getAnnotations();
    if (!currentAnnotations.containsKey(Annotations.Builds.GIT_CLONE_URL)) {
        currentAnnotations.put(Annotations.Builds.GIT_CLONE_URL, gitUrl);
    }
    String localGitUrl = getLocalGitUrl();
    if (!currentAnnotations.containsKey(Annotations.Builds.LOCAL_GIT_CLONE_URL) && Strings.isNotBlank(localGitUrl)) {
        currentAnnotations.put(Annotations.Builds.LOCAL_GIT_CLONE_URL, localGitUrl);
    }
    // lets switch to the local git URL to avoid DNS issues in forge or jenkins
    if (Strings.isNotBlank(localGitUrl)) {
        gitUrl = localGitUrl;
    }
    Builds.configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, buildImageStream, buildImageTag, s2iCustomBuilderImage, secret, jenkinsUrl);
    try {
        getLog().info("About to apply build config: " + new JSONObject(KubernetesHelper.toJson(buildConfig)).toString(4));
        controller.applyBuildConfig(buildConfig, "maven");
        getLog().info("Created build configuration for " + name + " in namespace: " + controller.getNamespace() + " at " + kubernetes.getMasterUrl());
    } catch (Exception e) {
        getLog().error("Failed to create BuildConfig for " + KubernetesHelper.toJson(buildConfig) + ". " + e, e);
    }
    this.jenkinsJobName = name;
    if (isRegisterWebHooks()) {
        registerWebHooks();
        getLog().info("webhooks done");
    }
    if (modifiedConfig) {
        if (basedir == null) {
            getLog().error("Could not save updated " + ProjectConfigs.FILE_NAME + " due to missing basedir");
        } else {
            try {
                ProjectConfigs.saveToFolder(basedir, projectConfig, true);
                getLog().info("Updated " + ProjectConfigs.FILE_NAME);
            } catch (IOException e) {
                getLog().error("Could not save updated " + ProjectConfigs.FILE_NAME + ": " + e, e);
            }
        }
    }
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) HashMap(java.util.HashMap) IOException(java.io.IOException) Controller(io.fabric8.kubernetes.api.Controller) GitBuildSource(io.fabric8.openshift.api.model.GitBuildSource) SAXException(org.xml.sax.SAXException) WebApplicationException(javax.ws.rs.WebApplicationException) AuthenticationException(org.apache.http.auth.AuthenticationException) ConnectException(java.net.ConnectException) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BuildSource(io.fabric8.openshift.api.model.BuildSource) GitBuildSource(io.fabric8.openshift.api.model.GitBuildSource) JSONObject(org.json.JSONObject) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) LocalObjectReference(io.fabric8.kubernetes.api.model.LocalObjectReference) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) LetsChatClient(io.fabric8.letschat.LetsChatClient) BuildConfigSpec(io.fabric8.openshift.api.model.BuildConfigSpec)

Example 24 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by fabric8io.

the class WebHooks method createGogsWebhook.

/**
 * Creates a webook in the given gogs repo for the user and password if the webhook does not already exist
 */
public static boolean createGogsWebhook(GitRepoClient repoClient, Logger log, String gogsUser, String repoName, String webhookUrl, String webhookSecret) throws JsonProcessingException {
    if (repoClient == null) {
        log.info("Cannot create Gogs webhooks as no Gogs service could be found or created");
        return false;
    }
    String gogsAddress = repoClient.getAddress();
    log.info("Querying webhooks in gogs at address: " + gogsAddress + " for user " + gogsUser + " repoName: " + repoName);
    RepositoryDTO repository = repoClient.getRepository(gogsUser, repoName);
    if (repository == null) {
        log.info("No repository found for user: " + gogsUser + " repo: " + repoName + " so cannot create any web hooks");
    // return false;
    }
    List<WebHookDTO> webhooks = repoClient.getWebhooks(gogsUser, repoName);
    for (WebHookDTO webhook : webhooks) {
        String url = null;
        WebhookConfig config = webhook.getConfig();
        if (config != null) {
            url = config.getUrl();
            if (Objects.equal(webhookUrl, url)) {
                log.info("Already has webhook for: " + url + " so not creating again");
                return false;
            }
            log.info("Ignoring webhook " + url + " from: " + toJson(config));
        }
    }
    CreateWebhookDTO createWebhook = new CreateWebhookDTO();
    createWebhook.setType("gogs");
    WebhookConfig config = createWebhook.getConfig();
    config.setUrl(webhookUrl);
    config.setSecret(webhookSecret);
    WebHookDTO webhook = repoClient.createWebhook(gogsUser, repoName, createWebhook);
    if (log.isDebugEnabled()) {
        log.debug("Got created web hook: " + toJson(webhook));
    }
    log.info("Created webhook for " + webhookUrl + " for user: " + gogsUser + " repoName: " + repoName + " on gogs URL: " + gogsAddress);
    return true;
}
Also used : WebhookConfig(io.fabric8.repo.git.WebhookConfig) WebHookDTO(io.fabric8.repo.git.WebHookDTO) RepositoryDTO(io.fabric8.repo.git.RepositoryDTO) CreateWebhookDTO(io.fabric8.repo.git.CreateWebhookDTO)

Example 25 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by fabric8io.

the class BuildConfigHelper method importNewGitProject.

public static CreateGitProjectResults importNewGitProject(KubernetesClient kubernetesClient, UserDetails userDetails, File basedir, String namespace, String projectName, String origin, String message, boolean apply, boolean useLocalGitAddress) throws GitAPIException, JsonProcessingException {
    GitUtils.disableSslCertificateChecks();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);
    Git git = initCommand.call();
    LOG.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());
    PersonIdent personIdent = userDetails.createPersonIdent();
    String user = userDetails.getUser();
    String address = userDetails.getAddress();
    String internalAddress = userDetails.getInternalAddress();
    String branch = userDetails.getBranch();
    // lets create the repository
    GitRepoClient repoClient = userDetails.createRepoClient();
    CreateRepositoryDTO createRepository = new CreateRepositoryDTO();
    createRepository.setName(projectName);
    String fullName = null;
    RepositoryDTO repository = repoClient.createRepository(createRepository);
    if (repository != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Got repository: " + toJson(repository));
        }
        fullName = repository.getFullName();
    }
    if (Strings.isNullOrBlank(fullName)) {
        fullName = user + "/" + projectName;
    }
    String htmlUrl = URLUtils.pathJoin(resolveToRoot(address), user, projectName);
    String localCloneUrl = URLUtils.pathJoin(resolveToRoot(internalAddress), user, projectName + ".git");
    String cloneUrl = htmlUrl + ".git";
    String defaultCloneUrl = cloneUrl;
    // lets default to using the local git clone URL
    if (useLocalGitAddress && Strings.isNotBlank(internalAddress)) {
        defaultCloneUrl = localCloneUrl;
    }
    // now lets import the code and publish
    GitUtils.configureBranch(git, branch, origin, defaultCloneUrl);
    GitUtils.addDummyFileToEmptyFolders(basedir);
    LOG.info("About to git commit and push to: " + defaultCloneUrl + " and remote name " + origin);
    GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true);
    Map<String, String> annotations = new HashMap<>();
    annotations.put(Annotations.Builds.GIT_CLONE_URL, cloneUrl);
    annotations.put(Annotations.Builds.LOCAL_GIT_CLONE_URL, localCloneUrl);
    BuildConfig buildConfig;
    if (apply) {
        buildConfig = createAndApplyBuildConfig(kubernetesClient, namespace, projectName, defaultCloneUrl, annotations);
    } else {
        buildConfig = createBuildConfig(kubernetesClient, namespace, projectName, defaultCloneUrl, annotations);
    }
    return new CreateGitProjectResults(buildConfig, fullName, htmlUrl, localCloneUrl, cloneUrl);
}
Also used : Git(org.eclipse.jgit.api.Git) CreateRepositoryDTO(io.fabric8.repo.git.CreateRepositoryDTO) PersonIdent(org.eclipse.jgit.lib.PersonIdent) HashMap(java.util.HashMap) InitCommand(org.eclipse.jgit.api.InitCommand) GitRepoClient(io.fabric8.repo.git.GitRepoClient) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) RepositoryDTO(io.fabric8.repo.git.RepositoryDTO) CreateRepositoryDTO(io.fabric8.repo.git.CreateRepositoryDTO)

Aggregations

Test (org.junit.Test)31 File (java.io.File)19 IOException (java.io.IOException)17 HashMap (java.util.HashMap)16 Git (org.eclipse.jgit.api.Git)12 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)10 Map (java.util.Map)10 LinkedList (java.util.LinkedList)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 ObjectId (org.eclipse.jgit.lib.ObjectId)7 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)6 ArrayList (java.util.ArrayList)6 PatchException (io.fabric8.patch.management.PatchException)5 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)5 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)4 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)4 URL (java.net.URL)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)4 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)3