1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-10-30 23:57:50 +02:00

IntegrationArtifactDeploy Command (#2526)

* UpdateIntegrationArtifactConfiguration Command

* Fixes for codeclimate Check

* CommonStepsTest changes

* CodeReview Changes

* Git Patch

* Git Patch undo

* Code Review Comments

* code review fixes

* improve the error handling

* codeclimate fixes

* remove json parsing

* Error handling changes

* TestCase coverage fixes

* Refactoring Commands

* IntegrationArtifactDeploy Command

* Regenerate metadata_generated

* codereview fixes

* Code Review Fixes

* Code Review Fixes

Co-authored-by: Oliver Nocon <33484802+OliverNocon@users.noreply.github.com>
Co-authored-by: Oliver Feldmann <oliver.feldmann@sap.com>
This commit is contained in:
Mayur Belur Mohan
2021-01-22 20:25:50 +05:30
committed by GitHub
parent 3e0a2835fd
commit fe72b295d6
12 changed files with 79 additions and 61 deletions

View File

@@ -2,36 +2,37 @@ package cmd
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/SAP/jenkins-library/pkg/command"
cpi "github.com/SAP/jenkins-library/pkg/cpi"
"github.com/SAP/jenkins-library/pkg/cpi"
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"
)
type deployIntegrationArtifactUtils interface {
type integrationArtifactDeployUtils interface {
command.ExecRunner
// Add more methods here, or embed additional interfaces, or remove/replace as required.
// The deployIntegrationArtifactUtils interface should be descriptive of your runtime dependencies,
// The integrationArtifactDeployUtils interface should be descriptive of your runtime dependencies,
// i.e. include everything you need to be able to mock in tests.
// Unit tests shall be executable in parallel (not depend on global state), and don't (re-)test dependencies.
}
type deployIntegrationArtifactUtilsBundle struct {
type integrationArtifactDeployUtilsBundle struct {
*command.Command
// Embed more structs as necessary to implement methods or interfaces you add to deployIntegrationArtifactUtils.
// Embed more structs as necessary to implement methods or interfaces you add to integrationArtifactDeployUtils.
// Structs embedded in this way must each have a unique set of methods attached.
// If there is no struct which implements the method you need, attach the method to
// deployIntegrationArtifactUtilsBundle and forward to the implementation of the dependency.
// integrationArtifactDeployUtilsBundle and forward to the implementation of the dependency.
}
func newDeployIntegrationArtifactUtils() deployIntegrationArtifactUtils {
utils := deployIntegrationArtifactUtilsBundle{
func newIntegrationArtifactDeployUtils() integrationArtifactDeployUtils {
utils := integrationArtifactDeployUtilsBundle{
Command: &command.Command{},
}
// Reroute command output to logging framework
@@ -40,25 +41,26 @@ func newDeployIntegrationArtifactUtils() deployIntegrationArtifactUtils {
return &utils
}
func deployIntegrationArtifact(config deployIntegrationArtifactOptions, telemetryData *telemetry.CustomData) {
func integrationArtifactDeploy(config integrationArtifactDeployOptions, telemetryData *telemetry.CustomData) {
// Utils can be used wherever the command.ExecRunner interface is expected.
// It can also be used for example as a mavenExecRunner.
utils := newDeployIntegrationArtifactUtils()
utils := newIntegrationArtifactDeployUtils()
utils.Stdout(log.Writer())
httpClient := &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 be bubbled up until they reach the line below which will then stop execution
// through the log.Entry().Fatal() call leading to an os.Exit(1) in the end.
err := runDeployIntegrationArtifact(&config, telemetryData, httpClient)
err := runIntegrationArtifactDeploy(&config, telemetryData, httpClient)
if err != nil {
log.Entry().WithError(err).Fatal("step execution failed")
}
}
func runDeployIntegrationArtifact(config *deployIntegrationArtifactOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) error {
func runIntegrationArtifactDeploy(config *integrationArtifactDeployOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) error {
clientOptions := piperhttp.ClientOptions{}
httpClient.SetOptions(clientOptions)
header := make(http.Header)
@@ -86,13 +88,18 @@ func runDeployIntegrationArtifact(config *deployIntegrationArtifactOptions, tele
return errors.Errorf("did not retrieve a HTTP response")
}
if deployResp.StatusCode == 202 {
if deployResp.StatusCode == http.StatusAccepted {
log.Entry().
WithField("IntegrationFlowID", config.IntegrationFlowID).
Info("successfully deployed into CPI runtime")
return nil
}
responseBody, readErr := ioutil.ReadAll(deployResp.Body)
log.Entry().Errorf("a HTTP error occurred! Response Status Code: %v", deployResp.StatusCode)
if readErr != nil {
return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code : %v", deployResp.StatusCode)
}
log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", responseBody, deployResp.StatusCode)
return errors.Errorf("Integration Flow deployment failed, Response Status code: %v", deployResp.StatusCode)
}

View File

@@ -13,7 +13,7 @@ import (
"github.com/spf13/cobra"
)
type deployIntegrationArtifactOptions struct {
type integrationArtifactDeployOptions struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
IntegrationFlowID string `json:"integrationFlowId,omitempty"`
@@ -23,15 +23,15 @@ type deployIntegrationArtifactOptions struct {
OAuthTokenProviderURL string `json:"oAuthTokenProviderUrl,omitempty"`
}
// DeployIntegrationArtifactCommand Deploy a CPI integration flow
func DeployIntegrationArtifactCommand() *cobra.Command {
const STEP_NAME = "deployIntegrationArtifact"
// IntegrationArtifactDeployCommand Deploy a CPI integration flow
func IntegrationArtifactDeployCommand() *cobra.Command {
const STEP_NAME = "integrationArtifactDeploy"
metadata := deployIntegrationArtifactMetadata()
var stepConfig deployIntegrationArtifactOptions
metadata := integrationArtifactDeployMetadata()
var stepConfig integrationArtifactDeployOptions
var startTime time.Time
var createDeployIntegrationArtifactCmd = &cobra.Command{
var createIntegrationArtifactDeployCmd = &cobra.Command{
Use: STEP_NAME,
Short: "Deploy a CPI integration flow",
Long: `With this step you can deploy a integration flow artifact in to SAP Cloud Platform integration runtime using OData API.Learn more about the SAP Cloud Integration remote API for deploying an integration artifact [here](https://help.sap.com/viewer/368c481cd6954bdfa5d0435479fd4eaf/Cloud/en-US/08632076a1114bc1b6a1ecafef8f0178.html)`,
@@ -71,17 +71,17 @@ func DeployIntegrationArtifactCommand() *cobra.Command {
log.DeferExitHandler(handler)
defer handler()
telemetry.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
deployIntegrationArtifact(stepConfig, &telemetryData)
integrationArtifactDeploy(stepConfig, &telemetryData)
telemetryData.ErrorCode = "0"
log.Entry().Info("SUCCESS")
},
}
addDeployIntegrationArtifactFlags(createDeployIntegrationArtifactCmd, &stepConfig)
return createDeployIntegrationArtifactCmd
addIntegrationArtifactDeployFlags(createIntegrationArtifactDeployCmd, &stepConfig)
return createIntegrationArtifactDeployCmd
}
func addDeployIntegrationArtifactFlags(cmd *cobra.Command, stepConfig *deployIntegrationArtifactOptions) {
func addIntegrationArtifactDeployFlags(cmd *cobra.Command, stepConfig *integrationArtifactDeployOptions) {
cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "User to authenticate to the SAP Cloud Platform Integration Service")
cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password to authenticate to the SAP Cloud Platform Integration Service")
cmd.Flags().StringVar(&stepConfig.IntegrationFlowID, "integrationFlowId", os.Getenv("PIPER_integrationFlowId"), "Specifies the ID of the Integration Flow artifact")
@@ -99,10 +99,10 @@ func addDeployIntegrationArtifactFlags(cmd *cobra.Command, stepConfig *deployInt
}
// retrieve step metadata
func deployIntegrationArtifactMetadata() config.StepData {
func integrationArtifactDeployMetadata() config.StepData {
var theMetaData = config.StepData{
Metadata: config.StepMetadata{
Name: "deployIntegrationArtifact",
Name: "integrationArtifactDeploy",
Aliases: []config.Alias{},
Description: "Deploy a CPI integration flow",
},

View File

@@ -6,12 +6,12 @@ import (
"github.com/stretchr/testify/assert"
)
func TestDeployIntegrationArtifactCommand(t *testing.T) {
func TestIntegrationArtifactDeployCommand(t *testing.T) {
t.Parallel()
testCmd := DeployIntegrationArtifactCommand()
testCmd := IntegrationArtifactDeployCommand()
// only high level testing performed - details are tested in step generation procedure
assert.Equal(t, "deployIntegrationArtifact", testCmd.Use, "command name incorrect")
assert.Equal(t, "integrationArtifactDeploy", testCmd.Use, "command name incorrect")
}

View File

@@ -7,31 +7,29 @@ import (
"net/http"
"testing"
cpi "github.com/SAP/jenkins-library/pkg/cpi"
"github.com/SAP/jenkins-library/pkg/cpi"
piperhttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/mock"
"github.com/stretchr/testify/assert"
)
type deployIntegrationArtifactMockUtils struct {
type integrationArtifactDeployMockUtils struct {
*mock.ExecMockRunner
*mock.FilesMock
}
func newDeployIntegrationArtifactTestsUtils() deployIntegrationArtifactMockUtils {
utils := deployIntegrationArtifactMockUtils{
func newIntegrationArtifactDeployTestsUtils() integrationArtifactDeployMockUtils {
utils := integrationArtifactDeployMockUtils{
ExecMockRunner: &mock.ExecMockRunner{},
FilesMock: &mock.FilesMock{},
}
return utils
}
func TestRunDeployIntegrationArtifact(t *testing.T) {
func TestRunIntegrationArtifactDeploy(t *testing.T) {
t.Parallel()
t.Run("Successfull Integration Flow Deploy Test", func(t *testing.T) {
config := deployIntegrationArtifactOptions{
config := integrationArtifactDeployOptions{
Host: "https://demo",
OAuthTokenProviderURL: "https://demo/oauth/token",
Username: "demouser",
@@ -41,15 +39,24 @@ func TestRunDeployIntegrationArtifact(t *testing.T) {
Platform: "cf",
}
httpClient := httpMockCpis{CPIFunction: "DeployIntegrationDesigntimeArtifact", ResponseBody: ``, TestType: "Positive"}
httpClient := httpMockCpis{CPIFunction: "IntegrationArtifactDeploy", ResponseBody: ``, TestType: "Positive"}
err := runDeployIntegrationArtifact(&config, nil, &httpClient)
// assert
assert.NoError(t, err)
err := runIntegrationArtifactDeploy(&config, nil, &httpClient)
if assert.NoError(t, err) {
t.Run("check url", func(t *testing.T) {
assert.Equal(t, "https://demo/api/v1/DeployIntegrationDesigntimeArtifact?Id='flow1'&Version='1.0.1'", httpClient.URL)
})
t.Run("check method", func(t *testing.T) {
assert.Equal(t, "POST", httpClient.Method)
})
}
})
t.Run("Failed case of Integration Flow Deploy Test", func(t *testing.T) {
config := deployIntegrationArtifactOptions{
config := integrationArtifactDeployOptions{
Host: "https://demo",
OAuthTokenProviderURL: "https://demo/oauth/token",
Username: "demouser",
@@ -59,10 +66,10 @@ func TestRunDeployIntegrationArtifact(t *testing.T) {
Platform: "cf",
}
httpClient := httpMockCpis{CPIFunction: "DeployIntegrationDesigntimeArtifact", ResponseBody: ``, TestType: "Negative"}
httpClient := httpMockCpis{CPIFunction: "IntegrationArtifactDeploy", ResponseBody: ``, TestType: "Negative"}
err := runIntegrationArtifactDeploy(&config, nil, &httpClient)
err := runDeployIntegrationArtifact(&config, nil, &httpClient)
// assert
assert.EqualError(t, err, "HTTP POST request to https://demo/api/v1/DeployIntegrationDesigntimeArtifact?Id='flow1'&Version='1.0.1' failed with error: Internal Server Error")
})

View File

@@ -27,7 +27,6 @@ func GetAllStepMetadata() map[string]config.StepData {
"cloudFoundryDeleteService": cloudFoundryDeleteServiceMetadata(),
"cloudFoundryDeleteSpace": cloudFoundryDeleteSpaceMetadata(),
"cloudFoundryDeploy": cloudFoundryDeployMetadata(),
"deployIntegrationArtifact": deployIntegrationArtifactMetadata(),
"detectExecuteScan": detectExecuteScanMetadata(),
"fortifyExecuteScan": fortifyExecuteScanMetadata(),
"gctsCloneRepository": gctsCloneRepositoryMetadata(),
@@ -43,6 +42,7 @@ func GetAllStepMetadata() map[string]config.StepData {
"githubSetCommitStatus": githubSetCommitStatusMetadata(),
"gitopsUpdateDeployment": gitopsUpdateDeploymentMetadata(),
"hadolintExecute": hadolintExecuteMetadata(),
"integrationArtifactDeploy": integrationArtifactDeployMetadata(),
"jsonApplyPatch": jsonApplyPatchMetadata(),
"kanikoExecute": kanikoExecuteMetadata(),
"karmaExecuteTests": karmaExecuteTestsMetadata(),

View File

@@ -121,7 +121,7 @@ func Execute() {
rootCmd.AddCommand(CloudFoundryDeleteSpaceCommand())
rootCmd.AddCommand(VaultRotateSecretIdCommand())
rootCmd.AddCommand(TransportRequestUploadCTSCommand())
rootCmd.AddCommand(DeployIntegrationArtifactCommand())
rootCmd.AddCommand(IntegrationArtifactDeployCommand())
addRootFlags(rootCmd)
if err := rootCmd.Execute(); err != nil {

View File

@@ -15,7 +15,7 @@
Example configuration for the use in a `Jenkinsfile`.
```groovy
deployIntegrationArtifact script: this
integrationArtifactDeploy script: this
```
Example of a YAML configuration file (such as `.pipeline/config.yaml`).
@@ -23,7 +23,7 @@ Example of a YAML configuration file (such as `.pipeline/config.yaml`).
```yaml
steps:
<...>
deployIntegrationArtifact:
integrationArtifactDeploy:
cpiCredentialsId: 'MY_CPI_OAUTH_CREDENTIALSID_IN_JENKINS'
integrationFlowId: 'MY_INTEGRATION_FLOW_NAME'
integrationFlowVersion: 'MY_INTEGRATION_FLOW_VERSION'

View File

@@ -77,7 +77,6 @@ nav:
- containerExecuteStructureTests: steps/containerExecuteStructureTests.md
- containerPushToRegistry: steps/containerPushToRegistry.md
- debugReportArchive: steps/debugReportArchive.md
- deployIntegrationArtifact: steps/deployIntegrationArtifact.md
- detectExecuteScan: steps/detectExecuteScan.md
- dockerExecute: steps/dockerExecute.md
- dockerExecuteOnKubernetes: steps/dockerExecuteOnKubernetes.md
@@ -101,6 +100,7 @@ nav:
- handlePipelineStepErrors: steps/handlePipelineStepErrors.md
- healthExecuteCheck: steps/healthExecuteCheck.md
- influxWriteData: steps/influxWriteData.md
- integrationArtifactDeploy: steps/integrationArtifactDeploy.md
- jenkinsMaterializeLog: steps/jenkinsMaterializeLog.md
- kanikoExecute: steps/kanikoExecute.md
- karmaExecuteTests: steps/karmaExecuteTests.md

View File

@@ -13,13 +13,9 @@ import (
//GetCPIFunctionMockResponse -Generate mock response payload for different CPI functions
func GetCPIFunctionMockResponse(functionName, testType string) (*http.Response, error) {
switch functionName {
case "DeployIntegrationDesigntimeArtifact":
case "IntegrationArtifactDeploy":
if testType == "Positive" {
res := http.Response{
StatusCode: 202,
Body: ioutil.NopCloser(bytes.NewReader([]byte(``))),
}
return &res, nil
return GetEmptyHTTPResponseBody()
}
res := http.Response{
StatusCode: 500,
@@ -32,7 +28,6 @@ func GetCPIFunctionMockResponse(functionName, testType string) (*http.Response,
}`))),
}
return &res, errors.New("Internal Server Error")
default:
res := http.Response{
StatusCode: 404,
@@ -41,3 +36,12 @@ func GetCPIFunctionMockResponse(functionName, testType string) (*http.Response,
return &res, errors.New("Service not Found")
}
}
//GetEmptyHTTPResponseBody -Empty http respose body
func GetEmptyHTTPResponseBody() (*http.Response, error) {
res := http.Response{
StatusCode: 202,
Body: ioutil.NopCloser(bytes.NewReader([]byte(``))),
}
return &res, nil
}

View File

@@ -1,5 +1,5 @@
metadata:
name: deployIntegrationArtifact
name: integrationArtifactDeploy
description: Deploy a CPI integration flow
longDescription: |
With this step you can deploy a integration flow artifact in to SAP Cloud Platform integration runtime using OData API.Learn more about the SAP Cloud Integration remote API for deploying an integration artifact [here](https://help.sap.com/viewer/368c481cd6954bdfa5d0435479fd4eaf/Cloud/en-US/08632076a1114bc1b6a1ecafef8f0178.html)

View File

@@ -170,7 +170,7 @@ public class CommonStepsTest extends BasePiperTest{
'kanikoExecute', //implementing new golang pattern without fields
'gitopsUpdateDeployment', //implementing new golang pattern without fields
'vaultRotateSecretId', //implementing new golang pattern without fields
'deployIntegrationArtifact' //implementing new golang pattern without fields
'integrationArtifactDeploy', //implementing new golang pattern without fields
]
@Test

View File

@@ -1,7 +1,7 @@
import groovy.transform.Field
@Field String STEP_NAME = getClass().getName()
@Field String METADATA_FILE = 'metadata/deployIntegrationArtifact.yaml'
@Field String METADATA_FILE = 'metadata/integrationArtifactDeploy.yaml'
void call(Map parameters = [:]) {
List credentials = [