github.com/vmware/govmomi@v0.51.0/vapi/cis/tasks/tasks.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package tasks
     6  
     7  import (
     8  	"context"
     9  	"net/http"
    10  	"time"
    11  
    12  	"github.com/vmware/govmomi/vapi/rest"
    13  )
    14  
    15  const (
    16  	// TasksPath The endpoint for retrieving tasks
    17  	TasksPath = "/api/cis/tasks"
    18  	// The default interval in seconds for polling for task results
    19  	defaultPollingInterval = 10
    20  )
    21  
    22  // Manager extends rest.Client, adding task related methods.
    23  type Manager struct {
    24  	*rest.Client
    25  	pollingInterval int
    26  }
    27  
    28  // NewManager creates a new Manager instance with the given client.
    29  func NewManager(client *rest.Client) *Manager {
    30  	return &Manager{
    31  		Client:          client,
    32  		pollingInterval: defaultPollingInterval,
    33  	}
    34  }
    35  
    36  // NewManager creates a new Manager instance with the given client and custom polling interval
    37  func NewManagerWithCustomInterval(client *rest.Client, pollingInterval int) *Manager {
    38  	return &Manager{
    39  		Client:          client,
    40  		pollingInterval: pollingInterval,
    41  	}
    42  }
    43  
    44  func (c *Manager) WaitForCompletion(ctx context.Context, taskId string) (string, error) {
    45  	ticker := time.NewTicker(time.Second * time.Duration(c.pollingInterval))
    46  
    47  	for {
    48  		select {
    49  		case <-ctx.Done():
    50  		case <-ticker.C:
    51  			taskInfo, err := c.getTaskInfo(taskId)
    52  			status := taskInfo["status"].(string)
    53  			if err != nil {
    54  				return status, err
    55  			}
    56  
    57  			if status != "RUNNING" {
    58  				return status, nil
    59  			}
    60  		}
    61  	}
    62  }
    63  
    64  func (c *Manager) getTaskInfo(taskId string) (map[string]any, error) {
    65  	path := c.Resource(TasksPath).WithSubpath(taskId)
    66  	req := path.Request(http.MethodGet)
    67  	var res map[string]any
    68  	return res, c.Do(context.Background(), req, &res)
    69  }