Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: set release phase to failed if ctrl+C #1137

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 46 additions & 31 deletions pkg/cmd/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package apply

import (
"errors"
"fmt"
"io"
"strings"
Expand All @@ -36,6 +37,7 @@
"kusionstack.io/kusion/pkg/log"
"kusionstack.io/kusion/pkg/util/i18n"
"kusionstack.io/kusion/pkg/util/pretty"
"kusionstack.io/kusion/pkg/util/signal"
"kusionstack.io/kusion/pkg/util/terminal"
)

Expand Down Expand Up @@ -168,52 +170,65 @@
}

// Run executes the `apply` command.
func (o *ApplyOptions) Run() (err error) {
// update release to succeeded or failed
var storage release.Storage
var rel *apiv1.Release
releaseCreated := false
defer func() {
if !releaseCreated {
return
func (o *ApplyOptions) Run() error {
// create release
storage, err := o.Backend.ReleaseStorage(o.RefProject.Name, o.RefWorkspace.Name)
if err != nil {
return err
}
rel, err := release.NewApplyRelease(storage, o.RefProject.Name, o.RefStack.Name, o.RefWorkspace.Name)
if err != nil {
return err
}
if !o.DryRun {
if err = storage.Create(rel); err != nil {
return err
}
}

errCh := make(chan error, 1)
defer close(errCh)

// wait for the SIGTERM or SIGINT
go func() {
stopCh := signal.SetupSignalHandler()
<-stopCh
errCh <- errors.New("receive SIGTERM or SIGINT, exit cmd")
}()

// run apply command
go func() {
errCh <- o.run(rel, storage)
}()

// update release phase to succeeded or failed
select {

Check failure on line 205 in pkg/cmd/apply/apply.go

View workflow job for this annotation

GitHub Actions / Golang Lint

S1000: should use a simple channel send/receive instead of `select` with a single case (gosimple)
case err = <-errCh:
if err != nil {
rel.Phase = apiv1.ReleasePhaseFailed
_ = release.UpdateApplyRelease(storage, rel, o.DryRun)
} else {
rel.Phase = apiv1.ReleasePhaseSucceeded
err = release.UpdateApplyRelease(storage, rel, o.DryRun)
}
return err
}
}

// run executes `apply` command after the release is created.
func (o *ApplyOptions) run(rel *apiv1.Release, storage release.Storage) (err error) {
// update release to succeeded or failed
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("goroutine panic: %v", p)
}
}()

// set no style
if o.NoStyle {
pterm.DisableStyling()
}

// create release
storage, err = o.Backend.ReleaseStorage(o.RefProject.Name, o.RefWorkspace.Name)
if err != nil {
return
}
rel, err = release.NewApplyRelease(storage, o.RefProject.Name, o.RefStack.Name, o.RefWorkspace.Name)
if err != nil {
return
}
if !o.DryRun {
if err = storage.Create(rel); err != nil {
return
}
releaseCreated = true
}

// build parameters
parameters := make(map[string]string)
for _, value := range o.PreviewOptions.Values {
parts := strings.SplitN(value, "=", 2)
parameters[parts[0]] = parts[1]
}

// generate Spec
spec, err := generate.GenerateSpecWithSpinner(o.RefProject, o.RefStack, o.RefWorkspace, nil, o.UI, o.NoStyle)
if err != nil {
Expand Down
62 changes: 38 additions & 24 deletions pkg/cmd/destroy/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package destroy

import (
"errors"
"fmt"
"os"
"strings"
Expand All @@ -36,6 +37,7 @@
"kusionstack.io/kusion/pkg/engine/runtime/terraform"
"kusionstack.io/kusion/pkg/log"
"kusionstack.io/kusion/pkg/util/pretty"
"kusionstack.io/kusion/pkg/util/signal"
"kusionstack.io/kusion/pkg/util/terminal"
)

Expand Down Expand Up @@ -155,39 +157,51 @@
}

// Run executes the `delete` command.
func (o *DestroyOptions) Run() (err error) {
// update release to succeeded or failed
var storage release.Storage
var rel *apiv1.Release
releaseCreated := false
defer func() {
if !releaseCreated {
return
}
func (o *DestroyOptions) Run() error {
storage, err := o.Backend.ReleaseStorage(o.RefProject.Name, o.RefWorkspace.Name)
if err != nil {
return err
}
rel, err := release.CreateDestroyRelease(storage, o.RefProject.Name, o.RefStack.Name, o.RefWorkspace.Name)
if err != nil {
return err
}
if len(rel.Spec.Resources) == 0 {
pterm.Println(pterm.Green("No managed resources to destroy"))
return nil
}

errCh := make(chan error, 1)
defer close(errCh)

// wait for the SIGTERM or SIGINT
go func() {
stopCh := signal.SetupSignalHandler()
<-stopCh
errCh <- errors.New("receive SIGTERM or SIGINT, exit cmd")
}()

// run destroy command
go func() {
errCh <- o.run(rel, storage)
}()

// update release phase to succeeded or failed
select {

Check failure on line 190 in pkg/cmd/destroy/destroy.go

View workflow job for this annotation

GitHub Actions / Golang Lint

S1000: should use a simple channel send/receive instead of `select` with a single case (gosimple)
case err = <-errCh:
if err != nil {
rel.Phase = apiv1.ReleasePhaseFailed
_ = release.UpdateDestroyRelease(storage, rel)
} else {
rel.Phase = apiv1.ReleasePhaseSucceeded
err = release.UpdateDestroyRelease(storage, rel)
}
}()

// only destroy resources we managed
storage, err = o.Backend.ReleaseStorage(o.RefProject.Name, o.RefWorkspace.Name)
if err != nil {
return
}
rel, err = release.CreateDestroyRelease(storage, o.RefProject.Name, o.RefStack.Name, o.RefWorkspace.Name)
if err != nil {
return
}
if len(rel.Spec.Resources) == 0 {
pterm.Println(pterm.Green("No managed resources to destroy"))
return
return err
}
releaseCreated = true
}

// run executes the delete command after release is created.
func (o *DestroyOptions) run(rel *apiv1.Release, storage release.Storage) (err error) {
// compute changes for preview
changes, err := o.preview(rel.Spec, rel.State, o.RefProject, o.RefStack, storage)
if err != nil {
Expand Down Expand Up @@ -240,11 +254,11 @@
// destroy
fmt.Println("Start destroying resources......")
var updatedRel *apiv1.Release
updatedRel, err = o.destroy(rel, changes, storage)

Check failure on line 257 in pkg/cmd/destroy/destroy.go

View workflow job for this annotation

GitHub Actions / Golang Lint

SA4006: this value of `updatedRel` is never used (staticcheck)
if err != nil {
return err
}
rel = updatedRel

Check failure on line 261 in pkg/cmd/destroy/destroy.go

View workflow job for this annotation

GitHub Actions / Golang Lint

SA4006: this value of `rel` is never used (staticcheck)

return nil
}
Expand Down
73 changes: 73 additions & 0 deletions pkg/util/signal/signal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
Copyright 2017 The Kubernetes Authors.

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.
*/

// Note: This is copy from Kubernetes apiserver.

package signal

import (
"context"
"os"
"os/signal"
)

var (
onlyOneSignalHandler = make(chan struct{})
shutdownHandler chan os.Signal
)

// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
// be called once.
func SetupSignalHandler() <-chan struct{} {
return SetupSignalContext().Done()
}

// SetupSignalContext is same as SetupSignalHandler, but a context.Context is returned.
// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
// be called once.
func SetupSignalContext() context.Context {
close(onlyOneSignalHandler) // panics when called twice

shutdownHandler = make(chan os.Signal, 2)

ctx, cancel := context.WithCancel(context.Background())
signal.Notify(shutdownHandler, shutdownSignals...)
go func() {
<-shutdownHandler
cancel()
<-shutdownHandler
os.Exit(1) // second signal. Exit directly.
}()

return ctx
}

// RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT)
// This returns whether a handler was notified
func RequestShutdown() bool {
if shutdownHandler != nil {
select {
case shutdownHandler <- shutdownSignals[0]:
return true
default:
}
}

return false
}
29 changes: 29 additions & 0 deletions pkg/util/signal/signal_posix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//go:build !windows
// +build !windows

/*
Copyright 2017 The Kubernetes Authors.

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.
*/

// Note: This is copy from Kubernetes apiserver.

package signal

import (
"os"
"syscall"
)

var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
25 changes: 25 additions & 0 deletions pkg/util/signal/signal_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright 2017 The Kubernetes Authors.

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.
*/

// Note: This is copy from Kubernetes apiserver.

package signal

import (
"os"
)

var shutdownSignals = []os.Signal{os.Interrupt}
Loading