1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
|
package hcloud
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"time"
"github.com/hetznercloud/hcloud-go/v2/hcloud/schema"
)
// Image represents an Image in the Hetzner Cloud.
type Image struct {
ID int64
Name string
Type ImageType
Status ImageStatus
Description string
ImageSize float32
DiskSize float32
Created time.Time
CreatedFrom *Server
BoundTo *Server
RapidDeploy bool
OSFlavor string
OSVersion string
Architecture Architecture
Protection ImageProtection
Deprecated time.Time // The zero value denotes the image is not deprecated.
Labels map[string]string
Deleted time.Time
}
// IsDeprecated returns whether the image is deprecated.
func (image *Image) IsDeprecated() bool {
return !image.Deprecated.IsZero()
}
// IsDeleted returns whether the image is deleted.
func (image *Image) IsDeleted() bool {
return !image.Deleted.IsZero()
}
// ImageProtection represents the protection level of an image.
type ImageProtection struct {
Delete bool
}
// ImageType specifies the type of an image.
type ImageType string
const (
// ImageTypeSnapshot represents a snapshot image.
ImageTypeSnapshot ImageType = "snapshot"
// ImageTypeBackup represents a backup image.
ImageTypeBackup ImageType = "backup"
// ImageTypeSystem represents a system image.
ImageTypeSystem ImageType = "system"
// ImageTypeApp represents a one click app image.
ImageTypeApp ImageType = "app"
)
// ImageStatus specifies the status of an image.
type ImageStatus string
const (
// ImageStatusCreating is the status when an image is being created.
ImageStatusCreating ImageStatus = "creating"
// ImageStatusAvailable is the status when an image is available.
ImageStatusAvailable ImageStatus = "available"
)
// ImageClient is a client for the image API.
type ImageClient struct {
client *Client
Action *ResourceActionClient
}
// GetByID retrieves an image by its ID. If the image does not exist, nil is returned.
func (c *ImageClient) GetByID(ctx context.Context, id int64) (*Image, *Response, error) {
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/images/%d", id), nil)
if err != nil {
return nil, nil, err
}
var body schema.ImageGetResponse
resp, err := c.client.Do(req, &body)
if err != nil {
if IsError(err, ErrorCodeNotFound) {
return nil, resp, nil
}
return nil, nil, err
}
return ImageFromSchema(body.Image), resp, nil
}
// GetByName retrieves an image by its name. If the image does not exist, nil is returned.
//
// Deprecated: Use [ImageClient.GetByNameAndArchitecture] instead.
func (c *ImageClient) GetByName(ctx context.Context, name string) (*Image, *Response, error) {
if name == "" {
return nil, nil, nil
}
images, response, err := c.List(ctx, ImageListOpts{Name: name})
if len(images) == 0 {
return nil, response, err
}
return images[0], response, err
}
// GetByNameAndArchitecture retrieves an image by its name and architecture. If the image does not exist,
// nil is returned.
// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should
// check for this in your calling method.
func (c *ImageClient) GetByNameAndArchitecture(ctx context.Context, name string, architecture Architecture) (*Image, *Response, error) {
if name == "" {
return nil, nil, nil
}
images, response, err := c.List(ctx, ImageListOpts{Name: name, Architecture: []Architecture{architecture}, IncludeDeprecated: true})
if len(images) == 0 {
return nil, response, err
}
return images[0], response, err
}
// Get retrieves an image by its ID if the input can be parsed as an integer, otherwise it
// retrieves an image by its name. If the image does not exist, nil is returned.
//
// Deprecated: Use [ImageClient.GetForArchitecture] instead.
func (c *ImageClient) Get(ctx context.Context, idOrName string) (*Image, *Response, error) {
if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil {
return c.GetByID(ctx, id)
}
return c.GetByName(ctx, idOrName)
}
// GetForArchitecture retrieves an image by its ID if the input can be parsed as an integer, otherwise it
// retrieves an image by its name and architecture. If the image does not exist, nil is returned.
//
// In contrast to [ImageClient.Get], this method also returns deprecated images. Depending on your needs you should
// check for this in your calling method.
func (c *ImageClient) GetForArchitecture(ctx context.Context, idOrName string, architecture Architecture) (*Image, *Response, error) {
if id, err := strconv.ParseInt(idOrName, 10, 64); err == nil {
return c.GetByID(ctx, id)
}
return c.GetByNameAndArchitecture(ctx, idOrName, architecture)
}
// ImageListOpts specifies options for listing images.
type ImageListOpts struct {
ListOpts
Type []ImageType
BoundTo *Server
Name string
Sort []string
Status []ImageStatus
IncludeDeprecated bool
Architecture []Architecture
}
func (l ImageListOpts) values() url.Values {
vals := l.ListOpts.Values()
for _, typ := range l.Type {
vals.Add("type", string(typ))
}
if l.BoundTo != nil {
vals.Add("bound_to", strconv.FormatInt(l.BoundTo.ID, 10))
}
if l.Name != "" {
vals.Add("name", l.Name)
}
if l.IncludeDeprecated {
vals.Add("include_deprecated", strconv.FormatBool(l.IncludeDeprecated))
}
for _, sort := range l.Sort {
vals.Add("sort", sort)
}
for _, status := range l.Status {
vals.Add("status", string(status))
}
for _, arch := range l.Architecture {
vals.Add("architecture", string(arch))
}
return vals
}
// List returns a list of images for a specific page.
//
// Please note that filters specified in opts are not taken into account
// when their value corresponds to their zero value or when they are empty.
func (c *ImageClient) List(ctx context.Context, opts ImageListOpts) ([]*Image, *Response, error) {
path := "/images?" + opts.values().Encode()
req, err := c.client.NewRequest(ctx, "GET", path, nil)
if err != nil {
return nil, nil, err
}
var body schema.ImageListResponse
resp, err := c.client.Do(req, &body)
if err != nil {
return nil, nil, err
}
images := make([]*Image, 0, len(body.Images))
for _, i := range body.Images {
images = append(images, ImageFromSchema(i))
}
return images, resp, nil
}
// All returns all images.
func (c *ImageClient) All(ctx context.Context) ([]*Image, error) {
return c.AllWithOpts(ctx, ImageListOpts{ListOpts: ListOpts{PerPage: 50}})
}
// AllWithOpts returns all images for the given options.
func (c *ImageClient) AllWithOpts(ctx context.Context, opts ImageListOpts) ([]*Image, error) {
allImages := []*Image{}
err := c.client.all(func(page int) (*Response, error) {
opts.Page = page
images, resp, err := c.List(ctx, opts)
if err != nil {
return resp, err
}
allImages = append(allImages, images...)
return resp, nil
})
if err != nil {
return nil, err
}
return allImages, nil
}
// Delete deletes an image.
func (c *ImageClient) Delete(ctx context.Context, image *Image) (*Response, error) {
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("/images/%d", image.ID), nil)
if err != nil {
return nil, err
}
return c.client.Do(req, nil)
}
// ImageUpdateOpts specifies options for updating an image.
type ImageUpdateOpts struct {
Description *string
Type ImageType
Labels map[string]string
}
// Update updates an image.
func (c *ImageClient) Update(ctx context.Context, image *Image, opts ImageUpdateOpts) (*Image, *Response, error) {
reqBody := schema.ImageUpdateRequest{
Description: opts.Description,
}
if opts.Type != "" {
reqBody.Type = Ptr(string(opts.Type))
}
if opts.Labels != nil {
reqBody.Labels = &opts.Labels
}
reqBodyData, err := json.Marshal(reqBody)
if err != nil {
return nil, nil, err
}
path := fmt.Sprintf("/images/%d", image.ID)
req, err := c.client.NewRequest(ctx, "PUT", path, bytes.NewReader(reqBodyData))
if err != nil {
return nil, nil, err
}
respBody := schema.ImageUpdateResponse{}
resp, err := c.client.Do(req, &respBody)
if err != nil {
return nil, resp, err
}
return ImageFromSchema(respBody.Image), resp, nil
}
// ImageChangeProtectionOpts specifies options for changing the resource protection level of an image.
type ImageChangeProtectionOpts struct {
Delete *bool
}
// ChangeProtection changes the resource protection level of an image.
func (c *ImageClient) ChangeProtection(ctx context.Context, image *Image, opts ImageChangeProtectionOpts) (*Action, *Response, error) {
reqBody := schema.ImageActionChangeProtectionRequest{
Delete: opts.Delete,
}
reqBodyData, err := json.Marshal(reqBody)
if err != nil {
return nil, nil, err
}
path := fmt.Sprintf("/images/%d/actions/change_protection", image.ID)
req, err := c.client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData))
if err != nil {
return nil, nil, err
}
respBody := schema.ImageActionChangeProtectionResponse{}
resp, err := c.client.Do(req, &respBody)
if err != nil {
return nil, resp, err
}
return ActionFromSchema(respBody.Action), resp, err
}
|