Skip to content

Commit

Permalink
Implement a synchronous purge endpoint
Browse files Browse the repository at this point in the history
- Added a new API endpoint `POST /deployments/<id>/purge[?force]`
- Added a purge command on CLI
- Added a PURGE_FAILED deployment status
  • Loading branch information
loicalbertin committed Jan 6, 2021
1 parent 5e1c9fb commit 947175b
Show file tree
Hide file tree
Showing 13 changed files with 330 additions and 54 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

### ENHANCEMENTS

* Add a new synchronous purge API endpoint ([GH-707](https://github.com/ystia/yorc/issues/707))
* Should be able to specify the type of volume when creating an openstack instance ([GH-703](https://github.com/ystia/yorc/issues/703))
* Support ssh connection retries ([GH-688](https://github.com/ystia/yorc/issues/688))
* Remove useless/cluttering logs ([GH-681](https://github.com/ystia/yorc/issues/681))
Expand Down
93 changes: 93 additions & 0 deletions commands/deployments/dep_purge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France.
//
// Licensed 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 deployments

import (
"encoding/json"
"io/ioutil"
"net/http"
"path"
"strconv"

"github.com/pkg/errors"
"github.com/spf13/cobra"

"github.com/ystia/yorc/v4/commands/httputil"
"github.com/ystia/yorc/v4/log"
"github.com/ystia/yorc/v4/rest"
)

func init() {
var force bool
var purgeCmd = &cobra.Command{
Use: "purge <id>",
Short: "purge a deployment",
Long: `Purge a deployment <id>. This deployment should be in UNDEPLOYED status.
If an error is encountered the purge process is stopped and the deployment status is set
to PURGE_FAILED.
A purge may be run in force mode. In this mode Yorc does not check if the deployment is in
UNDEPLOYED status or even if the deployment exist. Moreover, in force mode the purge process
doesn't fail-fast and try to delete as much as it can. An report with encountered errors is
produced at the end of the process.`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.Errorf("Expecting a deployment id (got %d parameters)", len(args))
}

client, err := httputil.GetClient(ClientConfig)
if err != nil {
httputil.ErrExit(err)
}
deploymentID := args[0]

return postPurgeRequest(client, deploymentID, force)

},
}
purgeCmd.Flags().BoolVarP(&force, "force", "f", false, "Force purge of a deployment ignoring states checks and any errors. This should be use with extrem caution to cleanup environment.")
DeploymentsCmd.AddCommand(purgeCmd)
}

func postPurgeRequest(client httputil.HTTPClient, deploymentID string, force bool) error {
request, err := client.NewRequest("POST", path.Join("/deployments", deploymentID, "purge"), nil)
if err != nil {
httputil.ErrExit(errors.Wrap(err, httputil.YorcAPIDefaultErrorMsg))
}

query := request.URL.Query()
if force {
query.Set("force", strconv.FormatBool(force))
}
request.URL.RawQuery = query.Encode()
request.Header.Add("Accept", "application/json")
log.Debugf("POST: %s", request.URL.String())

response, err := client.Do(request)
if err != nil {
httputil.ErrExit(errors.Wrap(err, httputil.YorcAPIDefaultErrorMsg))
}
defer response.Body.Close()

if response.StatusCode == http.StatusOK {
ioutil.ReadAll(response.Body)
return nil
}
var errs rest.Errors
bodyContent, _ := ioutil.ReadAll(response.Body)
json.Unmarshal(bodyContent, &errs)

return nil
}
2 changes: 1 addition & 1 deletion deployments/deployments.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func GetDeploymentStatus(ctx context.Context, deploymentID string) (DeploymentSt
return INITIAL, errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if !exist || value == "" {
return INITIAL, deploymentNotFound{deploymentID: deploymentID}
return INITIAL, errors.WithStack(deploymentNotFound{deploymentID: deploymentID})
}
return DeploymentStatusFromString(value, true)
}
Expand Down
1 change: 1 addition & 0 deletions deployments/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ UPDATE_IN_PROGRESS
UPDATED
UPDATE_FAILURE
PURGED
PURGE_FAILED
)
*/
type DeploymentStatus int
Expand Down
6 changes: 5 additions & 1 deletion deployments/structs_enum.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ require (
github.com/hashicorp/go-cleanhttp v0.5.1
github.com/hashicorp/go-hclog v0.8.0
github.com/hashicorp/go-memdb v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.0.0
github.com/hashicorp/go-multierror v1.1.0
github.com/hashicorp/go-plugin v1.0.0
github.com/hashicorp/go-rootcerts v1.0.0
github.com/hashicorp/serf v0.8.3 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqk
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-plugin v1.0.0 h1:/gQ1sNR8/LHpoxKRQq4PmLBuacfZb4tC93e9B30o/7c=
github.com/hashicorp/go-plugin v1.0.0/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY=
github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=
Expand Down
137 changes: 137 additions & 0 deletions internal/operations/op_purge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright 2019 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France.
//
// Licensed 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 operations

import (
"context"
"os"
"path"
"path/filepath"

"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"

"github.com/ystia/yorc/v4/deployments"
"github.com/ystia/yorc/v4/events"
"github.com/ystia/yorc/v4/helper/collections"
"github.com/ystia/yorc/v4/helper/consulutil"
"github.com/ystia/yorc/v4/tasks"
)

// PurgeDeployment allows to completely remove references of a deployment within yorc
//
// Forced purge do not stop on errors and try to delete the maximum of elements while normal purge stops on the first error.
// The error returned by this function may be multi-evaluated use the standard errors.Unwrap method to access individual errors.
//
// ignoreTasks allows to prevent removing a given list of tasks this is particularly useful when calling it within a task.
// This option will probably be transitory for Yorc 4.x before switching to a full synchronous purge model
func PurgeDeployment(ctx context.Context, deploymentID, filepathWorkingDirectory string, force bool, ignoreTasks ...string) error {

var finalError *multierror.Error

if !force {
status, err := deployments.GetDeploymentStatus(ctx, deploymentID)
if err != nil {
finalError = multierror.Append(finalError, err)
return finalError
}
if status != deployments.UNDEPLOYED {
finalError = multierror.Append(finalError, errors.Errorf("can't purge a deployment not in %q state, actual status is %q", deployments.UNDEPLOYED, status))
return finalError
}
}

// Set status to PURGE_IN_PROGRESS
err := deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_IN_PROGRESS)
if err != nil {
if !force {
finalError = multierror.Append(finalError, err)
return finalError
}
// In force mode this error could be ignored
}

kv := consulutil.GetKV()
// Remove from KV all tasks from the current target deployment, except this purge task
tasksList, err := deployments.GetDeploymentTaskList(ctx, deploymentID)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}
for _, tid := range tasksList {

if !collections.ContainsString(ignoreTasks, tid) {
err = tasks.DeleteTask(tid)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}
}
_, err = kv.DeleteTree(path.Join(consulutil.WorkflowsPrefix, tid)+"/", nil)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}
}
// Delete events tree corresponding to the deployment TaskExecution
err = events.PurgeDeploymentEvents(ctx, deploymentID)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}
// Delete logs tree corresponding to the deployment
err = events.PurgeDeploymentLogs(ctx, deploymentID)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}
// Remove the working directory of the current target deployment
overlayPath := filepath.Join(filepathWorkingDirectory, "deployments", deploymentID)
err = os.RemoveAll(overlayPath)
if err != nil {
err = errors.Wrapf(err, "failed to remove deployments artifacts stored on disk: %q", overlayPath)
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}

err = deployments.DeleteDeployment(ctx, deploymentID)
if err != nil {
finalError = multierror.Append(finalError, err)
if !force {
deployments.SetDeploymentStatus(ctx, deploymentID, deployments.PURGE_FAILED)
return finalError
}
}

return finalError.ErrorOrNil()
}
31 changes: 31 additions & 0 deletions rest/deployments.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ import (
"regexp"
"strconv"

"github.com/hashicorp/go-multierror"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"

"github.com/ystia/yorc/v4/deployments"
"github.com/ystia/yorc/v4/internal/operations"
"github.com/ystia/yorc/v4/log"
"github.com/ystia/yorc/v4/tasks"
)
Expand Down Expand Up @@ -397,3 +399,32 @@ func (s *Server) listDeploymentsHandler(w http.ResponseWriter, r *http.Request)
}
encodeJSONResponse(w, r, DeploymentsCollection{Deployments: deps})
}

