func whoAmI(clientConfig *restclient.Config) (*api.User, error) { client, err := client.New(clientConfig) me, err := client.Users().Get("~") // if we're talking to kube (or likely talking to kube), if kerrors.IsNotFound(err) { switch { case len(clientConfig.BearerToken) > 0: // the user has already been willing to provide the token on the CLI, so they probably // don't mind using it again if they switch to and from this user return &api.User{ObjectMeta: kapi.ObjectMeta{Name: clientConfig.BearerToken}}, nil case len(clientConfig.Username) > 0: return &api.User{ObjectMeta: kapi.ObjectMeta{Name: clientConfig.Username}}, nil } } if err != nil { return nil, err } return me, nil }
func newBuilderConfigFromEnvironment() (*builderConfig, error) { cfg := &builderConfig{} var err error // build (BUILD) buildStr := os.Getenv("BUILD") glog.V(4).Infof("$BUILD env var is %s \n", buildStr) cfg.build = &api.Build{} if err = latest.Codec.DecodeInto([]byte(buildStr), cfg.build); err != nil { return nil, fmt.Errorf("unable to parse build: %v", err) } // sourceSecretsDir (SOURCE_SECRET_PATH) cfg.sourceSecretDir = os.Getenv("SOURCE_SECRET_PATH") // dockerClient and dockerEndpoint (DOCKER_HOST) // usually not set, defaults to docker socket cfg.dockerClient, cfg.dockerEndpoint, err = dockerutil.NewHelper().GetClient() if err != nil { return nil, fmt.Errorf("error obtaining docker client: %v", err) } // buildsClient (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT) clientConfig, err := kclient.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to get client config: %v", err) } osClient, err := client.New(clientConfig) if err != nil { return nil, fmt.Errorf("error obtaining OpenShift client: %v", err) } cfg.buildsClient = osClient.Builds(cfg.build.Namespace) return cfg, nil }
func TestUnprivilegedNewProject(t *testing.T) { _, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig := *clusterAdminClientConfig valerieClientConfig.Username = "" valerieClientConfig.Password = "" valerieClientConfig.BearerToken = "" valerieClientConfig.CertFile = "" valerieClientConfig.KeyFile = "" valerieClientConfig.CertData = nil valerieClientConfig.KeyData = nil accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!") if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig.BearerToken = accessToken valerieOpenshiftClient, err := client.New(&valerieClientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } // confirm that we have access to request the project allowed, err := valerieOpenshiftClient.ProjectRequests().List(labels.Everything(), fields.Everything()) if err != nil { t.Fatalf("unexpected error: %v", err) } if allowed.Status != unversioned.StatusSuccess { t.Fatalf("expected %v, got %v", unversioned.StatusSuccess, allowed.Status) } requestProject := oc.NewProjectOptions{ ProjectName: "new-project", DisplayName: "display name here", Description: "the special description", Client: valerieOpenshiftClient, Out: ioutil.Discard, } if err := requestProject.Run(); err != nil { t.Fatalf("unexpected error: %v", err) } waitForProject(t, valerieOpenshiftClient, "new-project", 5*time.Second, 10) if err := requestProject.Run(); !kapierrors.IsAlreadyExists(err) { t.Fatalf("expected an already exists error, but got %v", err) } }
func validateToken(token string, clientConfig *kclient.Config) { if len(token) == 0 { fmt.Println("You must provide a token to validate") return } fmt.Printf("Using token: %v\n", token) clientConfig.BearerToken = token osClient, err := osclient.New(clientConfig) if err != nil { fmt.Printf("Error building osClient: %v\n", err) return } jsonResponse, _, err := getTokenInfo(token, osClient) if err != nil { fmt.Printf("%v\n", err) fmt.Println("Try visiting " + getRequestTokenURL(clientConfig) + " for a new token.") return } fmt.Printf("%v\n", string(jsonResponse)) whoami, err := osClient.Users().Get("~") if err != nil { fmt.Printf("Error making whoami request: %v\n", err) return } whoamiJSON, err := json.Marshal(whoami) if err != nil { fmt.Printf("Error interpretting whoami response: %v\n", err) return } fmt.Printf("%v\n", string(whoamiJSON)) }
// Clients returns an OpenShift and Kubernetes client with the credentials of the named service account // TODO: change return types to client.Interface/kclient.Interface to allow auto-reloading credentials func Clients(config restclient.Config, tokenRetriever TokenRetriever, namespace, name string) (*restclient.Config, *client.Client, *kclient.Client, error) { // Clear existing auth info config.Username = "" config.Password = "" config.CertFile = "" config.CertData = []byte{} config.KeyFile = "" config.KeyData = []byte{} config.BearerToken = "" if len(config.UserAgent) > 0 { config.UserAgent += " " } config.UserAgent += fmt.Sprintf("system:serviceaccount:%s:%s", namespace, name) // For now, just initialize the token once // TODO: refetch the token if the client encounters 401 errors token, err := tokenRetriever.GetToken(namespace, name) if err != nil { return nil, nil, nil, err } config.BearerToken = token c, err := client.New(&config) if err != nil { return nil, nil, nil, err } kc, err := kclient.New(&config) if err != nil { return nil, nil, nil, err } return &config, c, kc, nil }
// Clients returns an OpenShift and Kubernetes client with the credentials of the named service account // TODO: change return types to client.Interface/kclient.Interface to allow auto-reloading credentials func Clients(config kclient.Config, tokenRetriever TokenRetriever, namespace, name string) (*client.Client, *kclient.Client, error) { // Clear existing auth info config.Username = "" config.Password = "" config.CertFile = "" config.CertData = []byte{} config.KeyFile = "" config.KeyData = []byte{} // For now, just initialize the token once // TODO: refetch the token if the client encounters 401 errors token, err := tokenRetriever.GetToken(namespace, name) if err != nil { return nil, nil, err } config.BearerToken = token c, err := client.New(&config) if err != nil { return nil, nil, err } kc, err := kclient.New(&config) if err != nil { return nil, nil, err } return c, kc, nil }
func TestCLIGetToken(t *testing.T) { testutil.RequireEtcd(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() checkErr(t, err) clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) checkErr(t, err) anonymousConfig := clientcmd.AnonymousClientConfig(clusterAdminClientConfig) reader := bytes.NewBufferString("user\npass") accessToken, err := tokencmd.RequestToken(&anonymousConfig, reader, "", "") if err != nil { t.Errorf("Unexpected error: %v", err) } if len(accessToken) == 0 { t.Error("Expected accessToken, but did not get one") } clientConfig := clientcmd.AnonymousClientConfig(clusterAdminClientConfig) clientConfig.BearerToken = accessToken osClient, err := client.New(&clientConfig) checkErr(t, err) user, err := osClient.Users().Get("~") checkErr(t, err) if user.Name != "user" { t.Errorf("expected %v, got %v", "user", user.Name) } }
func TestBootstrapPolicySelfSubjectAccessReviews(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } valerieClientConfig := *clusterAdminClientConfig valerieClientConfig.Username = "" valerieClientConfig.Password = "" valerieClientConfig.BearerToken = "" valerieClientConfig.CertFile = "" valerieClientConfig.KeyFile = "" valerieClientConfig.CertData = nil valerieClientConfig.KeyData = nil accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!") if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig.BearerToken = accessToken valerieOpenshiftClient, err := client.New(&valerieClientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } // can I get a subjectaccessreview on myself even if I have no rights to do it generally askCanICreatePolicyBindings := &authorizationapi.LocalSubjectAccessReview{ Action: authorizationapi.Action{Verb: "create", Resource: "policybindings"}, } subjectAccessReviewTest{ localInterface: valerieOpenshiftClient.LocalSubjectAccessReviews("openshift"), localReview: askCanICreatePolicyBindings, response: authorizationapi.SubjectAccessReviewResponse{ Allowed: false, Reason: `User "valerie" cannot create policybindings in project "openshift"`, Namespace: "openshift", }, }.run(t) // I shouldn't be allowed to ask whether someone else can perform an action askCanClusterAdminsCreateProject := &authorizationapi.LocalSubjectAccessReview{ Groups: sets.NewString("system:cluster-admins"), Action: authorizationapi.Action{Verb: "create", Resource: "projects"}, } subjectAccessReviewTest{ localInterface: valerieOpenshiftClient.LocalSubjectAccessReviews("openshift"), localReview: askCanClusterAdminsCreateProject, err: `User "valerie" cannot create localsubjectaccessreviews in project "openshift"`, }.run(t) }
func (o LogoutOptions) RunLogout() error { token := o.Config.BearerToken client, err := client.New(o.Config) if err != nil { return err } userInfo, err := whoAmI(client) if err != nil { return err } if err := client.OAuthAccessTokens().Delete(token); err != nil { return err } newConfig := *o.StartingKubeConfig for key, value := range newConfig.AuthInfos { if value.Token == token { value.Token = "" newConfig.AuthInfos[key] = value // don't break, its possible that more than one user stanza has the same token. } } if err := kclientcmd.ModifyConfig(o.PathOptions, newConfig, true); err != nil { return err } fmt.Fprintf(o.Out, "Logged %q out on %q\n", userInfo.Name, o.Config.Host) return nil }
func GetScopedClientForUser(adminClient *client.Client, clientConfig restclient.Config, username string, scopes []string) (*client.Client, *kclient.Client, *restclient.Config, error) { // make sure the user exists if _, _, _, err := GetClientForUser(clientConfig, username); err != nil { return nil, nil, nil, err } user, err := adminClient.Users().Get(username) if err != nil { return nil, nil, nil, err } token := &oauthapi.OAuthAccessToken{ ObjectMeta: kapi.ObjectMeta{Name: fmt.Sprintf("%s-token-plus-some-padding-here-to-make-the-limit-%d", username, rand.Int())}, ClientName: origin.OpenShiftCLIClientID, ExpiresIn: 86400, Scopes: scopes, RedirectURI: "https://127.0.0.1:12000/oauth/token/implicit", UserName: user.Name, UserUID: string(user.UID), } if _, err := adminClient.OAuthAccessTokens().Create(token); err != nil { return nil, nil, nil, err } scopedConfig := clientcmd.AnonymousClientConfig(&clientConfig) scopedConfig.BearerToken = token.Name kubeClient, err := kclient.New(&scopedConfig) if err != nil { return nil, nil, nil, err } osClient, err := client.New(&scopedConfig) if err != nil { return nil, nil, nil, err } return osClient, kubeClient, &scopedConfig, nil }
func (o *LoginOptions) canRequestProjects() (bool, error) { oClient, err := client.New(o.Config) if err != nil { return false, err } sar := &authorizationapi.SubjectAccessReview{ Action: authorizationapi.Action{ Namespace: o.DefaultNamespace, Verb: "list", Resource: "projectrequests", }, } listResponse, err := oClient.SubjectAccessReviews().Create(sar) if err != nil { return false, err } sar = &authorizationapi.SubjectAccessReview{ Action: authorizationapi.Action{ Namespace: o.DefaultNamespace, Verb: "create", Resource: "projectrequests", }, } createResponse, err := oClient.SubjectAccessReviews().Create(sar) if err != nil { return false, err } return (listResponse.Allowed && createResponse.Allowed), nil }
func TestUnprivilegedNewProjectDenied(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } role, err := clusterAdminClient.ClusterRoles().Get(bootstrappolicy.SelfProvisionerRoleName) if err != nil { t.Fatalf("unexpected error: %v", err) } role.Rules = []authorizationapi.PolicyRule{} if _, err := clusterAdminClient.ClusterRoles().Update(role); err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig := *clusterAdminClientConfig valerieClientConfig.Username = "" valerieClientConfig.Password = "" valerieClientConfig.BearerToken = "" valerieClientConfig.CertFile = "" valerieClientConfig.KeyFile = "" valerieClientConfig.CertData = nil valerieClientConfig.KeyData = nil accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!") if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig.BearerToken = accessToken valerieOpenshiftClient, err := client.New(&valerieClientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } if err := testutil.WaitForClusterPolicyUpdate(valerieOpenshiftClient, "create", projectapi.Resource("projectrequests"), false); err != nil { t.Fatalf("unexpected error: %v", err) } // confirm that we have access to request the project _, err = valerieOpenshiftClient.ProjectRequests().List(kapi.ListOptions{}) if err == nil { t.Fatalf("expected error: %v", err) } expectedError := `You may not request a new project via this API.` if (err != nil) && (err.Error() != expectedError) { t.Fatalf("expected\n\t%v\ngot\n\t%v", expectedError, err.Error()) } }
func GetClientForUser(clientConfig kclient.Config, username string) (*client.Client, *kclient.Client, *kclient.Config, error) { token, err := tokencmd.RequestToken(&clientConfig, nil, username, "password") if err != nil { return nil, nil, nil, err } userClientConfig := clientConfig userClientConfig.BearerToken = token userClientConfig.Username = "" userClientConfig.Password = "" userClientConfig.TLSClientConfig.CertFile = "" userClientConfig.TLSClientConfig.KeyFile = "" userClientConfig.TLSClientConfig.CertData = nil userClientConfig.TLSClientConfig.KeyData = nil kubeClient, err := kclient.New(&userClientConfig) if err != nil { return nil, nil, nil, err } osClient, err := client.New(&userClientConfig) if err != nil { return nil, nil, nil, err } return osClient, kubeClient, &userClientConfig, nil }
func (c *config) getOsClient() *osclient.Client { osClient, err := osclient.New("http://"+c.ListenAddr, nil) if err != nil { glog.Fatalf("Unable to configure client - bad URL: %v", err) } return osClient }
// Client provides an OpenShift client for the current user. If the user is not // set, then it provides client for the cluster admin user func (c *CLI) Client() *client.Client { _, _, clientConfig, err := configapi.GetKubeClient(c.configPath, nil) osClient, err := client.New(clientConfig) if err != nil { FatalErr(err) } return osClient }
func (o LoginOptions) whoAmI() (*api.User, error) { client, err := client.New(o.Config) if err != nil { return nil, err } return whoAmI(client) }
// AdminREST provides an OpenShift REST client for the cluster admin user. func (c *CLI) AdminREST() *client.Client { _, clientConfig, err := configapi.GetKubeClient(c.adminConfigPath) osClient, err := client.New(clientConfig) if err != nil { FatalErr(err) } return osClient }
func TestBootstrapPolicyAuthenticatedUsersAgainstOpenshiftNamespace(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } valerieClientConfig := *clusterAdminClientConfig valerieClientConfig.Username = "" valerieClientConfig.Password = "" valerieClientConfig.BearerToken = "" valerieClientConfig.CertFile = "" valerieClientConfig.KeyFile = "" valerieClientConfig.CertData = nil valerieClientConfig.KeyData = nil accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!") if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig.BearerToken = accessToken valerieOpenshiftClient, err := client.New(&valerieClientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } openshiftSharedResourcesNamespace := "openshift" if _, err := valerieOpenshiftClient.Templates(openshiftSharedResourcesNamespace).List(kapi.ListOptions{}); err != nil { t.Errorf("unexpected error: %v", err) } if _, err := valerieOpenshiftClient.Templates(kapi.NamespaceDefault).List(kapi.ListOptions{}); err == nil || !kapierror.IsForbidden(err) { t.Errorf("unexpected error: %v", err) } if _, err := valerieOpenshiftClient.ImageStreams(openshiftSharedResourcesNamespace).List(kapi.ListOptions{}); err != nil { t.Errorf("unexpected error: %v", err) } if _, err := valerieOpenshiftClient.ImageStreams(kapi.NamespaceDefault).List(kapi.ListOptions{}); err == nil || !kapierror.IsForbidden(err) { t.Errorf("unexpected error: %v", err) } if _, err := valerieOpenshiftClient.ImageStreamTags(openshiftSharedResourcesNamespace).Get("name", "tag"); !kapierror.IsNotFound(err) { t.Errorf("unexpected error: %v", err) } if _, err := valerieOpenshiftClient.ImageStreamTags(kapi.NamespaceDefault).Get("name", "tag"); err == nil || !kapierror.IsForbidden(err) { t.Errorf("unexpected error: %v", err) } }
func NewOpenShiftClient(cfg *restclient.Config) (*oclient.Client, *restclient.Config) { ocfg := *cfg ocfg.APIPath = "" c, err := oclient.New(&ocfg) if err != nil { util.Fatalf("Could not initialise an OpenShift client: %v", err) } return c, cfg }
func GetClusterAdminClient(adminKubeConfigFile string) (*client.Client, error) { clientConfig, err := GetClusterAdminClientConfig(adminKubeConfigFile) if err != nil { return nil, err } osClient, err := client.New(clientConfig) if err != nil { return nil, err } return osClient, nil }
func getClient() (client.Interface, error) { clientConfig, err := restclient.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to get client config: %v", err) } osClient, err := client.New(clientConfig) if err != nil { return nil, fmt.Errorf("error obtaining OpenShift client: %v", err) } return osClient, nil }
func NewUserOpenShiftClient(bearerToken string) (*osclient.Client, error) { config, err := openShiftClientConfig() if err != nil { return nil, err } config.BearerToken = bearerToken client, err := osclient.New(config) if err != nil { return nil, fmt.Errorf("error creating Origin client: %s", err) } return client, nil }
func clients() (*osclient.Client, *kubeclient.Client) { kubeClient, err := kubeclient.New(defaultServerAddr, nil) if err != nil { glog.Fatalf("Unable to start tour: %v", err) } client, err := osclient.New(defaultServerAddr, nil) if err != nil { glog.Fatalf("Unable to start tour: %v", err) } return client, kubeClient }
// TestVerifyImageStreamAccess mocks openshift http request/response and // tests invalid/valid/scoped openshift tokens. func TestVerifyImageStreamAccess(t *testing.T) { tests := []struct { openshiftResponse response expectedError error }{ { // Test invalid openshift bearer token openshiftResponse: response{401, "Unauthorized"}, expectedError: ErrOpenShiftAccessDenied, }, { // Test valid openshift bearer token but token *not* scoped for create operation openshiftResponse: response{ 200, runtime.EncodeOrDie(kapi.Codecs.LegacyCodec(registered.GroupOrDie(kapi.GroupName).GroupVersions[0]), &api.SubjectAccessReviewResponse{ Namespace: "foo", Allowed: false, Reason: "not authorized!", }), }, expectedError: ErrOpenShiftAccessDenied, }, { // Test valid openshift bearer token and token scoped for create operation openshiftResponse: response{ 200, runtime.EncodeOrDie(kapi.Codecs.LegacyCodec(registered.GroupOrDie(kapi.GroupName).GroupVersions[0]), &api.SubjectAccessReviewResponse{ Namespace: "foo", Allowed: true, Reason: "authorized!", }), }, expectedError: nil, }, } for _, test := range tests { ctx := context.Background() server, _ := simulateOpenShiftMaster([]response{test.openshiftResponse}) client, err := client.New(&restclient.Config{BearerToken: "magic bearer token", Host: server.URL}) if err != nil { t.Fatal(err) } err = verifyImageStreamAccess(ctx, "foo", "bar", "create", client) if err == nil || test.expectedError == nil { if err != test.expectedError { t.Fatalf("verifyImageStreamAccess did not get expected error - got %s - expected %s", err, test.expectedError) } } else if err.Error() != test.expectedError.Error() { t.Fatalf("verifyImageStreamAccess did not get expected error - got %s - expected %s", err, test.expectedError) } server.Close() } }
func whoami(clientCfg *kclient.Config) (*api.User, error) { oClient, err := client.New(clientCfg) if err != nil { return nil, err } me, err := oClient.Users().Get("~") if err != nil { return nil, err } return me, nil }
func GetClientForServiceAccount(adminClient *kclientset.Clientset, clientConfig restclient.Config, namespace, name string) (*client.Client, *kclientset.Clientset, *restclient.Config, error) { _, err := adminClient.Core().Namespaces().Create(&kapi.Namespace{ObjectMeta: kapi.ObjectMeta{Name: namespace}}) if err != nil && !kerrs.IsAlreadyExists(err) { return nil, nil, nil, err } sa, err := adminClient.Core().ServiceAccounts(namespace).Create(&kapi.ServiceAccount{ObjectMeta: kapi.ObjectMeta{Name: name}}) if kerrs.IsAlreadyExists(err) { sa, err = adminClient.Core().ServiceAccounts(namespace).Get(name) } if err != nil { return nil, nil, nil, err } token := "" err = wait.Poll(time.Second, 30*time.Second, func() (bool, error) { selector := fields.OneTermEqualSelector(kapi.SecretTypeField, string(kapi.SecretTypeServiceAccountToken)) secrets, err := adminClient.Core().Secrets(namespace).List(kapi.ListOptions{FieldSelector: selector}) if err != nil { return false, err } for _, secret := range secrets.Items { if serviceaccounts.IsValidServiceAccountToken(sa, &secret) { token = string(secret.Data[kapi.ServiceAccountTokenKey]) return true, nil } } return false, nil }) if err != nil { return nil, nil, nil, err } saClientConfig := clientcmd.AnonymousClientConfig(&clientConfig) saClientConfig.BearerToken = token kubeClient, err := kclient.New(&saClientConfig) if err != nil { return nil, nil, nil, err } kubeClientset := adapter.FromUnversionedClient(kubeClient) osClient, err := client.New(&saClientConfig) if err != nil { return nil, nil, nil, err } return osClient, kubeClientset, &saClientConfig, nil }
func newBuilderConfigFromEnvironment(out io.Writer) (*builderConfig, error) { cfg := &builderConfig{} var err error cfg.out = out // build (BUILD) buildStr := os.Getenv("BUILD") glog.V(4).Infof("$BUILD env var is %s \n", buildStr) cfg.build = &api.Build{} if err := runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), []byte(buildStr), cfg.build); err != nil { return nil, fmt.Errorf("unable to parse build: %v", err) } if errs := validation.ValidateBuild(cfg.build); len(errs) > 0 { return nil, errors.NewInvalid(unversioned.GroupKind{Kind: "Build"}, cfg.build.Name, errs) } glog.V(4).Infof("Build: %#v", cfg.build) masterVersion := os.Getenv(api.OriginVersion) thisVersion := version.Get().String() if len(masterVersion) != 0 && masterVersion != thisVersion { fmt.Fprintf(cfg.out, "warning: OpenShift server version %q differs from this image %q\n", masterVersion, thisVersion) } else { glog.V(4).Infof("Master version %q, Builder version %q", masterVersion, thisVersion) } // sourceSecretsDir (SOURCE_SECRET_PATH) cfg.sourceSecretDir = os.Getenv("SOURCE_SECRET_PATH") // dockerClient and dockerEndpoint (DOCKER_HOST) // usually not set, defaults to docker socket cfg.dockerClient, cfg.dockerEndpoint, err = dockerutil.NewHelper().GetClient() if err != nil { return nil, fmt.Errorf("no Docker configuration defined: %v", err) } // buildsClient (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT) clientConfig, err := restclient.InClusterConfig() if err != nil { return nil, fmt.Errorf("cannot connect to the server: %v", err) } osClient, err := client.New(clientConfig) if err != nil { return nil, fmt.Errorf("failed to get client: %v", err) } cfg.buildsClient = osClient.Builds(cfg.build.Namespace) return cfg, nil }
// run is responsible for preparing environment for actual build. // It accepts factoryFunc and an ordered array of SCMAuths. func run(b builder) { dockerClient, endpoint, err := dockerutil.NewHelper().GetClient() if err != nil { glog.Fatalf("Error obtaining docker client: %v", err) } buildStr := os.Getenv("BUILD") glog.V(4).Infof("$BUILD env var is %s \n", buildStr) build := api.Build{} if err := latest.Codec.DecodeInto([]byte(buildStr), &build); err != nil { glog.Fatalf("Unable to parse build: %v", err) } if build.Spec.Source.SourceSecret != nil { if build.Spec.Source.Git != nil { // TODO: this should be refactored to let each source type manage which secrets // it accepts sourceURL, err := git.ParseRepository(build.Spec.Source.Git.URI) if err != nil { glog.Fatalf("Cannot parse build URL: %s", build.Spec.Source.Git.URI) } scmAuths := auths(sourceURL) sourceURL, err = setupSourceSecret(build.Spec.Source.SourceSecret.Name, scmAuths) if err != nil { glog.Fatalf("Cannot setup secret file for accessing private repository: %v", err) } if sourceURL != nil { build.Annotations[bld.OriginalSourceURLAnnotationKey] = build.Spec.Source.Git.URI build.Spec.Source.Git.URI = sourceURL.String() } } } config, err := kclient.InClusterConfig() if err != nil { glog.Fatalf("Failed to get client config: %v", err) } osClient, err := client.New(config) if err != nil { glog.Fatalf("Error obtaining OpenShift client: %v", err) } buildsClient := osClient.Builds(build.Namespace) if err = b.Build(dockerClient, endpoint, buildsClient, &build); err != nil { glog.Fatalf("Build error: %v", err) } if build.Spec.Output.To == nil || len(build.Spec.Output.To.Name) == 0 { glog.Warning("Build does not have an Output defined, no output image was pushed to a registry.") } }
// Clients returns an OpenShift and a Kubernetes client from a given configuration func (cfg *Config) Clients() (osclient.Interface, kclient.Interface, error) { cfg.bindEnv() kubeClient, err := kclient.New(cfg.KubeConfig()) if err != nil { return nil, nil, fmt.Errorf("Unable to configure Kubernetes client: %v", err) } osClient, err := osclient.New(cfg.OpenShiftConfig()) if err != nil { return nil, nil, fmt.Errorf("Unable to configure Origin client: %v", err) } return osClient, kubeClient, nil }
// ClientForVersion initializes or reuses a client for the specified version, or returns an // error if that is not possible func (c *clientCache) ClientForVersion(version string) (*client.Client, error) { if client, ok := c.clients[version]; ok { return client, nil } config, err := c.ClientConfigForVersion(version) if err != nil { return nil, err } client, err := client.New(config) if err != nil { return nil, err } c.clients[config.Version] = client return client, nil }