forked from openshift/ansible-service-broker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
255 lines (213 loc) · 6.04 KB
/
client.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
252
253
254
255
package apb
import (
"encoding/json"
"errors"
"fmt"
"os"
docker "github.com/fsouza/go-dockerclient"
logging "github.com/op/go-logging"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
restclient "k8s.io/client-go/rest"
"github.com/openshift/ansible-service-broker/pkg/clients"
"github.com/pborman/uuid"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
)
/*
parameters will be 2 keys
answers {}
kubecfg {}
deprovision - delete the namespace and it tears the whole thing down.
oc delete?
route will be hardcoded, need to determine how to get that from the apb.
need to pass in cert through parameters
First cut might have to pass kubecfg from broker. FIRST SPRINT broker passes username and password.
admin/admin
*/
type ClusterConfig struct {
InCluster bool
Target string
User string
Password string `yaml:"pass"`
}
type Client struct {
dockerClient *docker.Client
ClusterClient *clientset.Clientset
RESTClient restclient.Interface
log *logging.Logger
}
func NewClient(log *logging.Logger) (*Client, error) {
dockerClient, err := clients.Docker(log)
if err != nil {
log.Error("Could not load docker client")
return nil, err
}
k8s, err := clients.Kubernetes(log)
if err != nil {
return nil, err
}
rest := k8s.CoreV1().RESTClient()
client := &Client{
dockerClient: dockerClient,
ClusterClient: k8s,
RESTClient: rest,
log: log,
}
return client, nil
}
func (c *Client) RunImage(
action string,
clusterConfig ClusterConfig,
spec *Spec,
context *Context,
p *Parameters,
) (string, error) {
// HACK: We're expecting to run containers via go APIs rather than cli cmds
// TODO: Expecting parameters to be passed here in the future as well
extraVars, err := createExtraVars(context, p)
if err != nil {
return "", err
}
if !clusterConfig.InCluster {
err = c.RefreshLoginToken(clusterConfig)
if err != nil {
c.log.Error("Error occurred while refreshing login token! Aborting apb run.")
c.log.Error(err.Error())
return "", err
}
c.log.Notice("Login token successfully refreshed.")
}
c.log.Debug("clusterConfig:")
if !clusterConfig.InCluster {
c.log.Debug("target: [ %s ]", clusterConfig.Target)
c.log.Debug("user: [ %s ]", clusterConfig.User)
}
c.log.Debug("name:[ %s ]", spec.Name)
c.log.Debug("image:[ %s ]", spec.Image)
c.log.Debug("action:[ %s ]", action)
// It's a critical error if a Namespace is not provided to the
// broker because its required to know where to execute the pods and
// sandbox them based on that Namespace. Should fail fast and loud,
// with controlled error handling.
if context.Namespace == "" {
errStr := "Namespace not found within request context. Cannot perform requested " + action
c.log.Error(errStr)
return "", errors.New(errStr)
}
ns := context.Namespace
apbId := fmt.Sprintf("apb-%s", uuid.New())
sam := NewServiceAccountManager(c.log)
serviceAccountName, err := sam.CreateApbSandbox(ns, apbId)
if err != nil {
c.log.Error(err.Error())
return apbId, err
}
// TODO(rhallisey): Cleanup the local vs incluster code paths so there
// is almost no variation between the two.
// TODO(rhallisey): The Kubernetes API objects should be in JSON structs
// so it's easier to manipulate them. This is for a rebase so we don't
// block the service account work. I'll come back after and clean this
// up.
var pod *v1.Pod
if clusterConfig.InCluster {
pod = &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: apbId,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "apb",
Image: spec.Image,
Args: []string{
action,
"--extra-vars",
extraVars,
},
ImagePullPolicy: v1.PullAlways,
},
},
RestartPolicy: v1.RestartPolicyNever,
ServiceAccountName: serviceAccountName,
},
}
} else {
pod = &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: apbId,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "apb",
Image: spec.Image,
Args: []string{
action,
"--extra-vars",
extraVars,
},
Env: []v1.EnvVar{{
Name: "OPENSHIFT_TARGET",
Value: clusterConfig.Target,
}, {
Name: "OPENSHIFT_USER",
Value: clusterConfig.User,
}, {
Name: "OPENSHIFT_PASS",
Value: clusterConfig.Password,
}},
ImagePullPolicy: v1.PullAlways,
},
},
RestartPolicy: v1.RestartPolicyNever,
},
}
}
c.log.Notice(fmt.Sprintf("Creating pod %q in the %s namespace", pod.Name, ns))
_, err = c.ClusterClient.CoreV1().Pods(ns).Create(pod)
return apbId, err
}
func (c *Client) PullImage(imageName string) error {
// Under what circumstances does this error out?
c.dockerClient.PullImage(docker.PullImageOptions{
Repository: imageName,
OutputStream: os.Stdout,
}, docker.AuthConfiguration{})
return nil
}
func (c *Client) RefreshLoginToken(clusterConfig ClusterConfig) error {
return OcLogin(c.log,
"--insecure-skip-tls-verify", clusterConfig.Target,
"-u", clusterConfig.User,
"-p", clusterConfig.Password,
)
}
// TODO(fabianvf): This function is also called from broker/broker.go
// We should probably move this logic out of the client to a more
// generic location.
func OcLogin(log *logging.Logger, args ...string) error {
log.Debug("Logging into openshift...")
fullArgs := append([]string{"login"}, args...)
output, err := RunCommand("oc", fullArgs...)
if err != nil {
log.Debug(string(output))
return err
}
return nil
}
// TODO: Instead of putting namespace directly as a parameter, we should create a dictionary
// of apb_metadata and put context and other variables in it so we don't pollute the user
// parameter space.
func createExtraVars(context *Context, parameters *Parameters) (string, error) {
var paramsCopy Parameters
if parameters != nil && *parameters != nil {
paramsCopy = *parameters
} else {
paramsCopy = make(Parameters)
}
if context != nil {
paramsCopy["namespace"] = context.Namespace
}
extraVars, err := json.Marshal(paramsCopy)
return string(extraVars), err
}