forked from openshift/origin
/
project.go
251 lines (209 loc) · 7.36 KB
/
project.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package cmd
import (
"bytes"
"fmt"
"io"
"os"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
kclient "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
kclientcmd "github.com/GoogleCloudPlatform/kubernetes/pkg/client/clientcmd"
clientcmdapi "github.com/GoogleCloudPlatform/kubernetes/pkg/client/clientcmd/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
"github.com/openshift/origin/pkg/client"
cliconfig "github.com/openshift/origin/pkg/cmd/cli/config"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
"github.com/openshift/origin/pkg/project/api"
"github.com/spf13/cobra"
)
func NewCmdProject(f *clientcmd.Factory, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "project <project-name>",
Short: "switch to another project",
Long: `Switch to another project and make it the default in your configuration.`,
Run: func(cmd *cobra.Command, args []string) {
err := RunProject(f, out, cmd, args)
if err == errExit {
os.Exit(1)
}
cmdutil.CheckErr(err)
},
}
return cmd
}
func RunProject(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
argsLength := len(args)
if argsLength > 1 {
return cmdutil.UsageError(cmd, "Only one argument is supported (project name).")
}
rawCfg, err := f.OpenShiftClientConfig.RawConfig()
if err != nil {
return err
}
clientCfg, err := f.OpenShiftClientConfig.ClientConfig()
if err != nil {
return err
}
oClient, _, err := f.Clients()
if err != nil {
return err
}
// No argument provided, we will just print info
if argsLength == 0 {
currentContext := rawCfg.Contexts[rawCfg.CurrentContext]
currentProject := currentContext.Namespace
if len(currentProject) > 0 {
_, err := oClient.Projects().Get(currentProject)
if err != nil {
if errors.IsNotFound(err) {
return fmt.Errorf("the project %q specified in your config does not exist.", currentProject)
}
if clientcmd.IsForbidden(err) {
return fmt.Errorf("you do not have rights to view project %q.", currentProject)
}
return err
}
if rawCfg.CurrentContext != currentProject {
if len(currentProject) > 0 {
fmt.Fprintf(out, "Using project %q from context named %q on server %q.\n", currentProject, rawCfg.CurrentContext, clientCfg.Host)
} else {
fmt.Fprintf(out, "Using context named %q on server %q.\n", rawCfg.CurrentContext, clientCfg.Host)
}
} else {
fmt.Fprintf(out, "Using project %q on server %q.\n", currentProject, clientCfg.Host)
}
} else {
fmt.Fprintf(out, "No project has been set. Pass a project name to make that the default.\n")
}
return nil
}
// We have an argument that can be either a context or project
argument := args[0]
configStore, err := loadConfigStore(cmd)
if err != nil {
return err
}
config := configStore.Config
contextInUse := ""
namespaceInUse := ""
// Check if argument is an existing context, if so just set it as the context in use.
// If not a context then we will try to handle it as a project.
if context, ok := config.Contexts[argument]; ok && len(context.Namespace) > 0 {
contextInUse = argument
namespaceInUse = context.Namespace
config.CurrentContext = argument
} else {
project, err := oClient.Projects().Get(argument)
if err != nil {
if isNotFound, isForbidden := errors.IsNotFound(err), clientcmd.IsForbidden(err); isNotFound || isForbidden {
msg := ""
if isNotFound {
msg = fmt.Sprintf("A project named %q does not exist on server %q.", argument, clientCfg.Host)
} else {
msg = fmt.Sprintf("You do not have rights to view project %q on server %q.", argument, clientCfg.Host)
}
projects, err := getProjects(oClient)
if err == nil {
msg += "\nYour projects are:"
for _, project := range projects {
msg += "\n" + project.Name
}
}
if hasMultipleServers(config) {
msg += "\nTo see projects on another server, pass '--server=<server>'."
}
fmt.Fprintln(out, msg)
return errExit
}
return err
}
// If a context exists, just set it as the current one.
exists := false
for k, ctx := range config.Contexts {
namespace := ctx.Namespace
cluster := config.Clusters[ctx.Cluster]
authInfo := config.AuthInfos[ctx.AuthInfo]
if len(namespace) > 0 && namespace == project.Name && clusterAndAuthEquality(clientCfg, cluster, authInfo) {
exists = true
config.CurrentContext = k
contextInUse = k
namespaceInUse = namespace
break
}
}
// Otherwise create a new context, reusing the cluster and auth info
if !exists {
currentCtx := rawCfg.CurrentContext
newCtx := clientcmdapi.NewContext()
newCtx.Namespace = project.Name
newCtx.AuthInfo = rawCfg.Contexts[currentCtx].AuthInfo
newCtx.Cluster = rawCfg.Contexts[currentCtx].Cluster
existingContexIdentifiers := &util.StringSet{}
for key := range rawCfg.Contexts {
existingContexIdentifiers.Insert(key)
}
newCtxName := cliconfig.GenerateContextIdentifier(newCtx.Namespace, newCtx.Cluster, "", existingContexIdentifiers)
config.Contexts[newCtxName] = *newCtx
config.CurrentContext = newCtxName
contextInUse = newCtxName
namespaceInUse = project.Name
}
}
if err := kclientcmd.WriteToFile(*config, configStore.Path); err != nil {
return err
}
if contextInUse != namespaceInUse {
if len(namespaceInUse) > 0 {
fmt.Fprintf(out, "Now using project %q from context named %q on server %q.\n", namespaceInUse, contextInUse, clientCfg.Host)
} else {
fmt.Fprintf(out, "Now using context named %q on server %q.\n", contextInUse, clientCfg.Host)
}
} else {
fmt.Fprintf(out, "Now using project %q on server %q.\n", namespaceInUse, clientCfg.Host)
}
return nil
}
func getProjects(oClient *client.Client) ([]api.Project, error) {
projects, err := oClient.Projects().List(labels.Everything(), fields.Everything())
if err != nil {
return nil, err
}
return projects.Items, nil
}
func loadConfigStore(cmd *cobra.Command) (*cliconfig.ConfigStore, error) {
pathFromFlag := cmdutil.GetFlagString(cmd, cliconfig.OpenShiftConfigFlagName)
configStore, err := cliconfig.LoadFrom(pathFromFlag)
if err != nil {
configStore, err = cliconfig.LoadWithLoadingRules()
if err != nil {
return nil, err
}
}
return configStore, err
}
func clusterAndAuthEquality(clientCfg *kclient.Config, cluster clientcmdapi.Cluster, authInfo clientcmdapi.AuthInfo) bool {
return cluster.Server == clientCfg.Host &&
cluster.InsecureSkipTLSVerify == clientCfg.Insecure &&
cluster.CertificateAuthority == clientCfg.CAFile &&
bytes.Equal(cluster.CertificateAuthorityData, clientCfg.CAData) &&
authInfo.Token == clientCfg.BearerToken &&
authInfo.ClientCertificate == clientCfg.TLSClientConfig.CertFile &&
bytes.Equal(authInfo.ClientCertificateData, clientCfg.TLSClientConfig.CertData) &&
authInfo.ClientKey == clientCfg.TLSClientConfig.KeyFile &&
bytes.Equal(authInfo.ClientKeyData, clientCfg.TLSClientConfig.KeyData)
}
// TODO these kind of funcs could be moved to some kind of clientcmd util
func hasMultipleServers(config *clientcmdapi.Config) bool {
server := ""
for _, cluster := range config.Clusters {
if len(server) == 0 {
server = cluster.Server
}
if server != cluster.Server {
return true
}
}
return false
}