github.com/waldiirawan/apm-agent-go/v2@v2.2.2/internal/apmhostutil/container_test.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package apmhostutil_test
    19  
    20  import (
    21  	"io/ioutil"
    22  	"os"
    23  	"runtime"
    24  	"strings"
    25  	"testing"
    26  
    27  	"github.com/stretchr/testify/assert"
    28  	"github.com/stretchr/testify/require"
    29  
    30  	"github.com/waldiirawan/apm-agent-go/v2/internal/apmhostutil"
    31  )
    32  
    33  func TestContainerID(t *testing.T) {
    34  	if runtime.GOOS != "linux" {
    35  		// Currently we only support Container in Linux containers.
    36  		_, err := apmhostutil.Container()
    37  		assert.Error(t, err)
    38  		return
    39  	}
    40  
    41  	// Ideally we would have the CI script pass the
    42  	// docker container ID into the test process,
    43  	// but this would make things convoluted. Instead,
    44  	// just do a basic check of cgroup to see if it's
    45  	// Docker-enabled, and then compare the ID to
    46  	// the container hostname.
    47  	data, err := ioutil.ReadFile("/proc/self/cgroup")
    48  	if err != nil {
    49  		t.Skipf("failed to read cgroup (%s)", err)
    50  	}
    51  	if !strings.Contains(string(data), "docker") {
    52  		t.Skipf("not running inside docker")
    53  	}
    54  
    55  	container, err := apmhostutil.Container()
    56  	require.NoError(t, err)
    57  	require.NotNil(t, container)
    58  	assert.Len(t, container.ID, 64)
    59  
    60  	// Docker sets the container hostname to a prefix
    61  	// of the full container ID.
    62  	hostname, err := os.Hostname()
    63  	require.NoError(t, err)
    64  	assert.Equal(t, hostname, container.ID[:len(hostname)])
    65  }