Search in sources :

Example 61 with User

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

the class ImportMojo method ensureExternalGitSecretsAreSetupFor.

protected void ensureExternalGitSecretsAreSetupFor(KubernetesClient kubernetes, String namespace, String gitRemoteURL) throws MojoExecutionException {
    String secretNamespace = getSecretNamespace();
    ensureNamespaceExists(kubernetes, secretNamespace);
    ConfigMap configMap = getSecretGitConfigMap(kubernetes, namespace, secretNamespace);
    String host = GitUtils.getGitHostName(gitRemoteURL);
    if (host == null) {
        host = "default";
    }
    String protocol = GitUtils.getGitProtocol(gitRemoteURL);
    boolean isSsh = Objects.equal("ssh", protocol);
    String currentSecretName = configMap.getData().get(host);
    if (currentSecretName == null) {
        currentSecretName = createGitSecretName(namespace, host);
    }
    Secret secret = findOrCreateGitSecret(kubernetes, currentSecretName, host);
    if (isSsh) {
        // lets see if we need to import ssh keys
        Map<String, String> secretData = secret.getData();
        if (secretData == null) {
            secretData = new HashMap<>();
        }
        if (!secretData.containsKey(PROPERTY_PRIVATE_KEY) || !secretData.containsKey(PROPERTY_PUBLIC_KEY)) {
            String answer = null;
            try {
                answer = prompter.prompt("Would you like to import your local SSH public/private key pair from your ~/.ssh folder? (Y/n)");
            } catch (PrompterException e) {
                log.warn("Failed to get prompt: %s", e);
            }
            if (answer != null && answer.trim().isEmpty() || answer.trim().toUpperCase().startsWith("Y")) {
                chooseSshKeyPairs(secretData, host);
                secret.setData(secretData);
            }
        }
    } else {
        // if empty or retrying lets re-enter the user/pwd
        getGogsSecretField(kubernetes, secret, host, "username");
        getGogsSecretField(kubernetes, secret, host, "password");
    }
    createOrUpdateSecret(kubernetes, secret);
    updateSecretGitConfigMap(kubernetes, secretNamespace, configMap, host, currentSecretName);
}
Also used : Secret(io.fabric8.kubernetes.api.model.Secret) PrompterException(org.codehaus.plexus.components.interactivity.PrompterException) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap)

Example 62 with User

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

the class KubernetesAccountValidator method validateKubeconfig.

