-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
vm.go
264 lines (233 loc) · 8.88 KB
/
vm.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
// Copyright 2022 Gravitational, Inc
//
// 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 azure
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v3"
"github.com/gravitational/trace"
"github.com/gravitational/teleport/api/types"
)
// armCompute provides an interface for an Azure virtual machine client.
type armCompute interface {
// Get retrieves information about an Azure virtual machine.
Get(ctx context.Context, resourceGroupName string, vmName string, options *armcompute.VirtualMachinesClientGetOptions) (armcompute.VirtualMachinesClientGetResponse, error)
// NewListPagers lists Azure virtual Machines.
NewListPager(resourceGroup string, opts *armcompute.VirtualMachinesClientListOptions) *runtime.Pager[armcompute.VirtualMachinesClientListResponse]
// NewListAllPager lists Azure virtual machines in any resource group.
NewListAllPager(opts *armcompute.VirtualMachinesClientListAllOptions) *runtime.Pager[armcompute.VirtualMachinesClientListAllResponse]
}
// VirtualMachinesClient is a client for Azure virtual machines.
type VirtualMachinesClient interface {
// Get returns the virtual machine for the given resource ID.
Get(ctx context.Context, resourceID string) (*VirtualMachine, error)
// GetByVMID returns the virtual machine for a given VM ID.
GetByVMID(ctx context.Context, resourceGroup, vmID string) (*VirtualMachine, error)
// ListVirtualMachines gets all of the virtual machines in the given resource group.
ListVirtualMachines(ctx context.Context, resourceGroup string) ([]*armcompute.VirtualMachine, error)
}
// VirtualMachine represents an Azure virtual machine.
type VirtualMachine struct {
// ID resource ID.
ID string `json:"id,omitempty"`
// Name resource name.
Name string `json:"name,omitempty"`
// Subscription is the Azure subscription the VM is in.
Subscription string
// ResourceGroup is the resource group the VM is in.
ResourceGroup string
// VMID is the VM's ID.
VMID string
// Identities are the identities associated with the resource.
Identities []Identity
}
// Identitiy represents an Azure virtual machine identity.
type Identity struct {
// ResourceID the identity resource ID.
ResourceID string
}
type vmClient struct {
// api is the Azure virtual machine client.
api armCompute
}
// NewVirtualMachinesClient creates a new Azure virtual machines client by
// subscription and credentials.
func NewVirtualMachinesClient(subscription string, cred azcore.TokenCredential, options *arm.ClientOptions) (VirtualMachinesClient, error) {
computeAPI, err := armcompute.NewVirtualMachinesClient(subscription, cred, options)
if err != nil {
return nil, trace.Wrap(err)
}
return NewVirtualMachinesClientByAPI(computeAPI), nil
}
// NewVirtualMachinesClientByAPI creates a new Azure virtual machines client by
// ARM API client.
func NewVirtualMachinesClientByAPI(api armCompute) VirtualMachinesClient {
return &vmClient{
api: api,
}
}
func parseVirtualMachine(vm *armcompute.VirtualMachine) (*VirtualMachine, error) {
resourceID, err := arm.ParseResourceID(*vm.ID)
if err != nil {
return nil, trace.Wrap(err)
}
var identities []Identity
if vm.Identity != nil {
if systemAssigned := StringVal(vm.Identity.PrincipalID); systemAssigned != "" {
identities = append(identities, Identity{ResourceID: systemAssigned})
}
for identityID := range vm.Identity.UserAssignedIdentities {
identities = append(identities, Identity{ResourceID: identityID})
}
}
var vmID string
if vm.Properties != nil {
vmID = *vm.Properties.VMID
}
return &VirtualMachine{
ID: *vm.ID,
Name: *vm.Name,
Subscription: resourceID.SubscriptionID,
ResourceGroup: resourceID.ResourceGroupName,
VMID: vmID,
Identities: identities,
}, nil
}
// Get returns the virtual machine for the given resource ID.
func (c *vmClient) Get(ctx context.Context, resourceID string) (*VirtualMachine, error) {
parsedResourceID, err := arm.ParseResourceID(resourceID)
if err != nil {
return nil, trace.Wrap(err)
}
resp, err := c.api.Get(ctx, parsedResourceID.ResourceGroupName, parsedResourceID.Name, nil)
if err != nil {
return nil, trace.Wrap(err)
}
vm, err := parseVirtualMachine(&resp.VirtualMachine)
return vm, trace.Wrap(err)
}
// GetByVMID returns the virtual machine for a given VM ID.
func (c *vmClient) GetByVMID(ctx context.Context, resourceGroup, vmID string) (*VirtualMachine, error) {
vms, err := c.ListVirtualMachines(ctx, resourceGroup)
if err != nil {
return nil, trace.Wrap(err)
}
for _, vm := range vms {
if vm.Properties != nil && *vm.Properties.VMID == vmID {
result, err := parseVirtualMachine(vm)
return result, trace.Wrap(err)
}
}
return nil, trace.NotFound("no VM with ID %q", vmID)
}
type vmPager struct {
more func() bool
nextPage func(context.Context) ([]*armcompute.VirtualMachine, error)
}
func newListPager(azurePager *runtime.Pager[armcompute.VirtualMachinesClientListResponse]) vmPager {
return vmPager{
more: azurePager.More,
nextPage: func(ctx context.Context) ([]*armcompute.VirtualMachine, error) {
res, err := azurePager.NextPage(ctx)
return res.Value, trace.Wrap(err)
},
}
}
func newListAllPager(azurePager *runtime.Pager[armcompute.VirtualMachinesClientListAllResponse]) vmPager {
return vmPager{
more: azurePager.More,
nextPage: func(ctx context.Context) ([]*armcompute.VirtualMachine, error) {
res, err := azurePager.NextPage(ctx)
return res.Value, trace.Wrap(err)
},
}
}
// ListVirtualMachines lists all virtual machines in a given resource group
// using the Azure virtual machines API. If resourceGroup is "*", it lists
// all virtual machines in any resource group.
func (c *vmClient) ListVirtualMachines(ctx context.Context, resourceGroup string) ([]*armcompute.VirtualMachine, error) {
var pager vmPager
if resourceGroup == types.Wildcard {
pager = newListAllPager(c.api.NewListAllPager(&armcompute.VirtualMachinesClientListAllOptions{}))
} else {
pager = newListPager(c.api.NewListPager(resourceGroup, &armcompute.VirtualMachinesClientListOptions{}))
}
var virtualMachines []*armcompute.VirtualMachine
for pager.more() {
res, err := pager.nextPage(ctx)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
virtualMachines = append(virtualMachines, res...)
}
return virtualMachines, nil
}
// RunCommandRequest combines parameters for running a command on an Azure virtual machine.
type RunCommandRequest struct {
// Region is the region of the VM.
Region string
// ResourceGroup is the resource group for the VM.
ResourceGroup string
// VMName is the name of the VM.
VMName string
// Script is the URI of the script for the virtual machine to execute.
Script string
// Parameters is a list of parameters for the script.
Parameters []string
}
// RunCommandClient is a client for Azure Run Commands.
type RunCommandClient interface {
Run(ctx context.Context, req RunCommandRequest) error
}
type runCommandClient struct {
api *armcompute.VirtualMachineRunCommandsClient
}
// NewRunCommandClient creates a new Azure Run Command client by subscription
// and credentials.
func NewRunCommandClient(subscription string, cred azcore.TokenCredential, options *arm.ClientOptions) (RunCommandClient, error) {
runCommandAPI, err := armcompute.NewVirtualMachineRunCommandsClient(subscription, cred, options)
if err != nil {
return nil, trace.Wrap(err)
}
return &runCommandClient{
api: runCommandAPI,
}, nil
}
// Run runs a command on a virtual machine.
func (c *runCommandClient) Run(ctx context.Context, req RunCommandRequest) error {
var params []*armcompute.RunCommandInputParameter
for _, value := range req.Parameters {
params = append(params, &armcompute.RunCommandInputParameter{
Value: to.Ptr(value),
})
}
poller, err := c.api.BeginCreateOrUpdate(ctx, req.ResourceGroup, req.VMName, "RunShellScript", armcompute.VirtualMachineRunCommand{
Location: to.Ptr(req.Region),
Properties: &armcompute.VirtualMachineRunCommandProperties{
AsyncExecution: to.Ptr(false),
Parameters: params,
Source: &armcompute.VirtualMachineRunCommandScriptSource{
Script: to.Ptr(req.Script),
},
},
}, nil)
if err != nil {
return trace.Wrap(err)
}
_, err = poller.PollUntilDone(ctx, nil /* options */)
return trace.Wrap(err)
}