Skip to content

Commit

Permalink
Merge pull request #402 from malinthaprasan/gitint
Browse files Browse the repository at this point in the history
APICTL + Git integration
  • Loading branch information
npamudika authored Jul 9, 2020
2 parents 82fbf38 + c07d795 commit 17e96ad
Show file tree
Hide file tree
Showing 31 changed files with 1,405 additions and 94 deletions.
14 changes: 1 addition & 13 deletions import-export-cli/cmd/deleteAPI.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"github.com/wso2/product-apim-tooling/import-export-cli/impl"
k8sUtils "github.com/wso2/product-apim-tooling/import-export-cli/operator/utils"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
"net/http"
)

var deleteAPIEnvironment string
Expand Down Expand Up @@ -78,18 +77,7 @@ func executeDeleteAPICmd(credential credentials.Credential) {
if err != nil {
utils.HandleErrorAndExit("Error while deleting API ", err)
}
// Print info on response
utils.Logf(utils.LogPrefixInfo+"ResponseStatus: %v\n", resp.Status())
if resp.StatusCode() == http.StatusOK {
// 200 OK
fmt.Println(deleteAPIName + " API deleted successfully!")
} else if resp.StatusCode() == http.StatusInternalServerError {
// 500 Internal Server Error
fmt.Println(string(resp.Body()))
} else {
// Neither 200 nor 500
fmt.Println("Error deleting API:", resp.Status(), "\n", string(resp.Body()))
}
impl.PrintDeleteAPIResponse(resp, err)
} else {
// Error deleting API
fmt.Println("Error getting OAuth tokens while deleting API:" + preCommandErr.Error())
Expand Down
17 changes: 2 additions & 15 deletions import-export-cli/cmd/deleteAPIProduct.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import (
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/credentials"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"

"net/http"
)

var deleteAPIProductEnvironment string
Expand Down Expand Up @@ -67,20 +65,9 @@ func executeDeleteAPIProductCmd(credential credentials.Credential) {
if preCommandErr == nil {
resp, err := impl.DeleteAPIProduct(accessToken, deleteAPIProductEnvironment, deleteAPIProductName, deleteAPIProductProvider)
if err != nil {
utils.HandleErrorAndExit("Error while deleting API Product ", err)
}
// Print info on response
utils.Logf(utils.LogPrefixInfo+"ResponseStatus: %v\n", resp.Status())
if resp.StatusCode() == http.StatusOK {
// 200 OK
fmt.Println(deleteAPIProductName + " API Product deleted successfully!")
} else if resp.StatusCode() == http.StatusInternalServerError {
// 500 Internal Server Error
fmt.Println(string(resp.Body()))
} else {
// Neither 200 nor 500
fmt.Println("Error deleting API Product:", resp.Status(), "\n", string(resp.Body()))
utils.HandleErrorAndExit("Error while deleting API Product", err)
}
impl.PrintDeleteAPIProductResponse(resp, err)
} else {
// Error deleting API Product
fmt.Println("Error getting OAuth tokens while deleting API Product:" + preCommandErr.Error())
Expand Down
17 changes: 2 additions & 15 deletions import-export-cli/cmd/deleteApp.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,10 @@ package cmd

import (
"fmt"
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/credentials"
"github.com/wso2/product-apim-tooling/import-export-cli/impl"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
"net/http"

"github.com/spf13/cobra"
)

var deleteAppEnvironment string
Expand Down Expand Up @@ -67,18 +65,7 @@ func executeDeleteAppCmd(credential credentials.Credential) {
if err != nil {
utils.HandleErrorAndExit("Error while deleting Application ", err)
}
// Print info on response
utils.Logf(utils.LogPrefixInfo + "ResponseStatus: %v\n", resp.Status())
if resp.StatusCode() == http.StatusOK {
// 200 OK
fmt.Println(deleteAppName + " Application deleted successfully!")
} else if resp.StatusCode() == http.StatusInternalServerError {
// 500 Internal Server Error
fmt.Println(string(resp.Body()))
} else {
// Neither 200 nor 500
fmt.Println("Error deleting Application:", resp.Status(), "\n", string(resp.Body()))
}
impl.PrintDeleteAppResponse(resp, err)
} else {
// Error deleting Application
fmt.Println("Error getting OAuth tokens while deleting Application:" + preCommandErr.Error())
Expand Down
23 changes: 1 addition & 22 deletions import-export-cli/cmd/importApp.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,10 @@
package cmd

import (
"fmt"
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/credentials"
"github.com/wso2/product-apim-tooling/import-export-cli/impl"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
"net/http"
)

var importAppFile string
Expand Down Expand Up @@ -69,30 +67,11 @@ func executeImportAppCmd(credential credentials.Credential) {
if err != nil {
utils.HandleErrorAndExit("Error getting OAuth Tokens", err)
}
resp, err := impl.ImportApplicationToEnv(accessToken, importAppEnvironment, importAppFile, importAppOwner,
_, err = impl.ImportApplicationToEnv(accessToken, importAppEnvironment, importAppFile, importAppOwner,
importAppUpdateApplication, preserveOwner, skipSubscriptions, importAppSkipKeys, importAppSkipCleanup)
if err != nil {
utils.HandleErrorAndExit("Error importing Application", err)
}

if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated {
// 200 OK or 201 Created
utils.Logln(utils.LogPrefixInfo+"Header:", resp.Header)
fmt.Println("Successfully imported Application!")
} else if resp.StatusCode == http.StatusMultiStatus {
// 207 Multi Status
fmt.Printf("\nPartially imported Application" +
"\nNOTE: One or more subscriptions were not imported due to unavailability of APIs/Tiers\n")
} else if resp.StatusCode == http.StatusUnauthorized {
// 401 Unauthorized
fmt.Println("Invalid Credentials or You may not have enough permission!")
} else if resp.StatusCode == http.StatusForbidden {
// 401 Unauthorized
fmt.Printf("Invalid Owner!" + "\nNOTE: Cross Tenant Imports are not allowed!\n")
} else {
fmt.Println("Error importing Application")
utils.Logln(utils.LogPrefixError + resp.Status)
}
}

func init() {
Expand Down
2 changes: 1 addition & 1 deletion import-export-cli/cmd/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
)

const removeCmdLiteral = "remove"
const removeCmdShortDesc = "Remove an environmnet"
const removeCmdShortDesc = "Remove an environment"
const removeCmdLongDesc = `Remove Environment and its related endpoints from the config file`

const removeCmdExamples = utils.ProjectName + ` ` + removeCmdLiteral + ` ` + removeEnvCmdLiteral + ` production`
Expand Down
47 changes: 47 additions & 0 deletions import-export-cli/cmd/vcs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package cmd

import (
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
)

// vcs command related usage Info
const vcsCmdLiteral = "vcs"
const vcsCmdShortDesc = "Checks status and deploys projects"
const vcsCmdLongDesc = `Checks status and deploys projects to the specified environment. In order to
use this command, 'git' must be installed in the system.'`
const vcsCmdExamples = utils.ProjectName + ` ` + vcsStatusCmdLiteral + ` ` + ` -e dev
` + utils.ProjectName + ` ` + deployCmdLiteral + ` -e dev`

// vcsCmd represents the vcs command
var VCSCmd = &cobra.Command{
Use: vcsCmdLiteral,
Short: vcsCmdShortDesc,
Long: vcsCmdLongDesc,
Example: vcsCmdExamples,
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + vcsCmdLiteral + " called")
},
}

func init() {
RootCmd.AddCommand(VCSCmd)
}
77 changes: 77 additions & 0 deletions import-export-cli/cmd/vcsDeploy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package cmd

import (
"fmt"
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/credentials"
"github.com/wso2/product-apim-tooling/import-export-cli/git"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
)

var flagVCSDeployEnvName string // name of the environment the project changes need to be deployed
var flagVCSDeploySkipRollback bool // specifies whether rolling back on error needs to be avoided

// deploy command related usage Info
const deployCmdLiteral = "deploy"
const deployCmdShortDesc = "Deploys projects to the specified environment"
const deployCmdLongDesc = `Deploys projects to the specified environment specified by --environment(-e).
Only the changed projects compared to the revision at the last successful deployment will be deployed.
If any project(s) got failed during the deployment, by default, the operation will rollback the environment to the last successful state. If this needs to be avoided, use --skipRollback=true
NOTE: --environment (-e) flag is mandatory`

const deployCmdExamples = utils.ProjectName + ` ` + deployCmdLiteral + ` -e dev
` + utils.ProjectName + ` ` + deployCmdLiteral + ` -e dev --skipRollback=true`

// deployCmd represents the deploy command
var DeployCmd = &cobra.Command{
Use: deployCmdLiteral,
Short: deployCmdShortDesc,
Long: deployCmdLongDesc,
Example: deployCmdExamples,
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + deployCmdLiteral + " called")
credential, err := getCredentials(flagVCSDeployEnvName)
if err != nil {
utils.HandleErrorAndExit("Error getting credentials", err)
}
accessOAuthToken, err := credentials.GetOAuthAccessToken(credential, flagVCSDeployEnvName)
if err != nil {
utils.HandleErrorAndExit("Error while getting an access token for deploying the project(s)", err)
}
failedProjects := git.DeployChangedFiles(accessOAuthToken, flagVCSDeployEnvName)
if failedProjects != nil && len(failedProjects) > 0 && flagVCSDeploySkipRollback == false {
fmt.Println("\nRolling back to the last successful revision as there are failures..")
git.Rollback(accessOAuthToken, flagVCSDeployEnvName)
utils.HandleErrorAndExit("There are project deployment failures. Rolled back to the last successful revision.", err)
}
},
}

func init() {
VCSCmd.AddCommand(DeployCmd)

DeployCmd.Flags().StringVarP(&flagVCSDeployEnvName, "environment", "e", "", "Name of the " +
"environment to deploy the project(s)")
DeployCmd.Flags().BoolVarP(&flagVCSDeploySkipRollback, "skipRollback", "", false,
"Specifies whether rolling back to the last successful revision during an error situation should be skipped")

_ = DeployCmd.MarkFlagRequired("environment")
}
89 changes: 89 additions & 0 deletions import-export-cli/cmd/vcsStatus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package cmd

import (
"fmt"
"github.com/spf13/cobra"
"github.com/wso2/product-apim-tooling/import-export-cli/git"
"github.com/wso2/product-apim-tooling/import-export-cli/specs/params"
"github.com/wso2/product-apim-tooling/import-export-cli/utils"
"strconv"
)

var flagVCSStatusEnvName string // name of the environment to be added

// push command related usage Info
const vcsStatusCmdLiteral = "status"
const vcsStatusCmdShortDesc = "Shows the list of projects that are ready to deploy"
const vcsStatusCmdLongDesc = `Shows the list of projects that are ready to deploy to the specified environment by --environment(-e)
NOTE: --environment (-e) flag is mandatory`

const vcsStatusCmdCmdExamples = utils.ProjectName + ` ` + vcsStatusCmdLiteral + ` ` + ` -e dev`

// pushCmd represents the push command
var VCSStatusCmd = &cobra.Command{
Use: vcsStatusCmdLiteral,
Short: vcsStatusCmdShortDesc,
Long: vcsStatusCmdLongDesc,
Example: vcsStatusCmdCmdExamples,
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + vcsStatusCmdLiteral + " called")
totalProjectsToUpdate, updatedProjectsPerType := git.GetStatus(flagVCSStatusEnvName, git.FromRevTypeLastAttempted)

if totalProjectsToUpdate == 0 {
fmt.Println("Everything is up-to-date")
return
}

fmt.Println("Projects to Update (" + strconv.Itoa(totalProjectsToUpdate) + ")");
printProjectsToUpdate(utils.ProjectTypeApi, updatedProjectsPerType[utils.ProjectTypeApi])
printProjectsToUpdate(utils.ProjectTypeApiProduct, updatedProjectsPerType[utils.ProjectTypeApiProduct])
printProjectsToUpdate(utils.ProjectTypeApplication, updatedProjectsPerType[utils.ProjectTypeApplication])
},
}

