@@ -3,7 +3,9 @@ package docker
33import (
44 "context"
55 "crypto/tls"
6+ "io/ioutil"
67 "sort"
8+ "strings"
79 "testing"
810
911 "github.com/influxdata/telegraf/testutil"
@@ -747,3 +749,69 @@ func TestContainerStateFilter(t *testing.T) {
747749 })
748750 }
749751}
752+
753+ func TestContainerName (t * testing.T ) {
754+ tests := []struct {
755+ name string
756+ clientFunc func (host string , tlsConfig * tls.Config ) (Client , error )
757+ expected string
758+ }{
759+ {
760+ name : "container stats name is preferred" ,
761+ clientFunc : func (host string , tlsConfig * tls.Config ) (Client , error ) {
762+ client := baseClient
763+ client .ContainerListF = func (context.Context , types.ContainerListOptions ) ([]types.Container , error ) {
764+ var containers []types.Container
765+ containers = append (containers , types.Container {
766+ Names : []string {"/logspout/foo" },
767+ })
768+ return containers , nil
769+ }
770+ client .ContainerStatsF = func (ctx context.Context , containerID string , stream bool ) (types.ContainerStats , error ) {
771+ return types.ContainerStats {
772+ Body : ioutil .NopCloser (strings .NewReader (`{"name": "logspout"}` )),
773+ }, nil
774+ }
775+ return & client , nil
776+ },
777+ expected : "logspout" ,
778+ },
779+ {
780+ name : "container stats without name uses container list name" ,
781+ clientFunc : func (host string , tlsConfig * tls.Config ) (Client , error ) {
782+ client := baseClient
783+ client .ContainerListF = func (context.Context , types.ContainerListOptions ) ([]types.Container , error ) {
784+ var containers []types.Container
785+ containers = append (containers , types.Container {
786+ Names : []string {"/logspout" },
787+ })
788+ return containers , nil
789+ }
790+ client .ContainerStatsF = func (ctx context.Context , containerID string , stream bool ) (types.ContainerStats , error ) {
791+ return types.ContainerStats {
792+ Body : ioutil .NopCloser (strings .NewReader (`{}` )),
793+ }, nil
794+ }
795+ return & client , nil
796+ },
797+ expected : "logspout" ,
798+ },
799+ }
800+ for _ , tt := range tests {
801+ t .Run (tt .name , func (t * testing.T ) {
802+ d := Docker {
803+ newClient : tt .clientFunc ,
804+ }
805+ var acc testutil.Accumulator
806+ err := d .Gather (& acc )
807+ require .NoError (t , err )
808+
809+ for _ , metric := range acc .Metrics {
810+ // This tag is set on all container measurements
811+ if metric .Measurement == "docker_container_mem" {
812+ require .Equal (t , tt .expected , metric .Tags ["container_name" ])
813+ }
814+ }
815+ })
816+ }
817+ }
0 commit comments