private void validateKubeconfig(ConfigProblemSetBuilder psBuilder, KubernetesAccount account) {
    io.fabric8.kubernetes.api.model.Config kubeconfig;
    String context = account.getContext();
    String kubeconfigFile = account.getKubeconfigFile();
    String cluster = account.getCluster();
    String user = account.getUser();
    List<String> namespaces = account.getNamespaces();
    List<String> omitNamespaces = account.getOmitNamespaces();
    // This indicates if a first pass at the config looks OK. If we don't see any serious problems, we'll do one last check
    // against the requested kubernetes cluster to ensure that we can run spinnaker.
    boolean smoketest = true;
    boolean namespacesProvided = namespaces != null && !namespaces.isEmpty();
    boolean omitNamespacesProvided = omitNamespaces != null && !omitNamespaces.isEmpty();
    if (namespacesProvided && omitNamespacesProvided) {
        psBuilder.addProblem(ERROR, "At most one of \"namespaces\" and \"omitNamespaces\" can be supplied.");
        smoketest = false;
    }
    // TODO(lwander) find a good resource / list of resources for generating kubeconfig files to link to here.
    try {
        if (ValidatingFileReader.contents(psBuilder, kubeconfigFile) == null) {
            return;
        }
        File kubeconfigFileOpen = new File(kubeconfigFile);
        kubeconfig = KubeConfigUtils.parseConfig(kubeconfigFileOpen);
    } catch (IOException e) {
        psBuilder.addProblem(ERROR, e.getMessage());
        return;
    }
    System.out.println(context);
    if (context != null && !context.isEmpty()) {
        Optional<NamedContext> namedContext = kubeconfig.getContexts().stream().filter(c -> c.getName().equals(context)).findFirst();
        if (!namedContext.isPresent()) {
            psBuilder.addProblem(ERROR, "Context \"" + context + "\" not found in kubeconfig \"" + kubeconfigFile + "\".", "context").setRemediation("Either add this context to your kubeconfig, rely on the default context, or pick another kubeconfig file.");
            smoketest = false;
        }
    } else {
        String currentContext = kubeconfig.getCurrentContext();
        if (StringUtils.isEmpty(currentContext)) {
            psBuilder.addProblem(ERROR, "You have not specified a Kubernetes context, and your kubeconfig \"" + kubeconfigFile + "\" has no current-context.", "context").setRemediation("Either specify a context in your halconfig, or set a current-context in your kubeconfig.");
            smoketest = false;
        } else {
            psBuilder.addProblem(WARNING, "You have not specified a Kubernetes context in your halconfig, Spinnaker will use \"" + currentContext + "\" instead.", "context").setRemediation("We recommend explicitly setting a context in your halconfig, to ensure changes to your kubeconfig won't break your deployment.");
        }
    }
    if (smoketest) {
        Config config = KubernetesConfigParser.parse(kubeconfigFile, context, cluster, user, namespaces, false);
        try {
            KubernetesClient client = new DefaultKubernetesClient(config);
            client.namespaces().list();
        } catch (Exception e) {
            ConfigProblemBuilder pb = psBuilder.addProblem(ERROR, "Unable to communicate with your Kubernetes cluster: " + e.getMessage() + ".");
            if (e.getMessage().contains("Token may have expired")) {
                pb.setRemediation("If you downloaded these keys with gcloud, it's possible they are in the wrong format. To fix this, run \n\n" + "gcloud config set container/use_client_certificate true\n\ngcloud container clusters get-credentials $CLUSTERNAME");
            } else {
                pb.setRemediation("Unable to authenticate with your Kubernetes cluster. Try using kubectl to verify your credentials.");
            }
        }
    }
}
Also used : KubernetesAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.kubernetes.KubernetesAccount) ConfigProblemSetBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemSetBuilder) StringUtils(org.apache.commons.lang3.StringUtils) DaemonTaskHandler(com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTaskHandler) WARNING(com.netflix.spinnaker.halyard.core.problem.v1.Problem.Severity.WARNING) CollectionUtils(org.apache.commons.collections.CollectionUtils) JobExecutor(com.netflix.spinnaker.halyard.core.job.v1.JobExecutor) KubernetesConfigParser(com.netflix.spinnaker.clouddriver.kubernetes.v1.security.KubernetesConfigParser) Validator(com.netflix.spinnaker.halyard.config.model.v1.node.Validator) KubeConfigUtils(io.fabric8.kubernetes.client.internal.KubeConfigUtils) NamedContext(io.fabric8.kubernetes.api.model.NamedContext) Provider(com.netflix.spinnaker.halyard.config.model.v1.node.Provider) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) DockerRegistryReference(com.netflix.spinnaker.halyard.config.model.v1.providers.containers.DockerRegistryReference) JobRequest(com.netflix.spinnaker.halyard.core.job.v1.JobRequest) ERROR(com.netflix.spinnaker.halyard.core.problem.v1.Problem.Severity.ERROR) IOException(java.io.IOException) DeploymentConfiguration(com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentConfiguration) Collectors(java.util.stream.Collectors) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) ConfigProblemBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemBuilder) Config(io.fabric8.kubernetes.client.Config) Component(org.springframework.stereotype.Component) List(java.util.List) FATAL(com.netflix.spinnaker.halyard.core.problem.v1.Problem.Severity.FATAL) DockerRegistryReferenceValidation.validateDockerRegistries(com.netflix.spinnaker.halyard.config.validate.v1.providers.dockerRegistry.DockerRegistryReferenceValidation.validateDockerRegistries) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Optional(java.util.Optional) ValidatingFileReader(com.netflix.spinnaker.halyard.config.validate.v1.util.ValidatingFileReader) DaemonTaskInterrupted(com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTaskInterrupted) Node(com.netflix.spinnaker.halyard.config.model.v1.node.Node) JobStatus(com.netflix.spinnaker.halyard.core.job.v1.JobStatus) Collections(java.util.Collections) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) NamedContext(io.fabric8.kubernetes.api.model.NamedContext) Config(io.fabric8.kubernetes.client.Config) IOException(java.io.IOException) IOException(java.io.IOException) ConfigProblemBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemBuilder) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) File(java.io.File)

Example 63 with User

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

the class DevOpsConnector method loadConfigFile.