func printProjectsToUpdate(projectType string, projects []*params.ProjectParams) {
if len(projects) != 0 {
fmt.Println("\n" + projectType + "s (" + strconv.Itoa(len(projects)) + ") ...")
for i, projectParam := range projects {
var operation string
var failed string
if projectParam.Deleted {
operation = "[delete]"
} else {
operation = "[save]"
}
if projectParam.FailedDuringPreviousDeploy {
failed = "[failed]"
}
fmt.Println(strconv.Itoa(i+1) + ": " + operation + "\t" + failed + "\t" + projectParam.NickName +
": (" + projectParam.RelativePath + ")")
}
}
}

func init() {
VCSCmd.AddCommand(VCSStatusCmd)

VCSStatusCmd.Flags().StringVarP(&flagVCSStatusEnvName, "environment", "e", "", "Name of the " +
"environment to check the project(s) status")

_ = VCSStatusCmd.MarkFlagRequired("environment")
}
3 changes: 2 additions & 1 deletion import-export-cli/docs/apictl.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ apictl [flags]
* [apictl list](apictl_list.md) - List APIs/APIProducts/Applications in an environment or List the environments
* [apictl login](apictl_login.md) - Login to an API Manager
* [apictl logout](apictl_logout.md) - Logout to from an API Manager
* [apictl remove](apictl_remove.md) - Remove an environmnet
* [apictl remove](apictl_remove.md) - Remove an environment
* [apictl set](apictl_set.md) - Set configuration parameters
* [apictl uninstall](apictl_uninstall.md) - Uninstall an operator in the configured K8s cluster
* [apictl update](apictl_update.md) - Update an API to the kubernetes cluster
* [apictl vcs](apictl_vcs.md) - Checks status and deploys projects
* [apictl version](apictl_version.md) - Display Version on current apictl

2 changes: 1 addition & 1 deletion import-export-cli/docs/apictl_remove.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## apictl remove

Remove an environmnet
Remove an environment

### Synopsis

Expand Down
2 changes: 1 addition & 1 deletion import-export-cli/docs/apictl_remove_env.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ apictl remove env production

### SEE ALSO

* [apictl remove](apictl_remove.md) - Remove an environmnet
* [apictl remove](apictl_remove.md) - Remove an environment

Loading

0 comments on commit 17e96ad

Please sign in to comment.