-
Notifications
You must be signed in to change notification settings - Fork 582
/
abaputils.go
448 lines (387 loc) · 15.2 KB
/
abaputils.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
package abaputils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/cloudfoundry"
"github.com/SAP/jenkins-library/pkg/command"
piperhttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
)
// AbapUtils Struct
type AbapUtils struct {
Exec command.ExecRunner
Intervall time.Duration
}
/*
Communication for defining function used for communication
*/
type Communication interface {
GetAbapCommunicationArrangementInfo(options AbapEnvironmentOptions, oDataURL string) (ConnectionDetailsHTTP, error)
GetPollIntervall() time.Duration
}
// GetAbapCommunicationArrangementInfo function fetches the communcation arrangement information in SAP CP ABAP Environment
func (abaputils *AbapUtils) GetAbapCommunicationArrangementInfo(options AbapEnvironmentOptions, oDataURL string) (ConnectionDetailsHTTP, error) {
c := abaputils.Exec
var connectionDetails ConnectionDetailsHTTP
var error error
if options.Host != "" {
// Host, User and Password are directly provided -> check for host schema (double https)
match, err := regexp.MatchString(`^(https|HTTPS):\/\/.*`, options.Host)
if err != nil {
log.SetErrorCategory(log.ErrorConfiguration)
return connectionDetails, errors.Wrap(err, "Schema validation for host parameter failed. Check for https.")
}
var hostOdataURL = options.Host + oDataURL
if match {
connectionDetails.URL = hostOdataURL
connectionDetails.Host = options.Host
} else {
connectionDetails.URL = "https://" + hostOdataURL
connectionDetails.Host = "https://" + options.Host
}
connectionDetails.User = options.Username
connectionDetails.Password = options.Password
} else {
if options.CfAPIEndpoint == "" || options.CfOrg == "" || options.CfSpace == "" || options.CfServiceInstance == "" || options.CfServiceKeyName == "" {
var err = errors.New("Parameters missing. Please provide EITHER the Host of the ABAP server OR the Cloud Foundry ApiEndpoint, Organization, Space, Service Instance and a corresponding Service Key for the Communication Scenario SAP_COM_0510")
log.SetErrorCategory(log.ErrorConfiguration)
return connectionDetails, err
}
// Url, User and Password should be read from a cf service key
var abapServiceKey, error = ReadServiceKeyAbapEnvironment(options, c)
if error != nil {
return connectionDetails, errors.Wrap(error, "Read service key failed")
}
connectionDetails.Host = abapServiceKey.URL
connectionDetails.URL = abapServiceKey.URL + oDataURL
connectionDetails.User = abapServiceKey.Abap.Username
connectionDetails.Password = abapServiceKey.Abap.Password
}
return connectionDetails, error
}
// ReadServiceKeyAbapEnvironment from Cloud Foundry and returns it. Depending on user/developer requirements if he wants to perform further Cloud Foundry actions
func ReadServiceKeyAbapEnvironment(options AbapEnvironmentOptions, c command.ExecRunner) (AbapServiceKey, error) {
var abapServiceKeyV8 AbapServiceKeyV8
var abapServiceKey AbapServiceKey
var serviceKeyJSON string
var err error
cfconfig := cloudfoundry.ServiceKeyOptions{
CfAPIEndpoint: options.CfAPIEndpoint,
CfOrg: options.CfOrg,
CfSpace: options.CfSpace,
CfServiceInstance: options.CfServiceInstance,
CfServiceKeyName: options.CfServiceKeyName,
Username: options.Username,
Password: options.Password,
}
cf := cloudfoundry.CFUtils{Exec: c}
serviceKeyJSON, err = cf.ReadServiceKey(cfconfig)
if err != nil {
// Executing cfReadServiceKeyScript failed
return abapServiceKeyV8.Credentials, err
}
// Depending on the cf cli version, the service key may be returned in a different format. For compatibility reason, both formats are supported
unmarshalErrorV8 := json.Unmarshal([]byte(serviceKeyJSON), &abapServiceKeyV8)
if abapServiceKeyV8 == (AbapServiceKeyV8{}) {
if unmarshalErrorV8 != nil {
log.Entry().Debug(unmarshalErrorV8.Error())
}
log.Entry().Debug("Could not parse the service key in the cf cli v8 format.")
} else {
log.Entry().Info("Service Key read successfully")
return abapServiceKeyV8.Credentials, nil
}
unmarshalError := json.Unmarshal([]byte(serviceKeyJSON), &abapServiceKey)
if abapServiceKey == (AbapServiceKey{}) {
if unmarshalError != nil {
log.Entry().Debug(unmarshalError.Error())
}
log.Entry().Debug("Could not parse the service key in the cf cli v7 format.")
} else {
log.Entry().Info("Service Key read successfully")
return abapServiceKey, nil
}
log.SetErrorCategory(log.ErrorInfrastructure)
return abapServiceKeyV8.Credentials, errors.New("Parsing the service key failed for all supported formats. Service key is empty")
}
/*
GetPollIntervall returns the specified intervall from AbapUtils or a default value of 10 seconds
*/
func (abaputils *AbapUtils) GetPollIntervall() time.Duration {
if abaputils.Intervall != 0 {
return abaputils.Intervall
}
return 10 * time.Second
}
/*
ReadCOnfigFile reads a file from a specific path and returns the json string as []byte
*/
func ReadConfigFile(path string) (file []byte, err error) {
filelocation, err := filepath.Glob(path)
if err != nil {
return nil, err
}
if len(filelocation) == 0 {
return nil, errors.New("Could not find " + path)
}
filename, err := filepath.Abs(filelocation[0])
if err != nil {
return nil, err
}
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
var jsonFile []byte
jsonFile, err = yaml.YAMLToJSON(yamlFile)
return jsonFile, err
}
// GetHTTPResponse wraps the SendRequest function of piperhttp
func GetHTTPResponse(requestType string, connectionDetails ConnectionDetailsHTTP, body []byte, client piperhttp.Sender) (*http.Response, error) {
log.Entry().Debugf("Request body: %s", string(body))
log.Entry().Debugf("Request user: %s", connectionDetails.User)
header := make(map[string][]string)
header["Content-Type"] = []string{"application/json"}
header["Accept"] = []string{"application/json"}
header["x-csrf-token"] = []string{connectionDetails.XCsrfToken}
httpResponse, err := client.SendRequest(requestType, connectionDetails.URL, bytes.NewBuffer(body), header, nil)
return httpResponse, err
}
// HandleHTTPError handles ABAP error messages which can occur when using OData services
//
// The point of this function is to enrich the error received from a HTTP Request (which is passed as a parameter to this function).
// Further error details may be present in the response body of the HTTP response.
// If the response body is parseable, the included details are wrapped around the original error from the HTTP repsponse.
// If this is not possible, the original error is returned.
func HandleHTTPError(resp *http.Response, err error, message string, connectionDetails ConnectionDetailsHTTP) (string, error) {
var errorText string
var errorCode string
var parsingError error
if resp == nil {
// Response is nil in case of a timeout
log.Entry().WithError(err).WithField("ABAP Endpoint", connectionDetails.URL).Error("Request failed")
match, _ := regexp.MatchString(".*EOF$", err.Error())
if match {
AddDefaultDashedLine(1)
log.Entry().Infof("%s", "A connection could not be established to the ABAP system. The typical root cause is the network configuration (firewall, IP allowlist, etc.)")
AddDefaultDashedLine(1)
}
log.Entry().Infof("Error message: %s,", err.Error())
} else {
defer resp.Body.Close()
log.Entry().WithField("StatusCode", resp.Status).WithField("User", connectionDetails.User).WithField("URL", connectionDetails.URL).Error(message)
errorText, errorCode, parsingError = GetErrorDetailsFromResponse(resp)
if parsingError != nil {
return "", err
}
abapError := errors.New(fmt.Sprintf("%s - %s", errorCode, errorText))
err = errors.Wrap(abapError, err.Error())
}
return errorCode, err
}
func GetErrorDetailsFromResponse(resp *http.Response) (errorString string, errorCode string, err error) {
// Include the error message of the ABAP Environment system, if available
var abapErrorResponse AbapError
bodyText, readError := io.ReadAll(resp.Body)
if readError != nil {
return "", "", readError
}
var abapResp map[string]*json.RawMessage
errUnmarshal := json.Unmarshal(bodyText, &abapResp)
if errUnmarshal != nil {
return "", "", errUnmarshal
}
if _, ok := abapResp["error"]; ok {
json.Unmarshal(*abapResp["error"], &abapErrorResponse)
if (AbapError{}) != abapErrorResponse {
log.Entry().WithField("ErrorCode", abapErrorResponse.Code).Debug(abapErrorResponse.Message.Value)
return abapErrorResponse.Message.Value, abapErrorResponse.Code, nil
}
}
return "", "", errors.New("Could not parse the JSON error response")
}
// ConvertTime formats an ABAP timestamp string from format /Date(1585576807000+0000)/ into a UNIX timestamp and returns it
func ConvertTime(logTimeStamp string) time.Time {
seconds := strings.TrimPrefix(strings.TrimSuffix(logTimeStamp, "000+0000)/"), "/Date(")
n, error := strconv.ParseInt(seconds, 10, 64)
if error != nil {
return time.Unix(0, 0).UTC()
}
t := time.Unix(n, 0).UTC()
return t
}
// AddDefaultDashedLine adds 25 dashes
func AddDefaultDashedLine(j int) {
for i := 1; i <= j; i++ {
log.Entry().Infof(strings.Repeat("-", 25))
}
}
// AddDefaultDebugLine adds 25 dashes in debug
func AddDebugDashedLine() {
log.Entry().Debugf(strings.Repeat("-", 25))
}
/*******************************
* Structs for specific steps *
*******************************/
// AbapEnvironmentPullGitRepoOptions struct for the PullGitRepo piper step
type AbapEnvironmentPullGitRepoOptions struct {
AbapEnvOptions AbapEnvironmentOptions
RepositoryNames []string `json:"repositoryNames,omitempty"`
}
// AbapEnvironmentCheckoutBranchOptions struct for the CheckoutBranch piper step
type AbapEnvironmentCheckoutBranchOptions struct {
AbapEnvOptions AbapEnvironmentOptions
RepositoryName string `json:"repositoryName,omitempty"`
}
// AbapEnvironmentRunATCCheckOptions struct for the RunATCCheck piper step
type AbapEnvironmentRunATCCheckOptions struct {
AbapEnvOptions AbapEnvironmentOptions
AtcConfig string `json:"atcConfig,omitempty"`
}
/********************************
* Structs for ABAP in general *
********************************/
// AbapEnvironmentOptions contains cloud foundry fields and the host parameter for connections to ABAP Environment instances
type AbapEnvironmentOptions struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Host string `json:"host,omitempty"`
CfAPIEndpoint string `json:"cfApiEndpoint,omitempty"`
CfOrg string `json:"cfOrg,omitempty"`
CfSpace string `json:"cfSpace,omitempty"`
CfServiceInstance string `json:"cfServiceInstance,omitempty"`
CfServiceKeyName string `json:"cfServiceKeyName,omitempty"`
}
// AbapMetadata contains the URI of metadata files
type AbapMetadata struct {
URI string `json:"uri"`
}
// ConnectionDetailsHTTP contains fields for HTTP connections including the XCSRF token
type ConnectionDetailsHTTP struct {
Host string
User string `json:"user"`
Password string `json:"password"`
URL string `json:"url"`
XCsrfToken string `json:"xcsrftoken"`
}
// AbapError contains the error code and the error message for ABAP errors
type AbapError struct {
Code string `json:"code"`
Message AbapErrorMessage `json:"message"`
}
// AbapErrorMessage contains the lanuage and value fields for ABAP errors
type AbapErrorMessage struct {
Lang string `json:"lang"`
Value string `json:"value"`
}
// AbapServiceKeyV8 contains the new format of an ABAP service key
type AbapServiceKeyV8 struct {
Credentials AbapServiceKey `json:"credentials"`
}
// AbapServiceKey contains information about an ABAP service key
type AbapServiceKey struct {
SapCloudService string `json:"sap.cloud.service"`
URL string `json:"url"`
SystemID string `json:"systemid"`
Abap AbapConnection `json:"abap"`
Binding AbapBinding `json:"binding"`
PreserveHostHeader bool `json:"preserve_host_header"`
}
// AbapConnection contains information about the ABAP connection for the ABAP endpoint
type AbapConnection struct {
Username string `json:"username"`
Password string `json:"password"`
CommunicationScenarioID string `json:"communication_scenario_id"`
CommunicationArrangementID string `json:"communication_arrangement_id"`
CommunicationSystemID string `json:"communication_system_id"`
CommunicationInboundUserID string `json:"communication_inbound_user_id"`
CommunicationInboundUserAuthMode string `json:"communication_inbound_user_auth_mode"`
}
// AbapBinding contains information about service binding in Cloud Foundry
type AbapBinding struct {
ID string `json:"id"`
Type string `json:"type"`
Version string `json:"version"`
Env string `json:"env"`
}
/********************************
* Testing with a client mock *
********************************/
// ClientMock contains information about the client mock
type ClientMock struct {
Token string
Body string
BodyList []string
StatusCode int
Error error
NilResponse bool
ErrorInsteadOfDump bool
ErrorList []error
}
// SetOptions sets clientOptions for a client mock
func (c *ClientMock) SetOptions(opts piperhttp.ClientOptions) {}
// SendRequest sets a HTTP response for a client mock
func (c *ClientMock) SendRequest(method, url string, bdy io.Reader, hdr http.Header, cookies []*http.Cookie) (*http.Response, error) {
if c.NilResponse {
return nil, c.Error
}
var body []byte
var responseError error
if c.Body != "" {
body = []byte(c.Body)
responseError = c.Error
} else {
if c.ErrorInsteadOfDump && len(c.BodyList) == 0 {
return nil, errors.New("No more bodies in the list")
}
bodyString := c.BodyList[len(c.BodyList)-1]
c.BodyList = c.BodyList[:len(c.BodyList)-1]
body = []byte(bodyString)
if len(c.ErrorList) == 0 {
responseError = c.Error
} else {
responseError = c.ErrorList[len(c.ErrorList)-1]
c.ErrorList = c.ErrorList[:len(c.ErrorList)-1]
}
}
header := http.Header{}
header.Set("X-Csrf-Token", c.Token)
return &http.Response{
StatusCode: c.StatusCode,
Header: header,
Body: io.NopCloser(bytes.NewReader(body)),
}, responseError
}
// DownloadFile : Empty file download
func (c *ClientMock) DownloadFile(url, filename string, header http.Header, cookies []*http.Cookie) error {
return nil
}
// AUtilsMock mock
type AUtilsMock struct {
ReturnedConnectionDetailsHTTP ConnectionDetailsHTTP
ReturnedError error
}
// GetAbapCommunicationArrangementInfo mock
func (autils *AUtilsMock) GetAbapCommunicationArrangementInfo(options AbapEnvironmentOptions, oDataURL string) (ConnectionDetailsHTTP, error) {
return autils.ReturnedConnectionDetailsHTTP, autils.ReturnedError
}
// GetPollIntervall mock
func (autils *AUtilsMock) GetPollIntervall() time.Duration {
return 1 * time.Microsecond
}
// Cleanup to reset AUtilsMock
func (autils *AUtilsMock) Cleanup() {
autils.ReturnedConnectionDetailsHTTP = ConnectionDetailsHTTP{}
autils.ReturnedError = nil
}