func (s *Server) purgeDeploymentHandler(w http.ResponseWriter, r *http.Request) {
var params httprouter.Params
ctx := r.Context()
params = ctx.Value(paramsLookupKey).(httprouter.Params)
deploymentID := params.ByName("id")

errs := new(Errors)
forcePurge, err := getBoolQueryParam(r, "force")
if err != nil {
log.Panic(err)
}
err = operations.PurgeDeployment(ctx, deploymentID, s.config.WorkingDirectory, forcePurge)
if err != nil {
log.Printf("purge error for deployment: %q\n%v", deploymentID, err)
if merr, ok := err.(*multierror.Error); ok {
for _, err := range merr.Errors {
errs.Errors = append(errs.Errors, &Error{"internal_server_error", http.StatusInternalServerError, "Internal Server Error", err.Error()})
}
} else {
errs.Errors = append(errs.Errors, newInternalServerError(err))
}

}
if len(errs.Errors) > 0 {
w.WriteHeader(http.StatusInternalServerError)
}
encodeJSONResponse(w, r, errs)
}
1 change: 1 addition & 0 deletions rest/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ func (s *Server) registerHandlers() {
s.router.Post("/deployments/:id/workflows/:workflowName", commonHandlers.ThenFunc(s.newWorkflowHandler))
s.router.Get("/deployments/:id/workflows/:workflowName", commonHandlers.Append(acceptHandler(mimeTypeApplicationJSON)).ThenFunc(s.getWorkflowHandler))
s.router.Get("/deployments/:id/workflows", commonHandlers.Append(acceptHandler(mimeTypeApplicationJSON)).ThenFunc(s.listWorkflowsHandler))
s.router.Post("/deployments/:id/purge", commonHandlers.Append(acceptHandler(mimeTypeApplicationJSON)).ThenFunc(s.purgeDeploymentHandler))

s.router.Get("/registry/delegates", commonHandlers.Append(acceptHandler(mimeTypeApplicationJSON)).ThenFunc(s.listRegistryDelegatesHandler))
s.router.Get("/registry/implementations", commonHandlers.Append(acceptHandler(mimeTypeApplicationJSON)).ThenFunc(s.listRegistryImplementationsHandler))
Expand Down
Loading

0 comments on commit 947175b

Please sign in to comment.