2020-02-04 11:43:27 +01:00
package cmd
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/cookiejar"
2020-04-08 12:43:41 +02:00
"reflect"
"sort"
"strconv"
2020-02-04 11:43:27 +01:00
"strings"
"time"
2020-07-23 10:26:50 +02:00
"github.com/SAP/jenkins-library/pkg/abaputils"
2020-02-04 11:43:27 +01:00
"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"
)
2020-07-31 14:43:23 +02:00
func abapEnvironmentPullGitRepo ( options abapEnvironmentPullGitRepoOptions , telemetryData * telemetry . CustomData ) {
// for command execution use Command
c := command . Command { }
// reroute command output to logging framework
c . Stdout ( log . Writer ( ) )
c . Stderr ( log . Writer ( ) )
var autils = abaputils . AbapUtils {
Exec : & c ,
}
client := piperhttp . Client { }
// 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
// error situations should stop execution through log.Entry().Fatal() call which leads to an os.Exit(1) in the end
err := runAbapEnvironmentPullGitRepo ( & options , telemetryData , & autils , & client )
if err != nil {
log . Entry ( ) . WithError ( err ) . Fatal ( "step execution failed" )
}
}
func runAbapEnvironmentPullGitRepo ( options * abapEnvironmentPullGitRepoOptions , telemetryData * telemetry . CustomData , com abaputils . Communication , client piperhttp . Sender ) error {
2020-07-23 10:26:50 +02:00
// Mapping for options
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
2020-04-08 12:43:41 +02:00
// Determine the host, user and password, either via the input parameters or via a cloud foundry service key
2020-07-31 14:43:23 +02:00
connectionDetails , errorGetInfo := com . GetAbapCommunicationArrangementInfo ( subOptions , "/sap/opu/odata/sap/MANAGE_GIT_REPOSITORY/Pull" )
2020-04-08 12:43:41 +02:00
if errorGetInfo != nil {
2020-07-31 14:43:23 +02:00
return errors . Wrap ( errorGetInfo , "Parameters for the ABAP Connection not available" )
2020-02-04 11:43:27 +01:00
}
2020-04-08 12:43:41 +02:00
// Configuring the HTTP Client and CookieJar
2020-07-31 14:43:23 +02:00
2020-04-08 12:43:41 +02:00
cookieJar , errorCookieJar := cookiejar . New ( nil )
if errorCookieJar != nil {
2020-07-31 14:43:23 +02:00
return errors . Wrap ( errorCookieJar , "Could not create a Cookie Jar" )
2020-04-08 12:43:41 +02:00
}
2020-02-04 11:43:27 +01:00
clientOptions := piperhttp . ClientOptions {
2020-05-28 13:08:26 +02:00
MaxRequestDuration : 180 * time . Second ,
2020-03-23 15:02:22 +01:00
CookieJar : cookieJar ,
Username : connectionDetails . User ,
Password : connectionDetails . Password ,
2020-02-04 11:43:27 +01:00
}
client . SetOptions ( clientOptions )
2020-05-07 15:51:11 +02:00
pollIntervall := 10 * time . Second
2020-02-04 11:43:27 +01:00
2020-07-23 10:26:50 +02:00
log . Entry ( ) . Infof ( "Start pulling %v repositories" , len ( options . RepositoryNames ) )
for _ , repositoryName := range options . RepositoryNames {
2020-02-04 11:43:27 +01:00
2020-05-07 15:51:11 +02:00
log . Entry ( ) . Info ( "-------------------------" )
log . Entry ( ) . Info ( "Start pulling " + repositoryName )
log . Entry ( ) . Info ( "-------------------------" )
2020-02-04 11:43:27 +01:00
2020-05-07 15:51:11 +02:00
// Triggering the Pull of the repository into the ABAP Environment system
2020-07-31 14:43:23 +02:00
uriConnectionDetails , errorTriggerPull := triggerPull ( repositoryName , connectionDetails , client )
2020-05-07 15:51:11 +02:00
if errorTriggerPull != nil {
2020-07-31 14:43:23 +02:00
return errors . Wrapf ( errorTriggerPull , "Pull of '%s' failed on the ABAP System" , repositoryName )
2020-05-07 15:51:11 +02:00
}
// Polling the status of the repository import on the ABAP Environment system
2020-07-31 14:43:23 +02:00
status , errorPollEntity := pollEntity ( repositoryName , uriConnectionDetails , client , pollIntervall )
2020-05-07 15:51:11 +02:00
if errorPollEntity != nil {
2020-07-31 14:43:23 +02:00
return errors . Wrapf ( errorPollEntity , "Pull of '%s' failed on the ABAP System" , repositoryName )
2020-05-07 15:51:11 +02:00
}
if status == "E" {
2020-07-31 14:43:23 +02:00
return errors . New ( "Pull of " + repositoryName + " failed on the ABAP System" )
2020-05-07 15:51:11 +02:00
}
log . Entry ( ) . Info ( repositoryName + " was pulled successfully" )
}
log . Entry ( ) . Info ( "-------------------------" )
log . Entry ( ) . Info ( "All repositories were pulled successfully" )
2020-02-04 11:43:27 +01:00
return nil
}
2020-07-23 10:26:50 +02:00
func triggerPull ( repositoryName string , pullConnectionDetails abaputils . ConnectionDetailsHTTP , client piperhttp . Sender ) ( abaputils . ConnectionDetailsHTTP , error ) {
2020-02-04 11:43:27 +01:00
uriConnectionDetails := pullConnectionDetails
uriConnectionDetails . URL = ""
pullConnectionDetails . XCsrfToken = "fetch"
// Loging into the ABAP System - getting the x-csrf-token and cookies
2020-04-08 12:43:41 +02:00
resp , err := getHTTPResponse ( "HEAD" , pullConnectionDetails , nil , client )
2020-02-04 11:43:27 +01:00
if err != nil {
2020-04-08 12:43:41 +02:00
err = handleHTTPError ( resp , err , "Authentication on the ABAP system failed" , pullConnectionDetails )
2020-02-04 11:43:27 +01:00
return uriConnectionDetails , err
}
2020-03-17 10:54:48 +01:00
defer resp . Body . Close ( )
2020-02-04 11:43:27 +01:00
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . WithField ( "ABAP Endpoint" , pullConnectionDetails . URL ) . Info ( "Authentication on the ABAP system successfull" )
uriConnectionDetails . XCsrfToken = resp . Header . Get ( "X-Csrf-Token" )
pullConnectionDetails . XCsrfToken = uriConnectionDetails . XCsrfToken
// Trigger the Pull of a Repository
2020-05-07 15:51:11 +02:00
if repositoryName == "" {
2020-04-08 12:43:41 +02:00
return uriConnectionDetails , errors . New ( "An empty string was passed for the parameter 'repositoryName'" )
}
2020-05-07 15:51:11 +02:00
jsonBody := [ ] byte ( ` { "sc_name":" ` + repositoryName + ` "} ` )
2020-02-04 11:43:27 +01:00
resp , err = getHTTPResponse ( "POST" , pullConnectionDetails , jsonBody , client )
if err != nil {
2020-05-07 15:51:11 +02:00
err = handleHTTPError ( resp , err , "Could not pull the Repository / Software Component " + repositoryName , uriConnectionDetails )
2020-02-04 11:43:27 +01:00
return uriConnectionDetails , err
}
2020-03-17 10:54:48 +01:00
defer resp . Body . Close ( )
2020-05-07 15:51:11 +02:00
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . WithField ( "repositoryName" , repositoryName ) . Info ( "Triggered Pull of Repository / Software Component" )
2020-02-04 11:43:27 +01:00
// Parse Response
2020-07-23 10:26:50 +02:00
var body abaputils . PullEntity
2020-02-04 11:43:27 +01:00
var abapResp map [ string ] * json . RawMessage
2020-04-08 12:43:41 +02:00
bodyText , errRead := ioutil . ReadAll ( resp . Body )
if errRead != nil {
return uriConnectionDetails , err
}
2020-02-04 11:43:27 +01:00
json . Unmarshal ( bodyText , & abapResp )
json . Unmarshal ( * abapResp [ "d" ] , & body )
2020-07-23 10:26:50 +02:00
if reflect . DeepEqual ( abaputils . PullEntity { } , body ) {
2020-05-07 15:51:11 +02:00
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . WithField ( "repositoryName" , repositoryName ) . Error ( "Could not pull the Repository / Software Component" )
2020-04-08 12:43:41 +02:00
err := errors . New ( "Request to ABAP System not successful" )
2020-02-04 11:43:27 +01:00
return uriConnectionDetails , err
}
2020-04-08 12:43:41 +02:00
expandLog := "?$expand=to_Execution_log,to_Transport_log"
uriConnectionDetails . URL = body . Metadata . URI + expandLog
2020-02-04 11:43:27 +01:00
return uriConnectionDetails , nil
}
2020-07-23 10:26:50 +02:00
func pollEntity ( repositoryName string , connectionDetails abaputils . ConnectionDetailsHTTP , client piperhttp . Sender , pollIntervall time . Duration ) ( string , error ) {
2020-02-04 11:43:27 +01:00
log . Entry ( ) . Info ( "Start polling the status..." )
var status string = "R"
for {
var resp , err = getHTTPResponse ( "GET" , connectionDetails , nil , client )
if err != nil {
2020-05-07 15:51:11 +02:00
err = handleHTTPError ( resp , err , "Could not pull the Repository / Software Component " + repositoryName , connectionDetails )
2020-02-04 11:43:27 +01:00
return "" , err
}
2020-03-17 10:54:48 +01:00
defer resp . Body . Close ( )
2020-02-04 11:43:27 +01:00
// Parse response
2020-07-23 10:26:50 +02:00
var body abaputils . PullEntity
2020-02-04 11:43:27 +01:00
bodyText , _ := ioutil . ReadAll ( resp . Body )
var abapResp map [ string ] * json . RawMessage
json . Unmarshal ( bodyText , & abapResp )
json . Unmarshal ( * abapResp [ "d" ] , & body )
2020-07-23 10:26:50 +02:00
if reflect . DeepEqual ( abaputils . PullEntity { } , body ) {
2020-05-07 15:51:11 +02:00
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . WithField ( "repositoryName" , repositoryName ) . Error ( "Could not pull the Repository / Software Component" )
2020-02-04 11:43:27 +01:00
var err = errors . New ( "Request to ABAP System not successful" )
return "" , err
}
status = body . Status
2020-07-23 10:26:50 +02:00
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . Info ( "Pull Status: " + body . StatusDescription )
2020-02-04 11:43:27 +01:00
if body . Status != "R" {
2020-04-08 12:43:41 +02:00
printLogs ( body )
2020-02-04 11:43:27 +01:00
break
}
time . Sleep ( pollIntervall )
}
return status , nil
}
2020-07-23 10:26:50 +02:00
func getHTTPResponse ( requestType string , connectionDetails abaputils . ConnectionDetailsHTTP , body [ ] byte , client piperhttp . Sender ) ( * http . Response , error ) {
2020-02-04 11:43:27 +01:00
header := make ( map [ string ] [ ] string )
header [ "Content-Type" ] = [ ] string { "application/json" }
header [ "Accept" ] = [ ] string { "application/json" }
header [ "x-csrf-token" ] = [ ] string { connectionDetails . XCsrfToken }
req , err := client . SendRequest ( requestType , connectionDetails . URL , bytes . NewBuffer ( body ) , header , nil )
return req , err
}
2020-07-23 10:26:50 +02:00
func handleHTTPError ( resp * http . Response , err error , message string , connectionDetails abaputils . ConnectionDetailsHTTP ) error {
2020-03-17 10:54:48 +01:00
if resp == nil {
2020-04-08 12:43:41 +02:00
// Response is nil in case of a timeout
2020-03-17 10:54:48 +01:00
log . Entry ( ) . WithError ( err ) . WithField ( "ABAP Endpoint" , connectionDetails . URL ) . Error ( "Request failed" )
} else {
log . Entry ( ) . WithField ( "StatusCode" , resp . Status ) . Error ( message )
2020-04-08 12:43:41 +02:00
// Include the error message of the ABAP Environment system, if available
2020-07-23 10:26:50 +02:00
var abapErrorResponse abaputils . AbapError
2020-04-08 12:43:41 +02:00
bodyText , readError := ioutil . ReadAll ( resp . Body )
if readError != nil {
return readError
}
var abapResp map [ string ] * json . RawMessage
json . Unmarshal ( bodyText , & abapResp )
json . Unmarshal ( * abapResp [ "error" ] , & abapErrorResponse )
2020-07-23 10:26:50 +02:00
if ( abaputils . AbapError { } ) != abapErrorResponse {
2020-04-08 12:43:41 +02:00
log . Entry ( ) . WithField ( "ErrorCode" , abapErrorResponse . Code ) . Error ( abapErrorResponse . Message . Value )
abapError := errors . New ( abapErrorResponse . Code + " - " + abapErrorResponse . Message . Value )
err = errors . Wrap ( abapError , err . Error ( ) )
}
2020-03-17 10:54:48 +01:00
resp . Body . Close ( )
}
2020-04-08 12:43:41 +02:00
return err
}
2020-07-23 10:26:50 +02:00
func printLogs ( entity abaputils . PullEntity ) {
2020-04-08 12:43:41 +02:00
// Sort logs
sort . SliceStable ( entity . ToExecutionLog . Results , func ( i , j int ) bool {
return entity . ToExecutionLog . Results [ i ] . Index < entity . ToExecutionLog . Results [ j ] . Index
} )
sort . SliceStable ( entity . ToTransportLog . Results , func ( i , j int ) bool {
return entity . ToTransportLog . Results [ i ] . Index < entity . ToTransportLog . Results [ j ] . Index
} )
log . Entry ( ) . Info ( "-------------------------" )
log . Entry ( ) . Info ( "Transport Log" )
log . Entry ( ) . Info ( "-------------------------" )
for _ , logEntry := range entity . ToTransportLog . Results {
log . Entry ( ) . WithField ( "Timestamp" , convertTime ( logEntry . Timestamp ) ) . Info ( logEntry . Description )
}
log . Entry ( ) . Info ( "-------------------------" )
log . Entry ( ) . Info ( "Execution Log" )
log . Entry ( ) . Info ( "-------------------------" )
for _ , logEntry := range entity . ToExecutionLog . Results {
log . Entry ( ) . WithField ( "Timestamp" , convertTime ( logEntry . Timestamp ) ) . Info ( logEntry . Description )
}
log . Entry ( ) . Info ( "-------------------------" )
}
func convertTime ( logTimeStamp string ) time . Time {
// The ABAP Environment system returns the date in the following format: /Date(1585576807000+0000)/
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
2020-03-17 10:54:48 +01:00
}