forked from SAP/jenkins-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgctsRollback.go
304 lines (243 loc) · 8.43 KB
/
gctsRollback.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
package cmd
import (
"io/ioutil"
"net/http/cookiejar"
"net/url"
"github.com/Jeffail/gabs/v2"
"github.com/SAP/jenkins-library/pkg/command"
piperhttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/pkg/errors"
)
func gctsRollback(config gctsRollbackOptions, telemetryData *telemetry.CustomData) {
// for command execution use Command
c := command.Command{}
// reroute command output to logging framework
c.Stdout(log.Entry().Writer())
c.Stderr(log.Entry().Writer())
// for http calls import piperhttp "github.com/SAP/jenkins-library/pkg/http"
// and use a &piperhttp.Client{} in a custom system
// Example: step checkmarxExecuteScan.go
httpClient := &piperhttp.Client{}
// error situations should stop execution through log.Entry().Fatal() call which leads to an os.Exit(1) in the end
err := rollback(&config, telemetryData, &c, httpClient)
if err != nil {
log.Entry().WithError(err).Fatal("step execution failed")
}
}
func rollback(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, command command.ExecRunner, httpClient piperhttp.Sender) error {
cookieJar, cookieErr := cookiejar.New(nil)
if cookieErr != nil {
return cookieErr
}
clientOptions := piperhttp.ClientOptions{
CookieJar: cookieJar,
Username: config.Username,
Password: config.Password,
}
httpClient.SetOptions(clientOptions)
repoInfo, err := getRepoInfo(config, telemetryData, httpClient)
if err != nil {
return errors.Wrap(err, "could not get local repository data")
}
if repoInfo.Result.URL == "" {
return errors.Errorf("no remote repository URL configured")
}
if err != nil {
return errors.Wrap(err, "could not parse remote repository URL as valid URL")
}
var deployOptions gctsDeployOptions
if config.Commit != "" {
log.Entry().Infof("rolling back to specified commit %v", config.Commit)
deployOptions = gctsDeployOptions{
Username: config.Username,
Password: config.Password,
Host: config.Host,
Repository: config.Repository,
Client: config.Client,
Commit: config.Commit,
}
} else {
repoHistory, err := getRepoHistory(config, telemetryData, httpClient)
if err != nil {
return errors.Wrap(err, "could not retrieve repository commit history")
}
if repoHistory.Result[0].FromCommit != "" {
log.Entry().WithField("repository", config.Repository).Infof("rolling back to last active commit %v", repoHistory.Result[0].FromCommit)
deployOptions = gctsDeployOptions{
Username: config.Username,
Password: config.Password,
Host: config.Host,
Repository: config.Repository,
Client: config.Client,
Commit: repoHistory.Result[0].FromCommit,
}
} else {
return errors.Errorf("no commit to rollback to (fromCommit) could be identified from the repository commit history")
}
}
deployErr := pullByCommit(&deployOptions, telemetryData, command, httpClient)
if deployErr != nil {
return errors.Wrap(deployErr, "rollback commit failed")
}
log.Entry().
WithField("repository", config.Repository).
Infof("rollback was successful")
return nil
}
func getLastSuccessfullCommit(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender, githubURL *url.URL, commitList []string) (string, error) {
cookieJar, cookieErr := cookiejar.New(nil)
if cookieErr != nil {
return "", cookieErr
}
clientOptions := piperhttp.ClientOptions{
CookieJar: cookieJar,
}
if config.GithubPersonalAccessToken != "" {
clientOptions.Token = "Bearer " + config.GithubPersonalAccessToken
} else {
log.Entry().Warning("no GitHub personal access token was provided")
}
httpClient.SetOptions(clientOptions)
for _, commit := range commitList {
url := githubURL.Scheme + "://api." + githubURL.Host + "/repos" + githubURL.Path + "/commits/" + commit + "/status"
resp, httpErr := httpClient.SendRequest("GET", url, nil, nil, nil)
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if httpErr != nil {
return "", httpErr
} else if resp == nil {
return "", errors.New("did not retrieve a HTTP response")
}
bodyText, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return "", errors.Wrapf(readErr, "HTTP response body could not be read")
}
response, parsingErr := gabs.ParseJSON([]byte(bodyText))
if parsingErr != nil {
return "", errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText))
}
if status, ok := response.Path("state").Data().(string); ok && status == "success" {
log.Entry().
WithField("repository", config.Repository).
Infof("last successful commit was determined to be %v", commit)
return commit, nil
}
}
return "", errors.Errorf("no commit with status 'success' could be found")
}
func getCommits(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) ([]string, error) {
url := config.Host +
"/sap/bc/cts_abapvcs/repository/" + config.Repository +
"/getCommit?sap-client=" + config.Client
type commitsResponseBody struct {
Commits []struct {
ID string `json:"id"`
Author string `json:"author"`
AuthorMail string `json:"authorMail"`
Message string `json:"message"`
Description string `json:"description"`
Date string `json:"date"`
} `json:"commits"`
}
resp, httpErr := httpClient.SendRequest("GET", url, nil, nil, nil)
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if httpErr != nil {
return []string{}, httpErr
} else if resp == nil {
return []string{}, errors.New("did not retrieve a HTTP response")
}
var response commitsResponseBody
parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &response)
if parsingErr != nil {
return []string{}, parsingErr
}
commitList := []string{}
for _, commit := range response.Commits {
commitList = append(commitList, commit.ID)
}
return commitList, nil
}
func getRepoInfo(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) (*getRepoInfoResponseBody, error) {
var response getRepoInfoResponseBody
url := config.Host +
"/sap/bc/cts_abapvcs/repository/" + config.Repository +
"?sap-client=" + config.Client
resp, httpErr := httpClient.SendRequest("GET", url, nil, nil, nil)
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if httpErr != nil {
return &response, httpErr
} else if resp == nil {
return &response, errors.New("did not retrieve a HTTP response")
}
parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &response)
if parsingErr != nil {
return &response, parsingErr
}
return &response, nil
}
type getRepoInfoResponseBody struct {
Result struct {
Rid string `json:"rid"`
Name string `json:"name"`
Role string `json:"role"`
Type string `json:"type"`
Vsid string `json:"vsid"`
Status string `json:"status"`
Branch string `json:"branch"`
URL string `json:"url"`
Version string `json:"version"`
Objects int `json:"objects"`
CurrentCommit string `json:"currentCommit"`
Connection string `json:"connection"`
Config []struct {
Key string `json:"key"`
Value string `json:"value"`
} `json:"config"`
} `json:"result"`
}
func getRepoHistory(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) (*getRepoHistoryResponseBody, error) {
var response getRepoHistoryResponseBody
url := config.Host +
"/sap/bc/cts_abapvcs/repository/" + config.Repository +
"/getHistory?sap-client=" + config.Client
resp, httpErr := httpClient.SendRequest("GET", url, nil, nil, nil)
defer func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}()
if httpErr != nil {
return &response, httpErr
} else if resp == nil {
return &response, errors.New("did not retrieve a HTTP response")
}
parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &response)
if parsingErr != nil {
return &response, parsingErr
}
return &response, nil
}
type getRepoHistoryResponseBody struct {
Result []struct {
Rid string `json:"rid"`
CheckoutTime int64 `json:"checkoutTime"`
FromCommit string `json:"fromCommit"`
ToCommit string `json:"toCommit"`
Caller string `json:"caller"`
Request string `json:"request"`
Type string `json:"type"`
} `json:"result"`
}