forked from abourget/teamcity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
296 lines (243 loc) · 6.81 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
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
package teamcity
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"time"
)
// Client to access a TeamCity API
type Client struct {
HTTPClient *http.Client
username string
password string
host string
}
func New(host, username, password string) *Client {
return &Client{
HTTPClient: http.DefaultClient,
username: username,
password: password,
host: host,
}
}
func (c *Client) QueueBuild(buildTypeID string, branchName string, properties map[string]string) (*Build, error) {
jsonQuery := struct {
BuildTypeID string `json:"buildTypeId,omitempty"`
Properties struct {
Property []oneProperty `json:"property,omitempty"`
} `json:"properties"`
BranchName string `json:"branchName,omitempty"`
}{}
jsonQuery.BuildTypeID = buildTypeID
if branchName != "" {
jsonQuery.BranchName = fmt.Sprintf("refs/heads/%s", branchName)
}
for k, v := range properties {
jsonQuery.Properties.Property = append(jsonQuery.Properties.Property, oneProperty{k, v})
}
build := &Build{}
retries := 8
err := withRetry(retries, func() error {
return c.doRequest("POST", "/httpAuth/app/rest/buildQueue", jsonQuery, &build)
})
if err != nil {
return nil, err
}
build.convertInputs()
return build, nil
}
func (c *Client) SearchBuild(locator string) ([]*Build, error) {
path := fmt.Sprintf("/httpAuth/app/rest/builds/?locator=%s&fields=count,build(*,tags(tag),triggered(*),properties(property),problemOccurrences(*,problemOccurrence(*)),testOccurrences(*,testOccurrence(*)),changes(*,change(*)))", locator)
respStruct := struct {
Count int
Build []*Build
}{}
retries := 8
err := withRetry(retries, func() error {
return c.doRequest("GET", path, nil, &respStruct)
})
if err != nil {
return nil, err
}
for _, build := range respStruct.Build {
build.convertInputs()
}
return respStruct.Build, nil
}
func (c *Client) GetBuild(buildID string) (*Build, error) {
path := fmt.Sprintf("/httpAuth/app/rest/builds/id:%s?fields=*,tags(tag),triggered(*),properties(property),problemOccurrences(*,problemOccurrence(*)),testOccurrences(*,testOccurrence(*)),changes(*,change(*))", buildID)
var build *Build
retries := 8
err := withRetry(retries, func() error {
return c.doRequest("GET", path, nil, &build)
})
if err != nil {
return nil, err
}
if build == nil {
return nil, errors.New("build not found")
}
return build, nil
}
func (c *Client) GetBuildID(buildTypeID, branchName, buildNumber string) (string, error) {
type builds struct {
Count int
Href string
NextHref string
Build []Build
}
path := fmt.Sprintf("/httpAuth/app/rest/buildTypes/id:%s/builds?locator=branch:%s,number:%s,count:1", buildTypeID, branchName, buildNumber)
var build *builds
retries := 8
err := withRetry(retries, func() error {
return c.doRequest("GET", path, nil, &build)
})
if err != nil {
return "ID not found", err
}
if build == nil {
return "ID not found", errors.New("build not found")
}
return fmt.Sprintf("%d", build.Build[0].ID), nil
}
func (c *Client) GetBuildProperties(buildID string) (map[string]string, error) {
path := fmt.Sprintf("/httpAuth/app/rest/builds/id:%s/resulting-properties", buildID)
var response struct {
Property []oneProperty `json:"property,omitempty"`
}
retries := 8
err := withRetry(retries, func() error {
return c.doRequest("GET", path, nil, &response)
})
if err != nil {
return nil, err
}
m := make(map[string]string)
for _, prop := range response.Property {
m[prop.Name] = prop.Value
}
return m, nil
}
func (c *Client) GetChanges(path string) ([]Change, error) {
var changes struct {
Change []Change
}
path += ",count:99999"
err := c.doRequest("GET", path, nil, &changes)
if err != nil {
return nil, err
}
if changes.Change == nil {
return nil, errors.New("changes not found")
}
return changes.Change, nil
}
func (c *Client) GetProblems(path string, count int64) ([]ProblemOccurrence, error) {
var problems struct {
Count int64
Default bool
ProblemOccurrence []ProblemOccurrence
}
path += fmt.Sprintf(",count:%v&fields=*,problemOccurrence(*,details)", count)
err := c.doRequest("GET", path, nil, &problems)
if err != nil {
return nil, err
}
if problems.ProblemOccurrence == nil {
return nil, errors.New("problemOccurrence list not found")
}
return problems.ProblemOccurrence, nil
}
func (c *Client) GetTests(path string, count int64, failingOnly bool, ignoreMuted bool) ([]TestOccurrence, error) {
var tests struct {
Count int64
HREF string
TestOccurrence []TestOccurrence
}
if ignoreMuted {
path += ",currentlyMuted:false"
}
if failingOnly {
path += ",status:FAILURE"
}
path += fmt.Sprintf(",count:%v", count)
err := c.doRequest("GET", path, nil, &tests)
if err != nil {
return nil, err
}
return tests.TestOccurrence, nil
}
func (c *Client) CancelBuild(buildID int64, comment string) error {
body := map[string]interface{}{
"buildCancelRequest": map[string]interface{}{
"comment": comment,
"readIntoQueue": true,
},
}
return c.doRequest("POST", fmt.Sprintf("/httpAuth/app/rest/id:%d", buildID), body, nil)
}
func (c *Client) GetBuildLog(buildID string) (string, error) {
cnt, err := c.doNotJSONRequest("GET", fmt.Sprintf("/httpAuth/downloadBuildLog.html?buildId=%s", buildID), nil)
buf := bytes.NewBuffer(cnt)
return buf.String(), err
}
func (c *Client) doRequest(method string, path string, data interface{}, v interface{}) error {
jsonCnt, err := c.doNotJSONRequest(method, path, data)
if err != nil {
return err
}
ioutil.WriteFile(fmt.Sprintf("/tmp/mama-%s.json", time.Now().Format("15h04m05.000")), jsonCnt, 0644)
if v != nil {
err = json.Unmarshal(jsonCnt, &v)
if err != nil {
return fmt.Errorf("json unmarshal: %s (%q)", err, truncate(string(jsonCnt), 1000))
}
}
return nil
}
func (c *Client) doNotJSONRequest(method string, path string, data interface{}) ([]byte, error) {
authURL := fmt.Sprintf("https://%s%s", c.host, path)
fmt.Printf("Sending request to %s\n", authURL)
var body io.Reader
if data != nil {
jsonReq, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("marshaling data: %s", err)
}
body = bytes.NewBuffer(jsonReq)
}
req, _ := http.NewRequest(method, authURL, body)
req.SetBasicAuth(c.username, c.password)
req.Header.Add("Accept", "application/json")
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func truncate(s string, l int) string {
if len(s) > l {
return s[:l]
}
return s
}
func withRetry(retries int, f func() error) (err error) {
for i := 0; i < retries; i++ {
err = f()
if err != nil {
log.Printf("Retry: %v / %v, error: %v\n", i, retries, err)
} else {
return
}
}
return
}