Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Bearer Token authentication #17

Merged
merged 1 commit into from
Jan 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,36 @@ A [Prometheus](https://prometheus.io) exporter for [JFrog Artifactory](https://j


## Note

This exporter is under development and more metrics will be added later. Tested on Artifactory Enterprise and OSS version `6.16.0`.

## Authentication

The Artifactory provider supports multiple means of authentication. The following methods are supported:
* Basic Auth
* Bearer Token

### Basic Auth

Basic auth may be used by setting `ARTI_USERNAME` and `ARTI_PASSWORD` environment variables.

### Bearer Token

Artifactory access tokens may be used via the Authorization header by setting `ARTI_ACCESS_TOKEN` environment variable.

## Usage

### Binary

Download the binary for your operation system from [release](https://github.com/peimanja/artifactory_exporter/releases) page and run it:
```bash
$ ./artifactory_exporter <flags>
```

### Docker

Set the `ARTI_USERNAME` and `ARTI_PASSWORD` in `env_file_name` and run the artifactory exporter as a Docker container:
Set the credentials in `env_file_name` and you can deploy this exporter using the [peimanja/artifactory_exporter](https://registry.hub.docker.com/r/peimanja/artifactory_exporter/) Docker image:
:

```bash
$ docker run --env-file=env_file_name -p 9531:9531 peimanja/artifactory_exporter:latest <flags>
Expand Down Expand Up @@ -45,8 +68,11 @@ Flags:
| `artifactory.scrape-uri`<br/>`ARTI_SCRAPE_URI` | No | `http://localhost:8081/artifactory` | URI on which to scrape JFrog Artifactory. |
| `artifactory.ssl-verify`<br/>`ARTI_SSL_VERIFY` | No | `true` | Flag that enables SSL certificate verification for the scrape URI. |
| `artifactory.timeout`<br/>`ARTI_TIMEOUT` | No | `5s` | Timeout for trying to get stats from JFrog Artifactory. |
| `ARTI_USERNAME` | Yes | | User to access Artifactory |
| `ARTI_PASSWORD` | Yes | | Password of the user accessing the Artifactory |
| `ARTI_USERNAME` | *No | | User to access Artifactory |
| `ARTI_PASSWORD` | *No | | Password of the user accessing the Artifactory |
| `ARTI_ACCESS_TOKEN` | *No | | Access token for accessing the Artifactory |

* Either `ARTI_USERNAME` and `ARTI_PASSWORD` or `ARTI_ACCESS_TOKEN` environment variables has to be set.

### Metrics

Expand Down
30 changes: 18 additions & 12 deletions collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,27 @@ var (
// Exporter collects JFrog Artifactory stats from the given URI and
// exports them using the prometheus metrics package.
type Exporter struct {
URI string
bc config.BasicCredentials
sslVerify bool
timeout time.Duration
mutex sync.RWMutex
URI string
cred config.Credentials
authMethod string
sslVerify bool
timeout time.Duration
mutex sync.RWMutex

up prometheus.Gauge
totalScrapes, jsonParseFailures prometheus.Counter
logger log.Logger
}

// NewExporter returns an initialized Exporter.
func NewExporter(uri string, bc config.BasicCredentials, sslVerify bool, timeout time.Duration, logger log.Logger) (*Exporter, error) {
func NewExporter(uri string, cred config.Credentials, authMethod string, sslVerify bool, timeout time.Duration, logger log.Logger) (*Exporter, error) {

return &Exporter{
URI: uri,
bc: bc,
sslVerify: sslVerify,
timeout: timeout,
URI: uri,
cred: cred,
authMethod: authMethod,
sslVerify: sslVerify,
timeout: timeout,
up: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Expand Down Expand Up @@ -139,7 +141,7 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
ch <- e.jsonParseFailures
}

func fetchHTTP(uri string, path string, bc config.BasicCredentials, sslVerify bool, timeout time.Duration) ([]byte, error) {
func fetchHTTP(uri string, path string, cred config.Credentials, authMethod string, sslVerify bool, timeout time.Duration) ([]byte, error) {
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}}
client := http.Client{
Timeout: timeout,
Expand All @@ -150,7 +152,11 @@ func fetchHTTP(uri string, path string, bc config.BasicCredentials, sslVerify bo
if err != nil {
return nil, err
}
req.SetBasicAuth(bc.Username, bc.Password)
if authMethod == "userPass" {
req.SetBasicAuth(cred.Username, cred.Password)
} else if authMethod == "accessToken" {
req.Header.Add("Authorization", "Bearer "+cred.AccessToken)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion collector/replication.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type replication struct {

func (e *Exporter) fetchReplications() ([]replication, error) {
var replications []replication
resp, err := fetchHTTP(e.URI, "replications", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "replications", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions collector/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type user struct {

func (e *Exporter) fetchUsers() ([]user, error) {
var users []user
resp, err := fetchHTTP(e.URI, "security/users", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "security/users", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -62,7 +62,7 @@ type group struct {

func (e *Exporter) fetchGroups() ([]group, error) {
var groups []group
resp, err := fetchHTTP(e.URI, "security/groups", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "security/groups", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion collector/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ type storageInfo struct {

func (e *Exporter) fetchStorageInfo() (storageInfo, error) {
var storageInfo storageInfo
resp, err := fetchHTTP(e.URI, "storageinfo", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "storageinfo", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return storageInfo, err
}
Expand Down
6 changes: 3 additions & 3 deletions collector/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package collector
import "encoding/json"

func (e *Exporter) fetchHealth() (float64, error) {
resp, err := fetchHTTP(e.URI, "system/ping", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "system/ping", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return 0, err
}
Expand All @@ -21,7 +21,7 @@ type buildInfo struct {

func (e *Exporter) fetchBuildInfo() (buildInfo, error) {
var buildInfo buildInfo
resp, err := fetchHTTP(e.URI, "system/version", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "system/version", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return buildInfo, err
}
Expand All @@ -40,7 +40,7 @@ type licenseInfo struct {

func (e *Exporter) fetchLicense() (licenseInfo, error) {
var licenseInfo licenseInfo
resp, err := fetchHTTP(e.URI, "system/license", e.bc, e.sslVerify, e.timeout)
resp, err := fetchHTTP(e.URI, "system/license", e.cred, e.authMethod, e.sslVerify, e.timeout)
if err != nil {
return licenseInfo, err
}
Expand Down
43 changes: 28 additions & 15 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"fmt"
"net/url"
"time"

Expand All @@ -15,25 +16,28 @@ var (
listenAddress = kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Envar("WEB_LISTEN_ADDR").Default(":9531").String()
metricsPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Envar("WEB_TELEMETRY_PATH").Default("/metrics").String()
artiScrapeURI = kingpin.Flag("artifactory.scrape-uri", "URI on which to scrape JFrog Artifactory.").Envar("ARTI_SCRAPE_URI").Default("http://localhost:8081/artifactory").String()
artiSSLVerify = kingpin.Flag("artifactory.ssl-verify", "Flag that enables SSL certificate verification for the scrape URI").Envar("ARTI_SSL_VERIFY").Default("true").Bool()
artiSSLVerify = kingpin.Flag("artifactory.ssl-verify", "Flag that enables SSL certificate verification for the scrape URI").Envar("ARTI_SSL_VERIFY").Default("false").Bool()
artiTimeout = kingpin.Flag("artifactory.timeout", "Timeout for trying to get stats from JFrog Artifactory.").Envar("ARTI_TIMEOUT").Default("5s").Duration()
)

// BasicCredentials represents Username and Password for Artifactory HTTP Basic Authentication
type BasicCredentials struct {
Username string `required:"true" envconfig:"ARTI_USERNAME"`
Password string `required:"true" envconfig:"ARTI_PASSWORD"`
// Credentials represents Username and Password or API Key for
// Artifactory Authentication
type Credentials struct {
Username string `required:"false" envconfig:"ARTI_USERNAME"`
Password string `required:"false" envconfig:"ARTI_PASSWORD"`
AccessToken string `required:"false" envconfig:"ARTI_ACCESS_TOKEN"`
}

// Config represents all configuration options for running the Exporter.
type Config struct {
ListenAddress string
MetricsPath string
ArtiScrapeURI string
BasicCredentials *BasicCredentials
ArtiSSLVerify bool
ArtiTimeout time.Duration
Logger log.Logger
ListenAddress string
MetricsPath string
ArtiScrapeURI string
Credentials *Credentials
AuthMethod string
ArtiSSLVerify bool
ArtiTimeout time.Duration
Logger log.Logger
}

// NewConfig Creates new Artifactory exporter Config
Expand All @@ -45,11 +49,19 @@ func NewConfig() (*Config, error) {
kingpin.Parse()
logger := promlog.New(promlogConfig)

var basicCredentials BasicCredentials
err := envconfig.Process("", &basicCredentials)
var credentials Credentials
var authMethod string
err := envconfig.Process("", &credentials)
if err != nil {
return nil, err
}
if credentials.Username != "" && credentials.Password != "" && credentials.AccessToken == "" {
authMethod = "userPass"
} else if credentials.Username == "" && credentials.Password == "" && credentials.AccessToken != "" {
authMethod = "accessToken"
} else {
return nil, fmt.Errorf("`ARTI_USERNAME` and `ARTI_PASSWORD` or `ARTI_ACCESS_TOKEN` environment variable hast to be set.")
}

u, err := url.Parse(*artiScrapeURI)
if err != nil {
Expand All @@ -62,7 +74,8 @@ func NewConfig() (*Config, error) {
*listenAddress,
*metricsPath,
*artiScrapeURI,
&basicCredentials,
&credentials,
authMethod,
*artiSSLVerify,
*artiTimeout,
logger,
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func main() {
os.Exit(1)
}

exporter, err := collector.NewExporter(c.ArtiScrapeURI, *c.BasicCredentials, c.ArtiSSLVerify, c.ArtiTimeout, c.Logger)
exporter, err := collector.NewExporter(c.ArtiScrapeURI, *c.Credentials, c.AuthMethod, c.ArtiSSLVerify, c.ArtiTimeout, c.Logger)
if err != nil {
level.Error(c.Logger).Log("msg", "Error creating an exporter", "err", err)
os.Exit(1)
Expand Down