| 1 | |
| 2 | |
| 3 | |
| 4 | package hostagent |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/sirupsen/logrus" |
| 11 | ) |
| 12 | |
| 13 | const ( |
| 14 | timeSyncInterval = 10 * time.Second |
| 15 | timeSyncStartupDelay = 5 * time.Second |
| 16 | ) |
| 17 | |
| 18 | func (a *HostAgent) startTimeSync(ctx context.Context) { |
| 19 | select { |
| 20 | case <-a.guestAgentAliveCh: |
| 21 | logrus.Info("Time sync: guest agent is alive, starting time synchronization") |
| 22 | case <-ctx.Done(): |
| 23 | return |
| 24 | } |
| 25 | |
| 26 | select { |
| 27 | case <-time.After(timeSyncStartupDelay): |
| 28 | case <-ctx.Done(): |
| 29 | return |
| 30 | } |
| 31 | |
| 32 | ticker := time.NewTicker(timeSyncInterval) |
| 33 | defer ticker.Stop() |
| 34 | |
| 35 | a.syncTimeOnce(ctx) |
| 36 | |
| 37 | for { |
| 38 | select { |
| 39 | case <-ctx.Done(): |
| 40 | logrus.Debug("Time sync: context cancelled, stopping") |
| 41 | return |
| 42 | case <-ticker.C: |
| 43 | a.syncTimeOnce(ctx) |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | func (a *HostAgent) syncTimeOnce(ctx context.Context) { |
| 49 | client, err := a.getOrCreateClient(ctx) |
| 50 | if err != nil { |
| 51 | logrus.WithError(err).Debug("Time sync: failed to get client") |
| 52 | return |
| 53 | } |
| 54 | |
| 55 | hostTime := time.Now() |
| 56 | resp, err := client.SyncTime(ctx, hostTime) |
| 57 | if err != nil { |
| 58 | logrus.WithError(err).Debug("Time sync: RPC failed") |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | if resp.Error != "" { |
| 63 | logrus.Warnf("Time sync: guest failed to set time: %#q (drift was %dms)", resp.Error, resp.DriftMs) |
| 64 | return |
| 65 | } |
| 66 | |
| 67 | if resp.Adjusted { |
| 68 | logrus.Infof("Time sync: guest clock adjusted (was %dms off)", resp.DriftMs) |
| 69 | } else { |
| 70 | logrus.Debugf("Time sync: drift %dms within threshold", resp.DriftMs) |
| 71 | } |
| 72 | } |