summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/vsphere/client/keepalive.go
blob: 0ce1ef5c063b6f8ab7991382b1a45c91a0ec23cf (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package client

import (
	"context"
	"net/url"
	"time"

	"github.com/vmware/govmomi"
	"github.com/vmware/govmomi/session"
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/soap"
	"github.com/vmware/govmomi/vim25/types"
)

const (
	keepAliveEvery = time.Second * 15
)

// TODO: survive vCenter reboot, it looks like we need to re New()
func addKeepAlive(client *govmomi.Client, userinfo *url.Userinfo) {
	f := func(rt soap.RoundTripper) error {
		_, err := methods.GetCurrentTime(context.Background(), rt)
		if err == nil {
			return nil
		}

		if !isNotAuthenticated(err) {
			return nil
		}

		_ = client.Login(context.Background(), userinfo)
		return nil
	}
	client.Client.RoundTripper = session.KeepAliveHandler(client.Client.RoundTripper, keepAliveEvery, f)
}

func isNotAuthenticated(err error) bool {
	if !soap.IsSoapFault(err) {
		return false
	}
	_, ok := soap.ToSoapFault(err).VimFault().(*types.NotAuthenticated)
	return ok
}