Make uptime available in the stat output for a container

This commit is contained in:
Dane Everitt
2021-10-03 12:59:03 -07:00
parent 0cfd72e1d1
commit d9ebf693e0
4 changed files with 37 additions and 7 deletions

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"math"
"time"
"emperror.dev/errors"
"github.com/docker/docker/api/types"
@@ -12,6 +13,23 @@ import (
"github.com/pterodactyl/wings/environment"
)
// Uptime returns the current uptime of the container in milliseconds. If the
// container is not currently running this will return 0.
func (e *Environment) Uptime(ctx context.Context) (int64, error) {
ins, err := e.client.ContainerInspect(ctx, e.Id)
if err != nil {
return 0, errors.Wrap(err, "environment: could not inspect container")
}
if !ins.State.Running {
return 0, nil
}
started, err := time.Parse(time.RFC3339, ins.State.StartedAt)
if err != nil {
return 0, errors.Wrap(err, "environment: failed to parse container start time")
}
return time.Since(started).Milliseconds(), nil
}
// Attach to the instance and then automatically emit an event whenever the resource usage for the
// server process changes.
func (e *Environment) pollResources(ctx context.Context) error {
@@ -28,6 +46,11 @@ func (e *Environment) pollResources(ctx context.Context) error {
}
defer stats.Body.Close()
uptime, err := e.Uptime(ctx)
if err != nil {
e.log().WithField("error", err).Warn("failed to calculate container uptime")
}
dec := json.NewDecoder(stats.Body)
for {
select {
@@ -50,7 +73,12 @@ func (e *Environment) pollResources(ctx context.Context) error {
return nil
}
if !v.PreRead.IsZero() {
uptime = uptime + v.Read.Sub(v.PreRead).Milliseconds()
}
st := environment.Stats{
Uptime: uptime,
Memory: calculateDockerMemory(v.MemoryStats),
MemoryLimit: v.MemoryStats.Limit,
CpuAbsolute: calculateDockerAbsoluteCpu(v.PreCPUStats, v.CPUStats),