github.com/netdata/go.d.plugin@v0.58.1/modules/dockerhub/dockerhub.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package dockerhub
     4  
     5  import (
     6  	_ "embed"
     7  	"time"
     8  
     9  	"github.com/netdata/go.d.plugin/pkg/web"
    10  
    11  	"github.com/netdata/go.d.plugin/agent/module"
    12  )
    13  
    14  const (
    15  	defaultURL         = "https://hub.docker.com/v2/repositories"
    16  	defaultHTTPTimeout = time.Second * 2
    17  
    18  	defaultUpdateEvery = 5
    19  )
    20  
    21  //go:embed "config_schema.json"
    22  var configSchema string
    23  
    24  func init() {
    25  	module.Register("dockerhub", module.Creator{
    26  		JobConfigSchema: configSchema,
    27  		Defaults: module.Defaults{
    28  			UpdateEvery: defaultUpdateEvery,
    29  		},
    30  		Create: func() module.Module { return New() },
    31  	})
    32  }
    33  
    34  // New creates DockerHub with default values.
    35  func New() *DockerHub {
    36  	config := Config{
    37  		HTTP: web.HTTP{
    38  			Request: web.Request{
    39  				URL: defaultURL,
    40  			},
    41  			Client: web.Client{
    42  				Timeout: web.Duration{Duration: defaultHTTPTimeout},
    43  			},
    44  		},
    45  	}
    46  	return &DockerHub{
    47  		Config: config,
    48  	}
    49  }
    50  
    51  // Config is the DockerHub module configuration.
    52  type Config struct {
    53  	web.HTTP     `yaml:",inline"`
    54  	Repositories []string
    55  }
    56  
    57  // DockerHub DockerHub module.
    58  type DockerHub struct {
    59  	module.Base
    60  	Config `yaml:",inline"`
    61  	client *apiClient
    62  }
    63  
    64  // Cleanup makes cleanup.
    65  func (DockerHub) Cleanup() {}
    66  
    67  // Init makes initialization.
    68  func (dh *DockerHub) Init() bool {
    69  	if dh.URL == "" {
    70  		dh.Error("URL not set")
    71  		return false
    72  	}
    73  
    74  	if len(dh.Repositories) == 0 {
    75  		dh.Error("repositories parameter is not set")
    76  		return false
    77  	}
    78  
    79  	client, err := web.NewHTTPClient(dh.Client)
    80  	if err != nil {
    81  		dh.Errorf("error on creating http client : %v", err)
    82  		return false
    83  	}
    84  	dh.client = newAPIClient(client, dh.Request)
    85  
    86  	return true
    87  }
    88  
    89  // Check makes check.
    90  func (dh DockerHub) Check() bool {
    91  	return len(dh.Collect()) > 0
    92  }
    93  
    94  // Charts creates Charts.
    95  func (dh DockerHub) Charts() *Charts {
    96  	cs := charts.Copy()
    97  	addReposToCharts(dh.Repositories, cs)
    98  	return cs
    99  }
   100  
   101  // Collect collects metrics.
   102  func (dh *DockerHub) Collect() map[string]int64 {
   103  	mx, err := dh.collect()
   104  
   105  	if err != nil {
   106  		dh.Error(err)
   107  		return nil
   108  	}
   109  
   110  	return mx
   111  }