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
|
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
internalInstance "github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/server/auth"
"github.com/lxc/incus/v6/internal/server/cluster"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/operations"
"github.com/lxc/incus/v6/internal/server/request"
"github.com/lxc/incus/v6/internal/server/response"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
)
func coalesceErrors(local bool, errors map[string]error) error {
if len(errors) == 0 {
return nil
}
var errorMsg string
if local {
errorMsg += "The following instances failed to update state:\n"
}
for instName, err := range errors {
if local {
errorMsg += fmt.Sprintf(" - Instance: %s: %v\n", instName, err)
} else {
errorMsg += strings.TrimSpace(fmt.Sprintf("%v\n", err))
}
}
return fmt.Errorf("%s", errorMsg)
}
// swagger:operation PUT /1.0/instances instances instances_put
//
// Bulk instance state update
//
// Changes the running state of all instances.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: body
// name: state
// description: State
// required: false
// schema:
// $ref: "#/definitions/InstancesPut"
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func instancesPut(d *Daemon, r *http.Request) response.Response {
projectName := request.ProjectParam(r)
// Don't mess with instances while in setup mode.
<-d.waitReady.Done()
s := d.State()
c, err := instance.LoadNodeAll(s, instancetype.Any)
if err != nil {
return response.BadRequest(err)
}
req := api.InstancesPut{}
req.State = &api.InstanceStatePut{}
req.State.Timeout = -1
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
action := internalInstance.InstanceAction(req.State.Action)
userHasPermission, err := s.Authorizer.GetPermissionChecker(r.Context(), r, auth.EntitlementCanUpdateState, auth.ObjectTypeInstance)
if err != nil {
return response.SmartError(err)
}
var names []string
var instances []instance.Instance
for _, inst := range c {
if inst.Project().Name != projectName {
continue
}
// Only allow changing the state of instances the user has permission for.
if !userHasPermission(auth.ObjectInstance(inst.Project().Name, inst.Name())) {
continue
}
switch action {
case internalInstance.Freeze:
if !inst.IsRunning() {
continue
}
case internalInstance.Restart:
if !inst.IsRunning() {
continue
}
case internalInstance.Start:
if inst.IsRunning() {
continue
}
case internalInstance.Stop:
if !inst.IsRunning() {
continue
}
case internalInstance.Unfreeze:
if !inst.IsFrozen() {
continue
}
}
instances = append(instances, inst)
names = append(names, inst.Name())
}
// Determine operation type.
opType, err := instanceActionToOpType(req.State.Action)
if err != nil {
return response.BadRequest(err)
}
// Batch the changes.
do := func(op *operations.Operation) error {
localAction := func(local bool) error {
failures := map[string]error{}
failuresLock := sync.Mutex{}
wgAction := sync.WaitGroup{}
for _, inst := range instances {
wgAction.Add(1)
go func(inst instance.Instance) {
defer wgAction.Done()
inst.SetOperation(op)
err := doInstanceStatePut(inst, *req.State)
if err != nil {
failuresLock.Lock()
failures[inst.Name()] = err
failuresLock.Unlock()
}
}(inst)
}
wgAction.Wait()
return coalesceErrors(local, failures)
}
// Only return the local data if asked by cluster member.
if isClusterNotification(r) {
return localAction(false)
}
// If not clustered, return the local data.
if !s.ServerClustered {
return localAction(true)
}
// Get all members in cluster.
var members []db.NodeInfo
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
members, err = tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
return nil
})
if err != nil {
return err
}
// Get local cluster address.
localClusterAddress := s.LocalConfig.ClusterAddress()
// Record the results.
failures := map[string]error{}
failuresLock := sync.Mutex{}
wgAction := sync.WaitGroup{}
networkCert := s.Endpoints.NetworkCert()
for _, member := range members {
wgAction.Add(1)
go func(member db.NodeInfo) {
defer wgAction.Done()
// Special handling for the local member.
if member.Address == localClusterAddress {
err := localAction(false)
if err != nil {
failuresLock.Lock()
failures[member.Name] = err
failuresLock.Unlock()
}
return
}
// Connect to the remote server.
client, err := cluster.Connect(member.Address, networkCert, s.ServerCert(), r, true)
if err != nil {
failuresLock.Lock()
failures[member.Name] = err
failuresLock.Unlock()
return
}
client = client.UseProject(projectName)
// Perform the action.
op, err := client.UpdateInstances(req, "")
if err != nil {
failuresLock.Lock()
failures[member.Name] = err
failuresLock.Unlock()
return
}
err = op.Wait()
if err != nil {
failuresLock.Lock()
failures[member.Name] = err
failuresLock.Unlock()
return
}
}(member)
}
wgAction.Wait()
return coalesceErrors(true, failures)
}
resources := map[string][]api.URL{}
for _, instName := range names {
resources["instances"] = append(resources["instances"], *api.NewURL().Path(version.APIVersion, "instances", instName))
}
op, err := operations.OperationCreate(s, projectName, operations.OperationClassTask, opType, resources, nil, do, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
|