-
Notifications
You must be signed in to change notification settings - Fork 21
/
api_client.go
288 lines (236 loc) · 8.52 KB
/
api_client.go
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
/*
Copyright 2023-2024 IONOS Cloud.
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.
*/
// Package goproxmox implements a client for Proxmox resource lifecycle management.
package goproxmox
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/go-logr/logr"
"github.com/luthermonson/go-proxmox"
"github.com/pkg/errors"
capmox "github.com/ionos-cloud/cluster-api-provider-proxmox/pkg/proxmox"
)
var _ capmox.Client = &APIClient{}
// APIClient Proxmox API client object.
type APIClient struct {
*proxmox.Client
logger logr.Logger
}
// NewAPIClient initializes a Proxmox API client. If the client is misconfigured, an error is returned.
func NewAPIClient(ctx context.Context, logger logr.Logger, baseURL string, options ...proxmox.Option) (*APIClient, error) {
proxmoxAPIURL, err := url.JoinPath(baseURL, "api2", "json")
if err != nil {
return nil, fmt.Errorf("invalid proxmox base URL %q: %w", baseURL, err)
}
options = append(options, proxmox.WithLogger(capmox.Logger{}))
upstreamClient := proxmox.NewClient(proxmoxAPIURL, options...)
version, err := upstreamClient.Version(ctx)
if err != nil {
return nil, fmt.Errorf("unable to initialize proxmox api client: %w", err)
}
logger.Info("Proxmox client initialized")
logger.Info("Proxmox server", "version", version.Release)
return &APIClient{
Client: upstreamClient,
logger: logger,
}, nil
}
// CloneVM clones a VM based on templateID and VMCloneRequest.
func (c *APIClient) CloneVM(ctx context.Context, templateID int, clone capmox.VMCloneRequest) (capmox.VMCloneResponse, error) {
// get the node
node, err := c.Node(ctx, clone.Node)
if err != nil {
return capmox.VMCloneResponse{}, fmt.Errorf("cannot find node with name %s: %w", clone.Node, err)
}
// get the vm template
vmTemplate, err := node.VirtualMachine(ctx, templateID)
if err != nil {
return capmox.VMCloneResponse{}, fmt.Errorf("unable to find vm template: %w", err)
}
vmOptions := proxmox.VirtualMachineCloneOptions{
NewID: clone.NewID,
Description: clone.Description,
Format: clone.Format,
Full: clone.Full,
Name: clone.Name,
Pool: clone.Pool,
SnapName: clone.SnapName,
Storage: clone.Storage,
Target: clone.Target,
}
newID, task, err := vmTemplate.Clone(ctx, &vmOptions)
if err != nil {
return capmox.VMCloneResponse{}, fmt.Errorf("unable to create new vm: %w", err)
}
return capmox.VMCloneResponse{NewID: int64(newID), Task: task}, nil
}
// ConfigureVM updates a VMs settings.
func (c *APIClient) ConfigureVM(ctx context.Context, vm *proxmox.VirtualMachine, options ...capmox.VirtualMachineOption) (*proxmox.Task, error) {
task, err := vm.Config(ctx, options...)
if err != nil {
return nil, fmt.Errorf("unable to configure vm: %w", err)
}
return task, nil
}
// GetVM returns a VM based on nodeName and vmID.
func (c *APIClient) GetVM(ctx context.Context, nodeName string, vmID int64) (*proxmox.VirtualMachine, error) {
node, err := c.Node(ctx, nodeName)
if err != nil {
return nil, fmt.Errorf("cannot find node with name %s: %w", nodeName, err)
}
vm, err := node.VirtualMachine(ctx, int(vmID))
if err != nil {
return nil, fmt.Errorf("cannot find vm with id %d: %w", vmID, err)
}
return vm, nil
}
// FindVMResource tries to find a VM by its ID on the whole cluster.
func (c *APIClient) FindVMResource(ctx context.Context, vmID uint64) (*proxmox.ClusterResource, error) {
cluster, err := c.Cluster(ctx)
if err != nil {
return nil, fmt.Errorf("cannot get cluster status: %w", err)
}
vmResources, err := cluster.Resources(ctx, "vm")
if err != nil {
return nil, fmt.Errorf("could not list vm resources: %w", err)
}
for _, vm := range vmResources {
if vm.VMID == vmID {
return vm, nil
}
}
return nil, fmt.Errorf("unable to find VM with ID %d on any of the nodes", vmID)
}
// DeleteVM deletes a VM based on the nodeName and vmID.
func (c *APIClient) DeleteVM(ctx context.Context, nodeName string, vmID int64) (*proxmox.Task, error) {
// A vmID can not be lower than 100.
// If the provided vmID is lower (like -1 in issue #31), just error out without calling the API.
if vmID < 100 {
return nil, fmt.Errorf("vm with id %d does not exist", vmID)
}
node, err := c.Node(ctx, nodeName)
if err != nil {
return nil, fmt.Errorf("cannot find node with name %s: %w", nodeName, err)
}
vm, err := node.VirtualMachine(ctx, int(vmID))
if err != nil {
return nil, fmt.Errorf("cannot find vm with id %d: %w", vmID, err)
}
if vm.IsRunning() {
if _, err = vm.Stop(ctx); err != nil {
return nil, fmt.Errorf("cannot stop vm id %d: %w", vmID, err)
}
}
task, err := vm.Delete(ctx)
if err != nil {
return nil, fmt.Errorf("cannot delete vm with id %d: %w", vmID, err)
}
return task, nil
}
// GetTask returns a task associated with upID.
func (c *APIClient) GetTask(ctx context.Context, upID string) (*proxmox.Task, error) {
task := proxmox.NewTask(proxmox.UPID(upID), c.Client)
err := task.Ping(ctx)
if err != nil {
return nil, fmt.Errorf("cannot get task with UPID %s: %w", upID, err)
}
return task, nil
}
// GetReservableMemoryBytes returns the memory that can be reserved by a new VM, in bytes.
func (c *APIClient) GetReservableMemoryBytes(ctx context.Context, nodeName string, nodeMemoryAdjustment uint64) (uint64, error) {
node, err := c.Client.Node(ctx, nodeName)
if err != nil {
return 0, fmt.Errorf("cannot find node with name %s: %w", nodeName, err)
}
reservableMemory := uint64(float64(node.Memory.Total) / 100 * float64(nodeMemoryAdjustment))
if nodeMemoryAdjustment == 0 {
return node.Memory.Total, nil
}
vms, err := node.VirtualMachines(ctx)
if err != nil {
return 0, fmt.Errorf("cannot list vms for node %s: %w", nodeName, err)
}
for _, vm := range vms {
// Ignore VM Templates, as they can't be started.
if vm.Template {
continue
}
if reservableMemory < vm.MaxMem {
reservableMemory = 0
} else {
reservableMemory -= vm.MaxMem
}
}
containers, err := node.Containers(ctx)
if err != nil {
return 0, fmt.Errorf("cannot list containers for node %s: %w", nodeName, err)
}
for _, ct := range containers {
if reservableMemory < ct.MaxMem {
reservableMemory = 0
} else {
reservableMemory -= ct.MaxMem
}
}
return reservableMemory, nil
}
// ResizeDisk resizes a VM disk to the specified size.
func (c *APIClient) ResizeDisk(ctx context.Context, vm *proxmox.VirtualMachine, disk, size string) error {
return vm.ResizeDisk(ctx, disk, size)
}
// ResumeVM resumes the VM.
func (c *APIClient) ResumeVM(ctx context.Context, vm *proxmox.VirtualMachine) (*proxmox.Task, error) {
return vm.Resume(ctx)
}
// StartVM starts the VM.
func (c *APIClient) StartVM(ctx context.Context, vm *proxmox.VirtualMachine) (*proxmox.Task, error) {
return vm.Start(ctx)
}
// TagVM tags the VM.
func (c *APIClient) TagVM(ctx context.Context, vm *proxmox.VirtualMachine, tag string) (*proxmox.Task, error) {
return vm.AddTag(ctx, tag)
}
// UnmountCloudInitISO unmounts the cloud-init iso from VM.
func (c *APIClient) UnmountCloudInitISO(ctx context.Context, vm *proxmox.VirtualMachine, device string) error {
err := vm.UnmountCloudInitISO(ctx, device)
if err != nil {
return fmt.Errorf("unable to unmount cloud-init iso: %w", err)
}
if vm.HasTag(proxmox.MakeTag(proxmox.TagCloudInit)) {
_, err = vm.RemoveTag(ctx, proxmox.MakeTag(proxmox.TagCloudInit))
}
return err
}
// CloudInitStatus returns the cloud-init status of the VM.
func (c *APIClient) CloudInitStatus(ctx context.Context, vm *proxmox.VirtualMachine) (running bool, err error) {
if err := vm.WaitForAgent(ctx, 5); err != nil {
return false, errors.Wrap(err, "error waiting for agent")
}
pid, err := vm.AgentExec(ctx, []string{"cloud-init", "status"}, "")
if err != nil {
return false, errors.Wrap(err, "unable to get cloud-init status")
}
status, err := vm.WaitForAgentExecExit(ctx, pid, 2)
if err != nil {
return false, errors.Wrap(err, "unable to wait for agent exec")
}
if status.Exited == 1 && status.ExitCode == 0 && strings.Contains(status.OutData, "running") {
return true, nil
}
if status.Exited == 1 && status.ExitCode != 0 {
return false, ErrCloudInitFailed
}
return false, nil
}