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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
|
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/lxc/incus/v6/internal/jmap"
"github.com/lxc/incus/v6/internal/server/auth"
"github.com/lxc/incus/v6/internal/server/cluster"
"github.com/lxc/incus/v6/internal/server/db"
dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
"github.com/lxc/incus/v6/internal/server/db/operationtype"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"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/server/state"
"github.com/lxc/incus/v6/internal/server/task"
localUtil "github.com/lxc/incus/v6/internal/server/util"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/util"
)
var operationCmd = APIEndpoint{
Path: "operations/{id}",
Delete: APIEndpointAction{Handler: operationDelete, AccessHandler: allowAuthenticated},
Get: APIEndpointAction{Handler: operationGet, AccessHandler: allowAuthenticated},
}
var operationsCmd = APIEndpoint{
Path: "operations",
Get: APIEndpointAction{Handler: operationsGet, AccessHandler: allowAuthenticated},
}
var operationWait = APIEndpoint{
Path: "operations/{id}/wait",
Get: APIEndpointAction{Handler: operationWaitGet, AllowUntrusted: true},
}
var operationWebsocket = APIEndpoint{
Path: "operations/{id}/websocket",
Get: APIEndpointAction{Handler: operationWebsocketGet, AllowUntrusted: true},
}
// waitForOperations waits for operations to finish.
// There's a timeout for console/exec operations that when reached will shut down the instances forcefully.
func waitForOperations(ctx context.Context, cluster *db.Cluster, consoleShutdownTimeout time.Duration) {
timeout := time.After(consoleShutdownTimeout)
defer func() {
_ = cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
err := dbCluster.DeleteOperations(ctx, tx.Tx(), cluster.GetNodeID())
if err != nil {
logger.Error("Failed cleaning up operations")
}
return nil
})
}()
// Check operation status every second.
tick := time.NewTicker(time.Second)
defer tick.Stop()
var i int
for {
// Get all the operations
ops := operations.Clone()
var runningOps, execConsoleOps int
for _, op := range ops {
if op.Status() != api.Running || op.Class() == operations.OperationClassToken {
continue
}
runningOps++
opType := op.Type()
if opType == operationtype.CommandExec || opType == operationtype.ConsoleShow {
execConsoleOps++
}
_, opAPI, err := op.Render()
if err != nil {
logger.Warn("Failed to render operation", logger.Ctx{"operation": op, "err": err})
} else if opAPI.MayCancel {
_, _ = op.Cancel()
}
}
// No more running operations left. Exit function.
if runningOps == 0 {
logger.Info("All running operations finished, shutting down")
return
}
// Print log message every minute.
if i%60 == 0 {
logger.Infof("Waiting for %d operation(s) to finish", runningOps)
}
i++
select {
case <-timeout:
// We wait up to core.shutdown_timeout minutes for exec/console operations to finish.
// If there are still running operations, we continue shutdown which will stop any running
// instances and terminate the operations.
if execConsoleOps > 0 {
logger.Info("Shutdown timeout reached, continuing with shutdown")
}
return
case <-ctx.Done():
// Return here, and ignore any running operations.
logger.Info("Forcing shutdown, ignoring running operations")
return
case <-tick.C:
}
}
}
// API functions
// swagger:operation GET /1.0/operations/{id} operations operation_get
//
// Get the operation state
//
// Gets the operation state.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Operation
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Operation"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func operationGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
id, err := url.PathUnescape(mux.Vars(r)["id"])
if err != nil {
return response.SmartError(err)
}
var body *api.Operation
// First check if the query is for a local operation from this node
op, err := operations.OperationGetInternal(id)
if err == nil {
_, body, err = op.Render()
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, body)
}
// Then check if the query is from an operation on another node, and, if so, forward it
var address string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.OperationFilter{UUID: &id}
ops, err := dbCluster.GetOperations(ctx, tx.Tx(), filter)
if err != nil {
return err
}
if len(ops) < 1 {
return api.StatusErrorf(http.StatusNotFound, "Operation not found")
}
if len(ops) > 1 {
return errors.New("More than one operation matches")
}
operation := ops[0]
address = operation.NodeAddress
return nil
})
if err != nil {
return response.SmartError(err)
}
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, false)
if err != nil {
return response.SmartError(err)
}
return response.ForwardedResponse(client, r)
}
// swagger:operation DELETE /1.0/operations/{id} operations operation_delete
//
// Cancel the operation
//
// Cancels the operation if supported.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func operationDelete(d *Daemon, r *http.Request) response.Response {
s := d.State()
id, err := url.PathUnescape(mux.Vars(r)["id"])
if err != nil {
return response.SmartError(err)
}
// First check if the query is for a local operation from this node
op, err := operations.OperationGetInternal(id)
if err == nil {
projectName := op.Project()
if projectName == "" {
projectName = api.ProjectDefaultName
}
objectType, entitlement := op.Permission()
if objectType != "" {
for _, v := range op.Resources() {
for _, u := range v {
// When dealing with specific objects, get the arguments from the URL.
var pathArgs []string
if objectType != auth.ObjectTypeProject {
var err error
_, _, _, pathArgs, err = dbCluster.URLToEntityType(u.String())
if err != nil {
return response.InternalError(fmt.Errorf("Unable to parse operation resource URL: %w", err))
}
}
// Check that the access is allowed.
object, err := auth.NewObject(objectType, projectName, pathArgs...)
if err != nil {
return response.InternalError(fmt.Errorf("Unable to create authorization object for operation: %w", err))
}
err = s.Authorizer.CheckPermission(r.Context(), r, object, entitlement)
if err != nil {
return response.SmartError(err)
}
}
}
}
_, err = op.Cancel()
if err != nil {
return response.BadRequest(err)
}
s.Events.SendLifecycle(projectName, lifecycle.OperationCancelled.Event(op, request.CreateRequestor(r), nil))
return response.EmptySyncResponse
}
// Then check if the query is from an operation on another node, and, if so, forward it
var address string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.OperationFilter{UUID: &id}
ops, err := dbCluster.GetOperations(ctx, tx.Tx(), filter)
if err != nil {
return err
}
if len(ops) < 1 {
return api.StatusErrorf(http.StatusNotFound, "Operation not found")
}
if len(ops) > 1 {
return errors.New("More than one operation matches")
}
operation := ops[0]
address = operation.NodeAddress
return nil
})
if err != nil {
return response.SmartError(err)
}
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, false)
if err != nil {
return response.SmartError(err)
}
return response.ForwardedResponse(client, r)
}
// operationCancel cancels an operation that exists on any member.
func operationCancel(s *state.State, r *http.Request, projectName string, op *api.Operation) error {
// Check if operation is local and if so, cancel it.
localOp, _ := operations.OperationGetInternal(op.ID)
if localOp != nil {
if localOp.Status() == api.Running {
_, err := localOp.Cancel()
if err != nil {
return fmt.Errorf("Failed to cancel local operation %q: %w", op.ID, err)
}
}
s.Events.SendLifecycle(projectName, lifecycle.OperationCancelled.Event(localOp, request.CreateRequestor(r), nil))
return nil
}
// If not found locally, try connecting to remote member to delete it.
var memberAddress string
var err error
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.OperationFilter{UUID: &op.ID}
ops, err := dbCluster.GetOperations(ctx, tx.Tx(), filter)
if err != nil {
return fmt.Errorf("Failed loading operation %q: %w", op.ID, err)
}
if len(ops) < 1 {
return api.StatusErrorf(http.StatusNotFound, "Operation not found")
}
if len(ops) > 1 {
return errors.New("More than one operation matches")
}
operation := ops[0]
memberAddress = operation.NodeAddress
return nil
})
if err != nil {
return err
}
client, err := cluster.Connect(memberAddress, s.Endpoints.NetworkCert(), s.ServerCert(), r, true)
if err != nil {
return fmt.Errorf("Failed to connect to %q: %w", memberAddress, err)
}
err = client.UseProject(projectName).DeleteOperation(op.ID)
if err != nil {
return fmt.Errorf("Failed to delete remote operation %q on %q: %w", op.ID, memberAddress, err)
}
return nil
}
// swagger:operation GET /1.0/operations operations operations_get
//
// Get the operations
//
// Returns a JSON object of operation type to operation list (URLs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: all-projects
// description: Retrieve operations from all projects
// type: boolean
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: object
// additionalProperties:
// type: array
// items:
// type: string
// description: JSON object of operation types to operation URLs
// example: |-
// {
// "running": [
// "/1.0/operations/6916c8a6-9b7d-4abd-90b3-aedfec7ec7da"
// ]
// }
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/operations?recursion=1 operations operations_get_recursion1
//
// Get the operations
//
// Returns a list of operations (structs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: all-projects
// description: Retrieve operations from all projects
// type: boolean
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of operations
// items:
// $ref: "#/definitions/Operation"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func operationsGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName := request.QueryParam(r, "project")
allProjects := util.IsTrue(request.QueryParam(r, "all-projects"))
recursion := localUtil.IsRecursionRequest(r)
if allProjects && projectName != "" {
return response.SmartError(
api.StatusErrorf(http.StatusBadRequest, "Cannot specify a project when requesting all projects"),
)
} else if !allProjects && projectName == "" {
projectName = api.ProjectDefaultName
}
userHasPermission, err := s.Authorizer.GetPermissionChecker(r.Context(), r, auth.EntitlementCanViewOperations, auth.ObjectTypeProject)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to get operation permission checker: %w", err))
}
localOperationURLs := func() (jmap.Map, error) {
// Get all the operations.
localOps := operations.Clone()
// Build a list of URLs.
body := jmap.Map{}
for _, v := range localOps {
if !allProjects && v.Project() != "" && v.Project() != projectName {
continue
}
if !userHasPermission(auth.ObjectProject(v.Project())) {
continue
}
status := strings.ToLower(v.Status().String())
_, ok := body[status]
if !ok {
body[status] = make([]string, 0)
}
body[status] = append(body[status].([]string), v.URL())
}
return body, nil
}
localOperations := func() (jmap.Map, error) {
// Get all the operations.
localOps := operations.Clone()
// Build a list of operations.
body := jmap.Map{}
for _, v := range localOps {
if !allProjects && v.Project() != "" && v.Project() != projectName {
continue
}
if !userHasPermission(auth.ObjectProject(v.Project())) {
continue
}
status := strings.ToLower(v.Status().String())
_, ok := body[status]
if !ok {
body[status] = make([]*api.Operation, 0)
}
_, op, err := v.Render()
if err != nil {
return nil, err
}
body[status] = append(body[status].([]*api.Operation), op)
}
return body, nil
}
// Check if called from a cluster node.
if isClusterNotification(r) {
// Only return the local data.
if recursion {
// Recursive queries.
body, err := localOperations()
if err != nil {
return response.InternalError(err)
}
return response.SyncResponse(true, body)
}
// Normal queries
body, err := localOperationURLs()
if err != nil {
return response.InternalError(err)
}
return response.SyncResponse(true, body)
}
// Start with local operations.
var md jmap.Map
if recursion {
md, err = localOperations()
if err != nil {
return response.InternalError(err)
}
} else {
md, err = localOperationURLs()
if err != nil {
return response.InternalError(err)
}
}
// If not clustered, then just return local operations.
if !s.ServerClustered {
return response.SyncResponse(true, md)
}
// Get all nodes with running operations in this project.
var membersWithOps []string
var members []db.NodeInfo
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
if allProjects {
membersWithOps, err = tx.GetAllNodesWithOperations(ctx)
} else {
membersWithOps, err = tx.GetNodesWithOperations(ctx, projectName)
}
if err != nil {
return fmt.Errorf("Failed getting members with operations: %w", err)
}
members, err = tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Get local address.
localClusterAddress := s.LocalConfig.ClusterAddress()
offlineThreshold := s.GlobalConfig.OfflineThreshold()
memberOnline := func(memberAddress string) bool {
for _, member := range members {
if member.Address == memberAddress {
if member.IsOffline(offlineThreshold) {
logger.Warn("Excluding offline member from operations list", logger.Ctx{"member": member.Name, "address": member.Address, "ID": member.ID, "lastHeartbeat": member.Heartbeat})
return false
}
return true
}
}
return false
}
networkCert := s.Endpoints.NetworkCert()
for _, memberAddress := range membersWithOps {
if memberAddress == localClusterAddress {
continue
}
if !memberOnline(memberAddress) {
continue
}
// Connect to the remote server. Use notify=true to only get local operations on remote member.
client, err := cluster.Connect(memberAddress, networkCert, s.ServerCert(), r, true)
if err != nil {
return response.SmartError(fmt.Errorf("Failed connecting to member %q: %w", memberAddress, err))
}
// Get operation data.
var ops []api.Operation
if allProjects {
ops, err = client.GetOperationsAllProjects()
} else {
ops, err = client.UseProject(projectName).GetOperations()
}
if err != nil {
logger.Warn("Failed getting operations from member", logger.Ctx{"address": memberAddress, "err": err})
continue
}
// Merge with existing data.
for _, o := range ops {
op := o // Local var for pointer.
status := strings.ToLower(op.Status)
_, ok := md[status]
if !ok {
if recursion {
md[status] = make([]*api.Operation, 0)
} else {
md[status] = make([]string, 0)
}
}
if recursion {
md[status] = append(md[status].([]*api.Operation), &op)
} else {
md[status] = append(md[status].([]string), fmt.Sprintf("/1.0/operations/%s", op.ID))
}
}
}
return response.SyncResponse(true, md)
}
// operationsGetByType gets all operations for a project and type.
func operationsGetByType(s *state.State, r *http.Request, projectName string, opType operationtype.Type) ([]*api.Operation, error) {
ops := make([]*api.Operation, 0)
// Get local operations for project.
for _, op := range operations.Clone() {
if op.Project() != projectName || op.Type() != opType {
continue
}
_, apiOp, err := op.Render()
if err != nil {
return nil, fmt.Errorf("Failed converting local operation %q to API representation: %w", op.ID(), err)
}
ops = append(ops, apiOp)
}
// Return just local operations if not clustered.
if !s.ServerClustered {
return ops, nil
}
// Get all operations of the specified type in project.
var members []db.NodeInfo
memberOps := make(map[string]map[string]dbCluster.Operation)
err := s.DB.Cluster.Transaction(r.Context(), 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)
}
ops, err := tx.GetOperationsOfType(ctx, projectName, opType)
if err != nil {
return fmt.Errorf("Failed getting operations for project %q and type %d: %w", projectName, opType, err)
}
// Group operations by member address and UUID.
for _, op := range ops {
if memberOps[op.NodeAddress] == nil {
memberOps[op.NodeAddress] = make(map[string]dbCluster.Operation)
}
memberOps[op.NodeAddress][op.UUID] = op
}
return nil
})
if err != nil {
return nil, err
}
// Get local address.
localClusterAddress := s.LocalConfig.ClusterAddress()
offlineThreshold := s.GlobalConfig.OfflineThreshold()
memberOnline := func(memberAddress string) bool {
for _, member := range members {
if member.Address == memberAddress {
if member.IsOffline(offlineThreshold) {
logger.Warn("Excluding offline member from operations by type list", logger.Ctx{"member": member.Name, "address": member.Address, "ID": member.ID, "lastHeartbeat": member.Heartbeat, "opType": opType})
return false
}
return true
}
}
return false
}
networkCert := s.Endpoints.NetworkCert()
serverCert := s.ServerCert()
for memberAddress := range memberOps {
if memberAddress == localClusterAddress {
continue
}
if !memberOnline(memberAddress) {
continue
}
// Connect to the remote server. Use notify=true to only get local operations on remote member.
client, err := cluster.Connect(memberAddress, networkCert, serverCert, r, true)
if err != nil {
return nil, fmt.Errorf("Failed connecting to member %q: %w", memberAddress, err)
}
// Get all remote operations in project.
remoteOps, err := client.UseProject(projectName).GetOperations()
if err != nil {
logger.Warn("Failed getting operations from member", logger.Ctx{"address": memberAddress, "err": err})
continue
}
for _, o := range remoteOps {
op := o // Local var for pointer.
// Exclude remote operations that don't have the desired type.
if memberOps[memberAddress][op.ID].Type != opType {
continue
}
ops = append(ops, &op)
}
}
return ops, nil
}
// swagger:operation GET /1.0/operations/{id}/wait?public operations operation_wait_get_untrusted
//
// Wait for the operation
//
// Waits for the operation to reach a final state (or timeout) and retrieve its final state.
//
// When accessed by an untrusted user, the secret token must be provided.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: secret
// description: Authentication token
// type: string
// example: random-string
// - in: query
// name: timeout
// description: Timeout in seconds (-1 means never)
// type: integer
// example: -1
// responses:
// "200":
// description: Operation
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Operation"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/operations/{id}/wait operations operation_wait_get
//
// Wait for the operation
//
// Waits for the operation to reach a final state (or timeout) and retrieve its final state.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: timeout
// description: Timeout in seconds (-1 means never)
// type: integer
// example: -1
// responses:
// "200":
// description: Operation
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Operation"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func operationWaitGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
id, err := url.PathUnescape(mux.Vars(r)["id"])
if err != nil {
return response.SmartError(err)
}
secret := r.FormValue("secret")
trusted, _, _, _ := d.Authenticate(nil, r)
if !trusted && secret == "" {
return response.Forbidden(nil)
}
timeoutSecs := -1
if r.FormValue("timeout") != "" {
timeoutSecs, err = strconv.Atoi(r.FormValue("timeout"))
if err != nil {
return response.InternalError(err)
}
}
// First check if the query is for a local operation from this node
op, err := operations.OperationGetInternal(id)
if err == nil {
if secret != "" && op.Metadata()["secret"] != secret {
return response.Forbidden(nil)
}
var ctx context.Context
var cancel context.CancelFunc
// If timeout is -1, it will wait indefinitely otherwise it will timeout after timeoutSecs.
if timeoutSecs > -1 {
ctx, cancel = context.WithDeadline(r.Context(), time.Now().Add(time.Second*time.Duration(timeoutSecs)))
} else {
ctx, cancel = context.WithCancel(r.Context())
}
waitResponse := func(w http.ResponseWriter) error {
defer cancel()
// Write header to avoid client side timeouts.
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
f, ok := w.(http.Flusher)
if ok {
f.Flush()
}
// Wait for the operation.
_ = op.Wait(ctx)
// Render the current state.
_, body, err := op.Render()
if err != nil {
_ = response.SmartError(err).Render(w)
return nil
}
_ = response.SyncResponse(true, body).Render(w)
return nil
}
return response.ManualResponse(waitResponse)
}
// Then check if the query is from an operation on another node, and, if so, forward it
var address string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.OperationFilter{UUID: &id}
ops, err := dbCluster.GetOperations(ctx, tx.Tx(), filter)
if err != nil {
return err
}
if len(ops) < 1 {
return api.StatusErrorf(http.StatusNotFound, "Operation not found")
}
if len(ops) > 1 {
return errors.New("More than one operation matches")
}
operation := ops[0]
address = operation.NodeAddress
return nil
})
if err != nil {
return response.SmartError(err)
}
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, false)
if err != nil {
return response.SmartError(err)
}
return response.ForwardedResponse(client, r)
}
type operationWebSocket struct {
req *http.Request
op *operations.Operation
}
func (r *operationWebSocket) Render(w http.ResponseWriter) error {
chanErr, err := r.op.Connect(r.req, w)
if err != nil {
return err
}
err = <-chanErr
return err
}
func (r *operationWebSocket) String() string {
_, md, err := r.op.Render()
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return md.ID
}
// Code returns the HTTP code.
func (r *operationWebSocket) Code() int {
return http.StatusOK
}
// swagger:operation GET /1.0/operations/{id}/websocket?public operations operation_websocket_get_untrusted
//
// Get the websocket stream
//
// Connects to an associated websocket stream for the operation.
// This should almost never be done directly by a client, instead it's
// meant for server to server communication with the client only relaying the
// connection information to the servers.
//
// The untrusted endpoint is used by the target server to connect to the source server.
// Authentication is performed through the secret token.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: secret
// description: Authentication token
// type: string
// example: random-string
// responses:
// "200":
// description: Websocket operation messages (dependent on operation)
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/operations/{id}/websocket operations operation_websocket_get
//
// Get the websocket stream
//
// Connects to an associated websocket stream for the operation.
// This should almost never be done directly by a client, instead it's
// meant for server to server communication with the client only relaying the
// connection information to the servers.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: secret
// description: Authentication token
// type: string
// example: random-string
// responses:
// "200":
// description: Websocket operation messages (dependent on operation)
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func operationWebsocketGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
id, err := url.PathUnescape(mux.Vars(r)["id"])
if err != nil {
return response.SmartError(err)
}
// First check if the query is for a local operation from this node
op, err := operations.OperationGetInternal(id)
if err == nil {
return &operationWebSocket{r, op}
}
// Then check if the query is from an operation on another node, and, if so, forward it
secret := r.FormValue("secret")
if secret == "" {
return response.BadRequest(errors.New("Missing websocket secret"))
}
var address string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
filter := dbCluster.OperationFilter{UUID: &id}
ops, err := dbCluster.GetOperations(ctx, tx.Tx(), filter)
if err != nil {
return err
}
if len(ops) < 1 {
return api.StatusErrorf(http.StatusNotFound, "Operation not found")
}
if len(ops) > 1 {
return errors.New("More than one operation matches")
}
operation := ops[0]
address = operation.NodeAddress
return nil
})
if err != nil {
return response.SmartError(err)
}
client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), r, false)
if err != nil {
return response.SmartError(err)
}
source, err := client.GetOperationWebsocket(id, secret)
if err != nil {
return response.SmartError(err)
}
return operations.ForwardedOperationWebSocket(r, id, source)
}
func autoRemoveOrphanedOperationsTask(s *state.State) (task.Func, task.Schedule) {
f := func(ctx context.Context) {
localClusterAddress := s.LocalConfig.ClusterAddress()
leader, err := s.Cluster.LeaderAddress()
if err != nil {
if errors.Is(err, cluster.ErrNodeIsNotClustered) {
return // No error if not clustered.
}
logger.Error("Failed to get leader cluster member address", logger.Ctx{"err": err})
return
}
if localClusterAddress != leader {
logger.Debug("Skipping remove orphaned operations task since we're not leader")
return
}
opRun := func(op *operations.Operation) error {
return autoRemoveOrphanedOperations(ctx, s)
}
op, err := operations.OperationCreate(s, "", operations.OperationClassTask, operationtype.RemoveOrphanedOperations, nil, nil, opRun, nil, nil, nil)
if err != nil {
logger.Error("Failed creating remove orphaned operations operation", logger.Ctx{"err": err})
return
}
err = op.Start()
if err != nil {
logger.Error("Failed starting remove orphaned operations operation", logger.Ctx{"err": err})
return
}
err = op.Wait(ctx)
if err != nil {
logger.Error("Failed removing orphaned operations", logger.Ctx{"err": err})
return
}
}
return f, task.Hourly()
}
// autoRemoveOrphanedOperations removes old operations from offline members. Operations can be left
// behind if a cluster member abruptly becomes unreachable. If the affected cluster members comes
// back online, these operations won't be cleaned up. We therefore need to periodically clean up
// such operations.
func autoRemoveOrphanedOperations(ctx context.Context, s *state.State) error {
logger.Debug("Removing orphaned operations across the cluster")
offlineThreshold := s.GlobalConfig.OfflineThreshold()
err := s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
members, err := tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
for _, member := range members {
// Skip online nodes
if !member.IsOffline(offlineThreshold) {
continue
}
err = dbCluster.DeleteOperations(ctx, tx.Tx(), member.ID)
if err != nil {
return fmt.Errorf("Failed to delete operations: %w", err)
}
}
return nil
})
if err != nil {
return fmt.Errorf("Failed to remove orphaned operations: %w", err)
}
logger.Debug("Done removing orphaned operations across the cluster")
return nil
}
|