add reboot command (#119)

Signed-off-by: Nikita Savchenko <nikisavchenko@ozon.ru>
This commit is contained in:
Nikita Savchenko 2023-01-23 11:32:01 +04:00
parent 6c378aaed6
commit 2b535a0b86
4 changed files with 47 additions and 4 deletions

View File

@ -41,6 +41,7 @@ func NewHostAttackCommand(uid *string) *cobra.Command {
}
cmd.AddCommand(NewHostShutdownCommand(dep, options))
cmd.AddCommand(NewHostRebootCommand(dep, options))
return cmd
}
@ -51,6 +52,21 @@ func NewHostShutdownCommand(dep fx.Option, options *core.HostCommand) *cobra.Com
Short: "shutdowns system, this action will trigger shutdown of the host machine",
Run: func(*cobra.Command, []string) {
options.Action = core.HostShutdownAction
utils.FxNewAppWithoutLog(dep, fx.Invoke(hostAttackF)).Run()
},
}
return cmd
}
func NewHostRebootCommand(dep fx.Option, options *core.HostCommand) *cobra.Command {
cmd := &cobra.Command{
Use: "reboot",
Short: "reboot system, this action will trigger reboot of the host machine",
Run: func(*cobra.Command, []string) {
options.Action = core.HostRebootAction
utils.FxNewAppWithoutLog(dep, fx.Invoke(hostAttackF)).Run()
},
}

View File

@ -19,6 +19,7 @@ import (
const (
HostShutdownAction = "shutdown"
HostRebootAction = "reboot"
)
type HostCommand struct {
@ -40,8 +41,7 @@ func (h HostCommand) RecoverData() string {
func NewHostCommand() *HostCommand {
return &HostCommand{
CommonAttackConfig: CommonAttackConfig{
Kind: HostAttack,
Action: HostShutdownAction,
Kind: HostAttack,
},
}
}

View File

@ -14,6 +14,7 @@
package chaosd
import (
"github.com/pingcap/errors"
perr "github.com/pkg/errors"
"github.com/chaos-mesh/chaosd/pkg/core"
@ -22,6 +23,7 @@ import (
type HostManager interface {
Name() string
Shutdown() error
Reboot() error
}
type hostAttack struct{}
@ -29,9 +31,23 @@ type hostAttack struct{}
var HostAttack AttackType = hostAttack{}
func (hostAttack) Attack(options core.AttackConfig, _ Environment) error {
if err := Host.Shutdown(); err != nil {
return perr.WithStack(err)
hostOption, ok := options.(*core.HostCommand)
if !ok {
return errors.New("the type is not HostOption")
}
if hostOption.Action == core.HostShutdownAction {
if err := Host.Shutdown(); err != nil {
return perr.WithStack(err)
}
}
if hostOption.Action == core.HostRebootAction {
if err := Host.Reboot(); err != nil {
return perr.WithStack(err)
}
}
return nil
}

View File

@ -29,6 +29,8 @@ var Host HostManager = UnixHost{}
const CmdShutdown = "shutdown"
const CmdReboot = "reboot"
func (h UnixHost) Name() string {
return "unix"
}
@ -41,3 +43,12 @@ func (h UnixHost) Shutdown() error {
}
return err
}
func (h UnixHost) Reboot() error {
cmd := exec.Command(CmdReboot)
output, err := cmd.CombinedOutput()
if err != nil {
log.Error(string(output), zap.Error(err))
}
return err
}