forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ref.go
335 lines (285 loc) · 11.1 KB
/
ref.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package jenkins
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/util/wait"
exutil "github.com/openshift/origin/test/extended/util"
)
// JenkinsRef represents a Jenkins instance running on an OpenShift server
type JenkinsRef struct {
oc *exutil.CLI
host string
port string
// The namespace in which the Jenkins server is running
namespace string
token string
}
// FlowDefinition can be marshalled into XML to represent a Jenkins workflow job definition.
type FlowDefinition struct {
XMLName xml.Name `xml:"flow-definition"`
Plugin string `xml:"plugin,attr"`
KeepDependencies bool `xml:"keepDependencies"`
Definition Definition
}
// Definition is part of a FlowDefinition
type Definition struct {
XMLName xml.Name `xml:"definition"`
Class string `xml:"class,attr"`
Plugin string `xml:"plugin,attr"`
Script string `xml:"script"`
}
// ginkgolog creates simple entry in the GinkgoWriter.
func ginkgolog(format string, a ...interface{}) {
fmt.Fprintf(g.GinkgoWriter, format+"\n", a...)
}
// NewRef creates a jenkins reference from an OC client
func NewRef(oc *exutil.CLI) *JenkinsRef {
g.By("get ip and port for jenkins service")
serviceIP, err := oc.Run("get").Args("svc", "jenkins", "--config", exutil.KubeConfigPath()).Template("{{.spec.clusterIP}}").Output()
o.Expect(err).NotTo(o.HaveOccurred())
port, err := oc.Run("get").Args("svc", "jenkins", "--config", exutil.KubeConfigPath()).Template("{{ $x := index .spec.ports 0}}{{$x.port}}").Output()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("get token via whoami")
token, err := oc.Run("whoami").Args("-t").Output()
o.Expect(err).NotTo(o.HaveOccurred())
j := &JenkinsRef{
oc: oc,
host: serviceIP,
port: port,
namespace: oc.Namespace(),
token: token,
}
return j
}
// Namespace returns the Jenkins namespace
func (j *JenkinsRef) Namespace() string {
return j.namespace
}
// BuildURI builds a URI for the Jenkins server.
func (j *JenkinsRef) BuildURI(resourcePathFormat string, a ...interface{}) string {
resourcePath := fmt.Sprintf(resourcePathFormat, a...)
return fmt.Sprintf("http://%s:%v/%s", j.host, j.port, resourcePath)
}
// GetResource submits a GET request to this Jenkins server.
// Returns a response body and status code or an error.
func (j *JenkinsRef) GetResource(resourcePathFormat string, a ...interface{}) (string, int, error) {
uri := j.BuildURI(resourcePathFormat, a...)
ginkgolog("Retrieving Jenkins resource: %q", uri)
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return "", 0, fmt.Errorf("Unable to build request for uri %q: %v", uri, err)
}
// http://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors-when-making-multiple-requests-successi
req.Close = true
req.Header.Set("Authorization", "Bearer "+j.token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", 0, fmt.Errorf("Unable to GET uri %q: %v", uri, err)
}
defer resp.Body.Close()
status := resp.StatusCode
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", 0, fmt.Errorf("Error reading GET response %q: %v", uri, err)
}
return string(body), status, nil
}
// Post sends a POST to the Jenkins server. Returns response body and status code or an error.
func (j *JenkinsRef) Post(reqBody io.Reader, resourcePathFormat, contentType string, a ...interface{}) (string, int, error) {
uri := j.BuildURI(resourcePathFormat, a...)
req, err := http.NewRequest("POST", uri, reqBody)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
// http://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors-when-making-multiple-requests-successi
req.Close = true
if reqBody != nil {
req.Header.Set("Content-Type", contentType)
req.Header.Del("Expect") // jenkins will return 417 if we have an expect hdr
}
req.Header.Set("Authorization", "Bearer "+j.token)
client := &http.Client{}
ginkgolog("Posting to Jenkins resource: %q", uri)
resp, err := client.Do(req)
if err != nil {
return "", 0, fmt.Errorf("Error posting request to %q: %v", uri, err)
}
defer resp.Body.Close()
status := resp.StatusCode
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", 0, fmt.Errorf("Error reading Post response body %q: %v", uri, err)
}
return string(body), status, nil
}
// PostXML sends a POST to the Jenkins server. If a body is specified, it should be XML.
// Returns response body and status code or an error.
func (j *JenkinsRef) PostXML(reqBody io.Reader, resourcePathFormat string, a ...interface{}) (string, int, error) {
return j.Post(reqBody, resourcePathFormat, "application/xml", a...)
}
// GetResourceWithStatus repeatedly tries to GET a jenkins resource with an acceptable
// HTTP status. Retries for the specified duration.
func (j *JenkinsRef) GetResourceWithStatus(validStatusList []int, timeout time.Duration, resourcePathFormat string, a ...interface{}) (string, int, error) {
var retBody string
var retStatus int
err := wait.Poll(10*time.Second, timeout, func() (bool, error) {
body, status, err := j.GetResource(resourcePathFormat, a...)
if err != nil {
ginkgolog("Error accessing resource: %v", err)
return false, nil
}
var found bool
for _, s := range validStatusList {
if status == s {
found = true
break
}
}
if !found {
ginkgolog("Expected http status [%v] during GET by recevied [%v]", validStatusList, status)
return false, nil
}
retBody = body
retStatus = status
return true, nil
})
if err != nil {
uri := j.BuildURI(resourcePathFormat, a...)
return "", retStatus, fmt.Errorf("Error waiting for status %v from resource path %s: %v", validStatusList, uri, err)
}
return retBody, retStatus, nil
}
// WaitForContent waits for a particular HTTP status and HTML matching a particular
// pattern to be returned by this Jenkins server. An error will be returned
// if the condition is not matched within the timeout period.
func (j *JenkinsRef) WaitForContent(verificationRegEx string, verificationStatus int, timeout time.Duration, resourcePathFormat string, a ...interface{}) (string, error) {
var matchingContent = ""
err := wait.Poll(10*time.Second, timeout, func() (bool, error) {
content, _, err := j.GetResourceWithStatus([]int{verificationStatus}, timeout, resourcePathFormat, a...)
if err != nil {
return false, nil
}
if len(verificationRegEx) > 0 {
re := regexp.MustCompile(verificationRegEx)
if re.MatchString(content) {
matchingContent = content
return true, nil
} else {
ginkgolog("Content did not match verification regex %q:\n %v", verificationRegEx, content)
return false, nil
}
} else {
matchingContent = content
return true, nil
}
})
if err != nil {
uri := j.BuildURI(resourcePathFormat, a...)
return "", fmt.Errorf("Error waiting for status %v and verification regex %q from resource path %s: %v", verificationStatus, verificationRegEx, uri, err)
} else {
return matchingContent, nil
}
}
// CreateItem submits XML to create a named item on the Jenkins server.
func (j *JenkinsRef) CreateItem(name string, itemDefXML string) {
g.By(fmt.Sprintf("Creating new jenkins item: %s", name))
_, status, err := j.PostXML(bytes.NewBufferString(itemDefXML), "createItem?name=%s", name)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
o.ExpectWithOffset(1, status).To(o.Equal(200))
}
// GetJobBuildNumber returns the current buildNumber on the named project OR "new" if
// there are no builds against a job yet.
func (j *JenkinsRef) GetJobBuildNumber(name string, timeout time.Duration) (string, error) {
body, status, err := j.GetResourceWithStatus([]int{200, 404}, timeout, "job/%s/lastBuild/buildNumber", name)
if err != nil {
return "", err
}
if status != 200 {
return "new", nil
}
return body, nil
}
// StartJob triggers a named Jenkins job. The job can be monitored with the
// returned object.
func (j *JenkinsRef) StartJob(jobName string) *JobMon {
lastBuildNumber, err := j.GetJobBuildNumber(jobName, time.Minute)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
jmon := &JobMon{
j: j,
lastBuildNumber: lastBuildNumber,
buildNumber: "",
jobName: jobName,
}
ginkgolog("Current timestamp for [%s]: %q", jobName, jmon.lastBuildNumber)
g.By(fmt.Sprintf("Starting jenkins job: %s", jobName))
_, status, err := j.PostXML(nil, "job/%s/build?delay=0sec", jobName)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
o.ExpectWithOffset(1, status).To(o.Equal(201))
return jmon
}
// ReadJenkinsJobUsingVars returns the content of a Jenkins job XML file. Instances of the
// string "PROJECT_NAME" are replaced with the specified namespace.
// Variables named in the vars map will also be replaced with their
// corresponding value.
func (j *JenkinsRef) ReadJenkinsJobUsingVars(filename, namespace string, vars map[string]string) string {
pre := exutil.FixturePath("testdata", "jenkins-plugin", filename)
post := exutil.ArtifactPath(filename)
if vars == nil {
vars = map[string]string{}
}
vars["PROJECT_NAME"] = namespace
err := exutil.VarSubOnFile(pre, post, vars)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
data, err := ioutil.ReadFile(post)
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
return string(data)
}
// ReadJenkinsJob returns the content of a Jenkins job XML file. Instances of the
// string "PROJECT_NAME" are replaced with the specified namespace.
func (j *JenkinsRef) ReadJenkinsJob(filename, namespace string) string {
return j.ReadJenkinsJobUsingVars(filename, namespace, nil)
}
// BuildDSLJob returns an XML string defining a Jenkins workflow/pipeline DSL job. Instances of the
// string "PROJECT_NAME" are replaced with the specified namespace.
func (j *JenkinsRef) BuildDSLJob(namespace string, scriptLines ...string) (string, error) {
script := strings.Join(scriptLines, "\n")
script = strings.Replace(script, "PROJECT_NAME", namespace, -1)
fd := FlowDefinition{
Plugin: "workflow-job@2.7",
Definition: Definition{
Class: "org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition",
Plugin: "workflow-cps@2.18",
Script: script,
},
}
output, err := xml.MarshalIndent(fd, " ", " ")
ginkgolog("Formulated DSL Project XML:\n%s\n\n", output)
return string(output), err
}
// GetJobConsoleLogs returns the console logs of a particular buildNumber.
func (j *JenkinsRef) GetJobConsoleLogs(jobName, buildNumber string) (string, error) {
return j.WaitForContent("", 200, 10*time.Minute, "job/%s/%s/consoleText", jobName, buildNumber)
}
// GetLastJobConsoleLogs returns the last build associated with a Jenkins job.
func (j *JenkinsRef) GetLastJobConsoleLogs(jobName string) (string, error) {
return j.GetJobConsoleLogs(jobName, "lastBuild")
}
// Finds the pod running Jenkins
func FindJenkinsPod(oc *exutil.CLI) *kapi.Pod {
pods, err := exutil.GetDeploymentConfigPods(oc, "jenkins")
o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred())
if pods == nil || pods.Items == nil {
g.Fail("No pods matching jenkins deploymentconfig in namespace " + oc.Namespace())
}
o.ExpectWithOffset(1, len(pods.Items)).To(o.Equal(1))
return &pods.Items[0]
}