github.com/vmware/govmomi@v0.43.0/vapi/cis/tasks/tasks.go (about) 1 /* 2 Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tasks 18 19 import ( 20 "context" 21 "net/http" 22 "time" 23 24 "github.com/vmware/govmomi/vapi/rest" 25 ) 26 27 const ( 28 // TasksPath The endpoint for retrieving tasks 29 TasksPath = "/api/cis/tasks" 30 // The default interval in seconds for polling for task results 31 defaultPollingInterval = 10 32 ) 33 34 // Manager extends rest.Client, adding task related methods. 35 type Manager struct { 36 *rest.Client 37 pollingInterval int 38 } 39 40 // NewManager creates a new Manager instance with the given client. 41 func NewManager(client *rest.Client) *Manager { 42 return &Manager{ 43 Client: client, 44 pollingInterval: defaultPollingInterval, 45 } 46 } 47 48 // NewManager creates a new Manager instance with the given client and custom polling interval 49 func NewManagerWithCustomInterval(client *rest.Client, pollingInterval int) *Manager { 50 return &Manager{ 51 Client: client, 52 pollingInterval: pollingInterval, 53 } 54 } 55 56 func (c *Manager) WaitForCompletion(ctx context.Context, taskId string) (string, error) { 57 ticker := time.NewTicker(time.Second * time.Duration(c.pollingInterval)) 58 59 for { 60 select { 61 case <-ctx.Done(): 62 case <-ticker.C: 63 taskInfo, err := c.getTaskInfo(taskId) 64 status := taskInfo["status"].(string) 65 if err != nil { 66 return status, err 67 } 68 69 if status != "RUNNING" { 70 return status, nil 71 } 72 } 73 } 74 } 75 76 func (c *Manager) getTaskInfo(taskId string) (map[string]interface{}, error) { 77 path := c.Resource(TasksPath).WithSubpath(taskId) 78 req := path.Request(http.MethodGet) 79 var res map[string]interface{} 80 return res, c.Do(context.Background(), req, &res) 81 }