protected void loadConfigFile() {
    if (projectConfig == null) {
        GitRepoClient gitRepo = getGitRepoClient();
        boolean hasLocalConfig = false;
        if (basedir != null && basedir.isDirectory()) {
            projectConfig = ProjectConfigs.loadFromFolder(basedir);
            if (!projectConfig.isEmpty() || ProjectConfigs.hasConfigFile(basedir)) {
                hasLocalConfig = true;
            }
        }
        if (!hasLocalConfig && tryLoadConfigFileFromRemoteGit && Strings.isNotBlank(repoName) && gitRepo != null) {
            try {
                InputStream input = gitRepo.getRawFile(username, repoName, branch, ProjectConfigs.FILE_NAME);
                if (input != null) {
                    try {
                        getLog().info("Parsing " + ProjectConfigs.FILE_NAME + " from the git repo " + repoName + " user " + username + " in branch " + branch);
                        projectConfig = ProjectConfigs.parseProjectConfig(input);
                    } catch (IOException e) {
                        getLog().warn("Failed to parse " + ProjectConfigs.FILE_NAME + " from the repo " + repoName + " for user " + username + " branch: " + branch + ". " + e, e);
                    }
                }
            } catch (Exception e) {
                getLog().warn("Failed to load " + ProjectConfigs.FILE_NAME + " from the repo " + repoName + " for user " + username + " branch: " + branch + ". " + e, e);
            }
        }
    }
    if (projectConfig != null) {
        String chatRoom = projectConfig.getChatRoom();
        if (Strings.isNotBlank(chatRoom)) {
            getLog().info("Found chat room: " + chatRoom);
            letschatRoomExpression = chatRoom;
        }
        String issueProjectName = projectConfig.getIssueProjectName();
        if (Strings.isNotBlank(issueProjectName)) {
            taigaProjectName = issueProjectName;
        }
    } else {
        getLog().info("No fabric8.yml file found for " + basedir);
    }
    if (Strings.isNullOrBlank(gitUrl)) {
        try {
            gitUrl = GitHelpers.extractGitUrl(basedir);
        } catch (IOException e) {
            getLog().warn("Could not load git URL from directory: " + e, e);
        }
    }
    if (Strings.isNullOrBlank(taigaProjectName)) {
        taigaProjectName = repoName;
    }
    if (Strings.isNullOrBlank(taigaProjectSlug)) {
        // TODO should we upper case it or anything?
        taigaProjectSlug = taigaProjectName;
    }
}
Also used : GitRepoClient(io.fabric8.repo.git.GitRepoClient) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) 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)

Example 64 with User

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

the class ConfigFileParseTest method testParseConfig.

@Test
public void testParseConfig() throws Exception {
    setKubernetesConfigFileProperty();
    File file = getKubernetesConfigFile();
    assertThat(file).isFile().exists();
    Config config = Configs.parseConfigs();
    assertThat(config).isNotNull();
    String currentContextName = config.getCurrentContext();
    assertThat(currentContextName).describedAs("currentContext").isEqualTo("default/localhost:8443/admin");
    System.out.println("Found current context name: " + currentContextName);
    Context context = Configs.getCurrentContext(config);
    assertThat(context).describedAs("currentContext").isNotNull();
    assertThat(context.getNamespace()).describedAs("namespace").isEqualTo("jimmi-does-rock");
    assertThat(context.getUser()).describedAs("user").isEqualTo("admin/localhost:8443");
    assertThat(context.getCluster()).describedAs("cluster").isEqualTo("172-28-128-4:8443");
    String token = Configs.getUserToken(config, context);
    assertThat(token).describedAs("token").isEqualTo("ExpectedToken");
    System.out.println("User " + context.getUser() + " has token: " + token);
}
Also used : Context(io.fabric8.kubernetes.api.model.Context) Config(io.fabric8.kubernetes.api.model.Config) Configs.getKubernetesConfigFile(io.fabric8.kubernetes.api.extensions.Configs.getKubernetesConfigFile) File(java.io.File) Test(org.junit.Test)

Example 65 with User

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

the class UserHandlerTest method successfulWhoAmI.

@Test
public void successfulWhoAmI() {
    openShiftServer.expect().get().withPath("/oapi/v1/users/~").andReturn(200, new UserBuilder().withFullName("Test User").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()).isNotEmpty().hasValue("Test User");
}
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)

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