Working destroyer

This commit is contained in:
Quentin 2021-09-23 08:23:54 +02:00
parent 5476ba20d1
commit 80ed8bca6c
1 changed files with 30 additions and 16 deletions

46
main.go
View File

@ -87,13 +87,13 @@ func passInstanceTo(r io.Reader, d instanceReceiver) error {
count += 1
}
fmt.Fprintf(os.Stdout, " Waiting for %v servers\n", count)
for count > 0 {
err := <- com
count -= 1
if err != nil {
failed += 1
}
fmt.Fprintf(os.Stdout, " Waiting for %v more servers\n", count)
}
if failed > 0 {
@ -106,18 +106,19 @@ func passInstanceTo(r io.Reader, d instanceReceiver) error {
* instance wrapper
*/
type instance struct {
type action struct {
api *instance.API
}
func (i *instance) init() error {
func (i *action) init() error {
client, err := getClient()
if err != nil {
return err
}
i.api = instance.NewAPI(client),
i.api = instance.NewAPI(client)
return nil
}
func (i *instance) getInstanceByName(zone scw.Zone, name string) (*instance.Server, error) {
func (i *action) getInstanceByName(zone scw.Zone, name string) (*instance.Server, error) {
lr, err := i.api.ListServers(&instance.ListServersRequest{
Zone: zone,
Name: &name,
@ -143,7 +144,7 @@ func parseIP(s *instance.Server) string {
ip += " (dynamic)"
}
} else if s.PrivateIP != nil {
ip = fmt.Sprintf("%v %v", s.PrivateIP, "(private)")
ip = fmt.Sprintf("%s %s", *s.PrivateIP, "(private)")
}
return ip
}
@ -152,11 +153,7 @@ func parseIP(s *instance.Server) string {
/**
* Spawner
*/
type spawner instance
func newSpawner() (spawner, error) {
return newInstance()
}
type spawner struct { action }
func (sp *spawner) onInstance(zone, machine, image, name string) error {
z, err := scw.ParseZone(zone)
if err != nil {
@ -212,7 +209,7 @@ func (sp *spawner) onInstance(zone, machine, image, name string) error {
/**
* Destroyer
*/
type destroyer instance
type destroyer struct { action }
func (dt *destroyer) onInstance(zone, machine, image, name string) error {
z, err := scw.ParseZone(zone)
@ -220,17 +217,34 @@ func (dt *destroyer) onInstance(zone, machine, image, name string) error {
return err
}
targetServer, err := dt.inst.getInstanceByName(z, name)
targetServer, err := dt.getInstanceByName(z, name)
if err == instanceNotFound {
fmt.Fprintf(os.Stdout, "🟣 %v is already destroyed\n", name)
return nil
} else if err != nil {
return err
}
err = dt.api.ServerActionAndWait(&instance.ServerActionAndWaitRequest{
Zone: z,
ServerID: targetServer.ID,
Action: instance.ServerActionPoweroff,
})
if err != nil {
return err
}
err = dt.inst.api.DeleteServer(&instance.DeleteServerRequest{
err = dt.api.DeleteServer(&instance.DeleteServerRequest{
Zone: z,
ServerID: targetServer.ID
ServerID: targetServer.ID,
})
if err != nil {
return err
}
return err
ip := parseIP(targetServer)
fmt.Fprintf(os.Stdout, "✅ Destroyed %v on zone %v with ip %v\n", targetServer.Name, targetServer.Zone, ip)
return nil
}