github.com/sacloud/iaas-api-go@v1.12.0/helper/cleanup/server.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cleanup
    16  
    17  import (
    18  	"context"
    19  
    20  	"github.com/sacloud/iaas-api-go"
    21  	"github.com/sacloud/iaas-api-go/helper/power"
    22  	"github.com/sacloud/iaas-api-go/types"
    23  )
    24  
    25  // DeleteServer サーバの削除を行う。引数に応じて接続されたディスクの削除も同時に行う。
    26  // もし電源がONの場合は強制シャットダウンされる
    27  func DeleteServer(ctx context.Context, caller iaas.APICaller, zone string, id types.ID, withDisks bool) error {
    28  	serverOp := iaas.NewServerOp(caller)
    29  	server, err := serverOp.Read(ctx, zone, id)
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	if server.InstanceStatus.IsUp() {
    35  		if err := power.ShutdownServer(ctx, serverOp, zone, id, true); err != nil {
    36  			return err
    37  		}
    38  	}
    39  
    40  	if !withDisks {
    41  		return serverOp.Delete(ctx, zone, id)
    42  	}
    43  
    44  	var diskIDs []types.ID
    45  	for i := range server.Disks {
    46  		diskIDs = append(diskIDs, server.Disks[i].ID)
    47  	}
    48  
    49  	return serverOp.DeleteWithDisks(ctx, zone, id, &iaas.ServerDeleteWithDisksRequest{IDs: diskIDs})
    50  }