| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package client |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "net/url" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/vmware/govmomi" |
| 11 | "github.com/vmware/govmomi/session" |
| 12 | "github.com/vmware/govmomi/vim25/methods" |
| 13 | "github.com/vmware/govmomi/vim25/soap" |
| 14 | "github.com/vmware/govmomi/vim25/types" |
| 15 | ) |
| 16 | |
| 17 | const ( |
| 18 | keepAliveEvery = time.Second * 15 |
| 19 | ) |
| 20 | |
| 21 | // TODO: survive vCenter reboot, it looks like we need to re New() |
| 22 | func addKeepAlive(client *govmomi.Client, userinfo *url.Userinfo) { |
| 23 | f := func(rt soap.RoundTripper) error { |
| 24 | _, err := methods.GetCurrentTime(context.Background(), rt) |
| 25 | if err == nil { |
| 26 | return nil |
| 27 | } |
| 28 | |
| 29 | if !isNotAuthenticated(err) { |
| 30 | return nil |
| 31 | } |
| 32 | |
| 33 | _ = client.Login(context.Background(), userinfo) |
| 34 | return nil |
| 35 | } |
| 36 | client.Client.RoundTripper = session.KeepAliveHandler(client.Client.RoundTripper, keepAliveEvery, f) |
| 37 | } |
| 38 | |
| 39 | func isNotAuthenticated(err error) bool { |
| 40 | if !soap.IsSoapFault(err) { |
| 41 | return false |
| 42 | } |
| 43 | _, ok := soap.ToSoapFault(err).VimFault().(*types.NotAuthenticated) |
| 44 | return ok |
| 45 | } |