forked from SAP/jenkins-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabapEnvironmentRunATCCheck.go
467 lines (399 loc) · 17.1 KB
/
abapEnvironmentRunATCCheck.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package cmd
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"reflect"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/abaputils"
"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/piperutils"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/pkg/errors"
)
func abapEnvironmentRunATCCheck(options abapEnvironmentRunATCCheckOptions, telemetryData *telemetry.CustomData) {
// Mapping for options
subOptions := convertATCOptions(&options)
c := &command.Command{}
c.Stdout(log.Entry().Writer())
c.Stderr(log.Entry().Writer())
var autils = abaputils.AbapUtils{
Exec: c,
}
var err error
client := piperhttp.Client{}
cookieJar, _ := cookiejar.New(nil)
clientOptions := piperhttp.ClientOptions{
CookieJar: cookieJar,
}
client.SetOptions(clientOptions)
var details abaputils.ConnectionDetailsHTTP
//If Host flag is empty read ABAP endpoint from Service Key instead. Otherwise take ABAP system endpoint from config instead
if err == nil {
details, err = autils.GetAbapCommunicationArrangementInfo(subOptions, "")
}
var resp *http.Response
//Fetch Xcrsf-Token
if err == nil {
credentialsOptions := piperhttp.ClientOptions{
Username: details.User,
Password: details.Password,
CookieJar: cookieJar,
}
client.SetOptions(credentialsOptions)
details.XCsrfToken, err = fetchXcsrfToken("GET", details, nil, &client)
}
if err == nil {
resp, err = triggerATCRun(options, details, &client)
}
if err == nil {
err = fetchAndPersistATCResults(resp, details, &client, options.AtcResultsFileName, options.GenerateHTML)
}
if err != nil {
log.Entry().WithError(err).Fatal("step execution failed")
}
log.Entry().Info("ATC run completed successfully. If there are any results from the respective run they will be listed in the logs above as well as being saved in the output .xml file")
}
func fetchAndPersistATCResults(resp *http.Response, details abaputils.ConnectionDetailsHTTP, client piperhttp.Sender, atcResultFileName string, generateHTML bool) error {
var err error
var abapEndpoint string
abapEndpoint = details.URL
location := resp.Header.Get("Location")
details.URL = abapEndpoint + location
location, err = pollATCRun(details, nil, client)
if err == nil {
details.URL = abapEndpoint + location
resp, err = getResultATCRun("GET", details, nil, client)
}
//Parse response
var body []byte
if err == nil {
body, err = ioutil.ReadAll(resp.Body)
}
if err == nil {
defer resp.Body.Close()
err = logAndPersistATCResult(body, atcResultFileName, generateHTML)
}
if err != nil {
return fmt.Errorf("Handling ATC result failed: %w", err)
}
return nil
}
func triggerATCRun(config abapEnvironmentRunATCCheckOptions, details abaputils.ConnectionDetailsHTTP, client piperhttp.Sender) (*http.Response, error) {
bodyString, err := buildATCRequestBody(config)
if err != nil {
return nil, err
}
var resp *http.Response
abapEndpoint := details.URL
log.Entry().Infof("Request Body: %s", bodyString)
var body = []byte(bodyString)
details.URL = abapEndpoint + "/sap/bc/adt/api/atc/runs?clientWait=false"
resp, err = runATC("POST", details, body, client)
return resp, err
}
func buildATCRequestBody(config abapEnvironmentRunATCCheckOptions) (bodyString string, err error) {
atcConfig, err := resolveATCConfiguration(config)
if err != nil {
return "", err
}
// Create string for the run parameters
variant := "ABAP_CLOUD_DEVELOPMENT_DEFAULT"
if atcConfig.CheckVariant != "" {
variant = atcConfig.CheckVariant
}
log.Entry().Infof("ATC Check Variant: %s", variant)
runParameters := ` checkVariant="` + variant + `"`
if atcConfig.Configuration != "" {
runParameters += ` configuration="` + atcConfig.Configuration + `"`
}
var objectSetString string
//check if OSL Objectset is present
if !reflect.DeepEqual(abaputils.ObjectSet{}, atcConfig.ObjectSet) {
objectSetString = abaputils.BuildOSLString(atcConfig.ObjectSet)
}
//if initial - check if ATC Object set is present
if objectSetString == "" && (len(atcConfig.Objects.Package) != 0 || len(atcConfig.Objects.SoftwareComponent) != 0) {
objectSetString, err = getATCObjectSet(atcConfig)
}
if objectSetString == "" {
return objectSetString, fmt.Errorf("Error while parsing ATC test run object set config. No object set has been provided. Please configure the objects you want to be checked for the respective test run")
}
bodyString = `<?xml version="1.0" encoding="UTF-8"?><atc:runparameters xmlns:atc="http://www.sap.com/adt/atc" xmlns:obj="http://www.sap.com/adt/objectset"` + runParameters + `>` + objectSetString + `</atc:runparameters>`
return bodyString, err
}
func resolveATCConfiguration(config abapEnvironmentRunATCCheckOptions) (atcConfig ATCConfiguration, err error) {
if config.AtcConfig != "" {
// Configuration defaults to ATC Config
log.Entry().Infof("ATC Configuration: %s", config.AtcConfig)
atcConfigFile, err := abaputils.ReadConfigFile(config.AtcConfig)
if err != nil {
return atcConfig, err
}
json.Unmarshal(atcConfigFile, &atcConfig)
return atcConfig, err
} else if config.Repositories != "" {
// Fallback / EasyMode is the Repositories configuration
log.Entry().Infof("ATC Configuration derived from: %s", config.Repositories)
repositories, err := abaputils.GetRepositories((&abaputils.RepositoriesConfig{Repositories: config.Repositories}))
if err != nil {
return atcConfig, err
}
for _, repository := range repositories {
atcConfig.Objects.SoftwareComponent = append(atcConfig.Objects.SoftwareComponent, SoftwareComponent{Name: repository.Name})
}
return atcConfig, nil
} else {
// Fail if no configuration is provided
return atcConfig, errors.New("No configuration provided - please provide either an ATC configuration file or a repository configuration file")
}
}
func getATCObjectSet(ATCConfig ATCConfiguration) (objectSet string, err error) {
objectSet += `<obj:objectSet>`
//Build SC XML body
if len(ATCConfig.Objects.SoftwareComponent) != 0 {
objectSet += "<obj:softwarecomponents>"
for _, s := range ATCConfig.Objects.SoftwareComponent {
objectSet += `<obj:softwarecomponent value="` + s.Name + `"/>`
}
objectSet += "</obj:softwarecomponents>"
}
//Build Package XML body
if len(ATCConfig.Objects.Package) != 0 {
objectSet += "<obj:packages>"
for _, s := range ATCConfig.Objects.Package {
objectSet += `<obj:package value="` + s.Name + `" includeSubpackages="` + strconv.FormatBool(s.IncludeSubpackages) + `"/>`
}
objectSet += "</obj:packages>"
}
objectSet += `</obj:objectSet>`
return objectSet, nil
}
func logAndPersistATCResult(body []byte, atcResultFileName string, generateHTML bool) (err error) {
if len(body) == 0 {
return fmt.Errorf("Parsing ATC result failed: %w", errors.New("Body is empty, can't parse empty body"))
}
responseBody := string(body)
log.Entry().Debugf("Response body: %s", responseBody)
if strings.HasPrefix(responseBody, "<html>") {
return errors.New("The Software Component could not be checked. Please make sure the respective Software Component has been cloned successfully on the system")
}
parsedXML := new(Result)
xml.Unmarshal([]byte(body), &parsedXML)
if len(parsedXML.Files) == 0 {
log.Entry().Info("There were no results from this run, most likely the checked Software Components are empty or contain no ATC findings")
}
err = ioutil.WriteFile(atcResultFileName, body, 0644)
if err == nil {
log.Entry().Infof("Writing %s file was successful", atcResultFileName)
var reports []piperutils.Path
reports = append(reports, piperutils.Path{Target: atcResultFileName, Name: "ATC Results", Mandatory: true})
for _, s := range parsedXML.Files {
for _, t := range s.ATCErrors {
log.Entry().Infof("%s in file '%s': %s in line %s found by %s", t.Severity, s.Key, t.Message, t.Line, t.Source)
}
}
if generateHTML == true {
htmlString := generateHTMLDocument(parsedXML)
htmlStringByte := []byte(htmlString)
atcResultHTMLFileName := strings.Trim(atcResultFileName, ".xml") + ".html"
err = ioutil.WriteFile(atcResultHTMLFileName, htmlStringByte, 0644)
if err == nil {
log.Entry().Info("Writing " + atcResultHTMLFileName + " file was successful")
reports = append(reports, piperutils.Path{Target: atcResultFileName, Name: "ATC Results HTML file", Mandatory: true})
}
}
piperutils.PersistReportsAndLinks("abapEnvironmentRunATCCheck", "", reports, nil)
}
if err != nil {
return fmt.Errorf("Writing results failed: %w", err)
}
return nil
}
func runATC(requestType string, details abaputils.ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (*http.Response, error) {
log.Entry().WithField("ABAP endpoint: ", details.URL).Info("triggering ATC run")
header := make(map[string][]string)
header["X-Csrf-Token"] = []string{details.XCsrfToken}
header["Content-Type"] = []string{"application/vnd.sap.atc.run.parameters.v1+xml; charset=utf-8;"}
resp, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil)
logResponseBody(resp)
if err != nil || (resp != nil && resp.StatusCode == 400) { //send request does not seem to produce error with StatusCode 400!!!
err = abaputils.HandleHTTPError(resp, err, "triggering ATC run failed with Status: "+resp.Status, details)
log.SetErrorCategory(log.ErrorService)
return resp, fmt.Errorf("triggering ATC run failed: %w", err)
}
defer resp.Body.Close()
return resp, err
}
func logResponseBody(resp *http.Response) error {
var bodyText []byte
var readError error
if resp != nil {
bodyText, readError = ioutil.ReadAll(resp.Body)
if readError != nil {
return readError
}
log.Entry().Infof("Response body: %s", bodyText)
}
return nil
}
func fetchXcsrfToken(requestType string, details abaputils.ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (string, error) {
log.Entry().WithField("ABAP Endpoint: ", details.URL).Debug("Fetching Xcrsf-Token")
details.URL += "/sap/bc/adt/api/atc/runs/00000000000000000000000000000000"
details.XCsrfToken = "fetch"
header := make(map[string][]string)
header["X-Csrf-Token"] = []string{details.XCsrfToken}
header["Accept"] = []string{"application/vnd.sap.atc.run.v1+xml"}
req, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil)
if err != nil {
log.SetErrorCategory(log.ErrorInfrastructure)
return "", fmt.Errorf("Fetching Xcsrf-Token failed: %w", err)
}
defer req.Body.Close()
token := req.Header.Get("X-Csrf-Token")
return token, err
}
func pollATCRun(details abaputils.ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (string, error) {
log.Entry().WithField("ABAP endpoint", details.URL).Info("Polling ATC run status")
for {
resp, err := getHTTPResponseATCRun("GET", details, nil, client)
if err != nil {
return "", fmt.Errorf("Getting HTTP response failed: %w", err)
}
bodyText, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("Reading response body failed: %w", err)
}
x := new(Run)
xml.Unmarshal(bodyText, &x)
log.Entry().WithField("StatusCode", resp.StatusCode).Info("Status: " + x.Status)
if x.Status == "Not Created" {
return "", err
}
if x.Status == "Completed" {
return x.Link[0].Key, err
}
if x.Status == "" {
return "", fmt.Errorf("Could not get any response from ATC poll: %w", errors.New("Status from ATC run is empty. Either it's not an ABAP system or ATC run hasn't started"))
}
time.Sleep(5 * time.Second)
}
}
func getHTTPResponseATCRun(requestType string, details abaputils.ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (*http.Response, error) {
header := make(map[string][]string)
header["Accept"] = []string{"application/vnd.sap.atc.run.v1+xml"}
resp, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil)
if err != nil {
return resp, fmt.Errorf("Getting ATC run status failed: %w", err)
}
return resp, err
}
func getResultATCRun(requestType string, details abaputils.ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (*http.Response, error) {
log.Entry().WithField("ABAP Endpoint: ", details.URL).Info("Getting ATC results")
header := make(map[string][]string)
header["x-csrf-token"] = []string{details.XCsrfToken}
header["Accept"] = []string{"application/vnd.sap.atc.checkstyle.v1+xml"}
resp, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil)
if err != nil {
return resp, fmt.Errorf("Getting ATC run results failed: %w", err)
}
return resp, err
}
func convertATCOptions(options *abapEnvironmentRunATCCheckOptions) abaputils.AbapEnvironmentOptions {
subOptions := abaputils.AbapEnvironmentOptions{}
subOptions.CfAPIEndpoint = options.CfAPIEndpoint
subOptions.CfServiceInstance = options.CfServiceInstance
subOptions.CfServiceKeyName = options.CfServiceKeyName
subOptions.CfOrg = options.CfOrg
subOptions.CfSpace = options.CfSpace
subOptions.Host = options.Host
subOptions.Password = options.Password
subOptions.Username = options.Username
return subOptions
}
func generateHTMLDocument(parsedXML *Result) (htmlDocumentString string) {
htmlDocumentString = `<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head><title>ATC Results</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><style>table,th,td {border: 1px solid black;border-collapse:collapse;}th,td{padding: 5px;text-align:left;font-size:medium;}</style></head><body><h1 style="text-align:left;font-size:large">ATC Results</h1><table style="width:100%"><tr><th>Severity</th><th>File</th><th>Message</th><th>Line</th><th>Checked by</th></tr>`
var htmlDocumentStringError, htmlDocumentStringWarning, htmlDocumentStringInfo, htmlDocumentStringDefault string
for _, s := range parsedXML.Files {
for _, t := range s.ATCErrors {
var trBackgroundColor string
if t.Severity == "error" {
trBackgroundColor = "rgba(227,85,0)"
htmlDocumentStringError += `<tr style="background-color: ` + trBackgroundColor + `">` + `<td>` + t.Severity + `</td>` + `<td>` + s.Key + `</td>` + `<td>` + t.Message + `</td>` + `<td style="text-align:center">` + t.Line + `</td>` + `<td>` + t.Source + `</td>` + `</tr>`
}
if t.Severity == "warning" {
trBackgroundColor = "rgba(255,175,0, 0.75)"
htmlDocumentStringWarning += `<tr style="background-color: ` + trBackgroundColor + `">` + `<td>` + t.Severity + `</td>` + `<td>` + s.Key + `</td>` + `<td>` + t.Message + `</td>` + `<td style="text-align:center">` + t.Line + `</td>` + `<td>` + t.Source + `</td>` + `</tr>`
}
if t.Severity == "info" {
trBackgroundColor = "rgba(255,175,0, 0.2)"
htmlDocumentStringInfo += `<tr style="background-color: ` + trBackgroundColor + `">` + `<td>` + t.Severity + `</td>` + `<td>` + s.Key + `</td>` + `<td>` + t.Message + `</td>` + `<td style="text-align:center">` + t.Line + `</td>` + `<td>` + t.Source + `</td>` + `</tr>`
}
if t.Severity != "info" && t.Severity != "warning" && t.Severity != "error" {
trBackgroundColor = "rgba(255,175,0, 0)"
htmlDocumentStringDefault += `<tr style="background-color: ` + trBackgroundColor + `">` + `<td>` + t.Severity + `</td>` + `<td>` + s.Key + `</td>` + `<td>` + t.Message + `</td>` + `<td style="text-align:center">` + t.Line + `</td>` + `<td>` + t.Source + `</td>` + `</tr>`
}
}
}
htmlDocumentString += htmlDocumentStringError + htmlDocumentStringWarning + htmlDocumentStringInfo + htmlDocumentStringDefault + `</table></body></html>`
return htmlDocumentString
}
//ATCConfiguration object for parsing yaml config of software components and packages
type ATCConfiguration struct {
CheckVariant string `json:"checkvariant,omitempty"`
Configuration string `json:"configuration,omitempty"`
Objects ATCObjects `json:"atcobjects"`
ObjectSet abaputils.ObjectSet `json:"objectset,omitempty"`
}
//ATCObjects in form of packages and software components to be checked
type ATCObjects struct {
Package []Package `json:"package"`
SoftwareComponent []SoftwareComponent `json:"softwarecomponent"`
}
//Package for ATC run to be checked
type Package struct {
Name string `json:"name"`
IncludeSubpackages bool `json:"includesubpackage"`
}
//SoftwareComponent for ATC run to be checked
type SoftwareComponent struct {
Name string `json:"name"`
}
//Run Object for parsing XML
type Run struct {
XMLName xml.Name `xml:"run"`
Status string `xml:"status,attr"`
Link []Link `xml:"link"`
}
//Link of XML object
type Link struct {
Key string `xml:"href,attr"`
Value string `xml:",chardata"`
}
//Result from ATC check for all files that were checked
type Result struct {
XMLName xml.Name `xml:"checkstyle"`
Files []File `xml:"file"`
}
//File that contains ATC check with error for checked file
type File struct {
Key string `xml:"name,attr"`
Value string `xml:",chardata"`
ATCErrors []ATCError `xml:"error"`
}
//ATCError with message
type ATCError struct {
Text string `xml:",chardata"`
Message string `xml:"message,attr"`
Source string `xml:"source,attr"`
Line string `xml:"line,attr"`
Severity string `xml:"severity,attr"`
}