github.com/google/cadvisor@v0.49.1/collector/generic_collector_test.go (about)

     1  // Copyright 2015 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package collector
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"os"
    22  	"testing"
    23  
    24  	"github.com/stretchr/testify/assert"
    25  
    26  	containertest "github.com/google/cadvisor/container/testing"
    27  	v1 "github.com/google/cadvisor/info/v1"
    28  )
    29  
    30  func TestEmptyConfig(t *testing.T) {
    31  	assert := assert.New(t)
    32  
    33  	emptyConfig := `
    34          {
    35                  "endpoint" : "http://localhost:8000/nginx_status",
    36                  "metrics_config"  : [
    37                  ]
    38          }
    39          `
    40  
    41  	// Create a temporary config file 'temp.json' with invalid json format
    42  	assert.NoError(os.WriteFile("temp.json", []byte(emptyConfig), 0777))
    43  
    44  	configFile, err := os.ReadFile("temp.json")
    45  	assert.NoError(err)
    46  
    47  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
    48  	_, err = NewCollector("tempCollector", configFile, 100, containerHandler, http.DefaultClient)
    49  	assert.Error(err)
    50  
    51  	assert.NoError(os.Remove("temp.json"))
    52  }
    53  
    54  func TestConfigWithErrors(t *testing.T) {
    55  	assert := assert.New(t)
    56  
    57  	// Syntax error: Missed '"' after activeConnections
    58  	invalid := `
    59  	{
    60  		"endpoint" : "http://localhost:8000/nginx_status",
    61  		"metrics_config"  : [
    62  			{
    63  				 "name" : "activeConnections,  
    64  		  		 "metric_type" : "gauge",
    65  		 	 	 "data_type" : "int",
    66  		  		 "polling_frequency" : 10,
    67  		    		 "regex" : "Active connections: ([0-9]+)"			
    68  			}
    69  		]
    70  	}
    71  	`
    72  
    73  	// Create a temporary config file 'temp.json' with invalid json format
    74  	assert.NoError(os.WriteFile("temp.json", []byte(invalid), 0777))
    75  	configFile, err := os.ReadFile("temp.json")
    76  	assert.NoError(err)
    77  
    78  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
    79  	_, err = NewCollector("tempCollector", configFile, 100, containerHandler, http.DefaultClient)
    80  	assert.Error(err)
    81  
    82  	assert.NoError(os.Remove("temp.json"))
    83  }
    84  
    85  func TestConfigWithRegexErrors(t *testing.T) {
    86  	assert := assert.New(t)
    87  
    88  	// Error: Missed operand for '+' in activeConnections regex
    89  	invalid := `
    90          {
    91                  "endpoint" : "host:port/nginx_status",
    92                  "metrics_config"  : [
    93                          {
    94                                   "name" : "activeConnections",
    95                                   "metric_type" : "gauge",
    96                                   "data_type" : "int",
    97                                   "polling_frequency" : 10,
    98                                   "regex" : "Active connections: (+)"
    99                          },
   100                          {
   101                                   "name" : "reading",
   102                                   "metric_type" : "gauge",
   103                                   "data_type" : "int",
   104                                   "polling_frequency" : 10,
   105                                   "regex" : "Reading: ([0-9]+) .*"
   106                          }
   107                  ]
   108          }
   109          `
   110  
   111  	// Create a temporary config file 'temp.json'
   112  	assert.NoError(os.WriteFile("temp.json", []byte(invalid), 0777))
   113  
   114  	configFile, err := os.ReadFile("temp.json")
   115  	assert.NoError(err)
   116  
   117  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
   118  	_, err = NewCollector("tempCollector", configFile, 100, containerHandler, http.DefaultClient)
   119  	assert.Error(err)
   120  
   121  	assert.NoError(os.Remove("temp.json"))
   122  }
   123  
   124  func TestConfig(t *testing.T) {
   125  	assert := assert.New(t)
   126  
   127  	// Create an nginx collector using the config file 'sample_config.json'
   128  	configFile, err := os.ReadFile("config/sample_config.json")
   129  	assert.NoError(err)
   130  
   131  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
   132  	collector, err := NewCollector("nginx", configFile, 100, containerHandler, http.DefaultClient)
   133  	assert.NoError(err)
   134  	assert.Equal(collector.name, "nginx")
   135  	assert.Equal(collector.configFile.Endpoint.URL, "http://localhost:8000/nginx_status")
   136  	assert.Equal(collector.configFile.MetricsConfig[0].Name, "activeConnections")
   137  }
   138  
   139  func TestEndpointConfig(t *testing.T) {
   140  	assert := assert.New(t)
   141  	configFile, err := os.ReadFile("config/sample_config_endpoint_config.json")
   142  	assert.NoError(err)
   143  
   144  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
   145  	containerHandler.On("GetContainerIPAddress").Return(
   146  		"111.111.111.111",
   147  	)
   148  
   149  	collector, err := NewCollector("nginx", configFile, 100, containerHandler, http.DefaultClient)
   150  	assert.NoError(err)
   151  	assert.Equal(collector.name, "nginx")
   152  	assert.Equal(collector.configFile.Endpoint.URL, "https://111.111.111.111:8000/nginx_status")
   153  	assert.Equal(collector.configFile.MetricsConfig[0].Name, "activeConnections")
   154  }
   155  
   156  func TestMetricCollection(t *testing.T) {
   157  	assert := assert.New(t)
   158  
   159  	// Collect nginx metrics from a fake nginx endpoint
   160  	configFile, err := os.ReadFile("config/sample_config.json")
   161  	assert.NoError(err)
   162  
   163  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
   164  	fakeCollector, err := NewCollector("nginx", configFile, 100, containerHandler, http.DefaultClient)
   165  	assert.NoError(err)
   166  
   167  	tempServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   168  		fmt.Fprintln(w, "Active connections: 3\nserver accepts handled requests")
   169  		fmt.Fprintln(w, "5 5 32\nReading: 0 Writing: 1 Waiting: 2")
   170  	}))
   171  	defer tempServer.Close()
   172  	fakeCollector.configFile.Endpoint.URL = tempServer.URL
   173  
   174  	metrics := map[string][]v1.MetricVal{}
   175  	_, metrics, errMetric := fakeCollector.Collect(metrics)
   176  	assert.NoError(errMetric)
   177  	metricNames := []string{"activeConnections", "reading", "writing", "waiting"}
   178  	// activeConnections = 3
   179  	assert.Equal(metrics[metricNames[0]][0].IntValue, int64(3))
   180  	assert.Equal(metrics[metricNames[0]][0].FloatValue, float64(0))
   181  	// reading = 0
   182  	assert.Equal(metrics[metricNames[1]][0].IntValue, int64(0))
   183  	assert.Equal(metrics[metricNames[1]][0].FloatValue, float64(0))
   184  	// writing = 1
   185  	assert.Equal(metrics[metricNames[2]][0].IntValue, int64(1))
   186  	assert.Equal(metrics[metricNames[2]][0].FloatValue, float64(0))
   187  	// waiting = 2
   188  	assert.Equal(metrics[metricNames[3]][0].IntValue, int64(2))
   189  	assert.Equal(metrics[metricNames[3]][0].FloatValue, float64(0))
   190  }
   191  
   192  func TestMetricCollectionLimit(t *testing.T) {
   193  	assert := assert.New(t)
   194  
   195  	// Collect nginx metrics from a fake nginx endpoint
   196  	configFile, err := os.ReadFile("config/sample_config.json")
   197  	assert.NoError(err)
   198  
   199  	containerHandler := containertest.NewMockContainerHandler("mockContainer")
   200  	_, err = NewCollector("nginx", configFile, 1, containerHandler, http.DefaultClient)
   201  	assert.Error(err)
   202  }