Skip to content

Commit

Permalink
Merge pull request #3 from promhippie/fix-auth
Browse files Browse the repository at this point in the history
Fix authentication timeout/invalidation
  • Loading branch information
tboerger authored Jul 2, 2020
2 parents 26bc7ef + ee058d7 commit 82f96af
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 90 deletions.
8 changes: 8 additions & 0 deletions .codacy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
exclude_paths:
- .github/*.md
- CODE_OF_CONDUCT.md
- CHANGELOG.md
- changelog/**/*.md

...
24 changes: 22 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
# Changelog for unreleased
# Changelog for 0.1.1

The following sections list the changes for unreleased.
The following sections list the changes for 0.1.1.

## Summary

* Fix #2: Fix authentication timeout/invalidation

## Details

* Bugfix #2: Fix authentication timeout/invalidation

When running the service it happened that the authentication had been invalidated or simply
timed out, this should be fixed by simply authenticating the defined user before looping
through all the results. At the end also the disconnect function from the used library gets
executed.

https://github.com/promhippie/prometheus-vcd-sd/issues/2


# Changelog for 0.1.0

The following sections list the changes for 0.1.0.

## Summary

Expand Down
151 changes: 102 additions & 49 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -1,76 +1,129 @@

# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:
Examples of behavior that contributes to a positive environment for our
community include:

- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior by participants include:
Examples of unacceptable behavior include:

- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities
## Enforcement Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [[email protected].](mailto:[email protected].) All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
reported to the community leaders responsible for enforcement at
[email protected]. All complaints will be reviewed and investigated
promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at <https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
<https://www.contributor-covenant.org/faq>
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ The following list of meta labels can be used to relabel your scrape results ent

Here you get a snippet for the Prometheus `scrape_config` that configures Prometheus to scrape `node_exporter` assuming that it is deployed on all your servers.

```
```yml
- job_name: node
file_sd_configs:
- files: [ "/etc/prometheus/vcd.json" ]
Expand All @@ -54,7 +54,7 @@ Here you get a snippet for the Prometheus `scrape_config` that configures Promet
Make sure you have a working Go environment, for further reference or a guide take a look at the [install instructions](http://golang.org/doc/install.html). This project requires Go >= v1.11.
```bash
```console
git clone https://github.com/promhippie/prometheus-vcd-sd.git
cd prometheus-vcd-sd

Expand Down
File renamed without changes.
8 changes: 8 additions & 0 deletions changelog/0.1.1_2020-07-02/auth-timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Bugfix: Fix authentication timeout/invalidation

When running the service it happened that the authentication had been
invalidated or simply timed out, this should be fixed by simply authenticating
the defined user before looping through all the results. At the end also the
disconnect function from the used library gets executed.

https://github.com/promhippie/prometheus-vcd-sd/issues/2
37 changes: 21 additions & 16 deletions pkg/action/discoverer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/vmware/go-vcloud-director/v2/govcd"
"github.com/promhippie/prometheus-vcd-sd/pkg/client"
)

const (
Expand All @@ -33,21 +33,11 @@ const (
var (
// ErrClientEndpoint defines an error if the client auth fails.
ErrClientEndpoint = errors.New("failed to parse api url")

// ErrClientAuth defines an error if the client auth fails.
ErrClientAuth = errors.New("failed to authenticate client")
)

// Config wraps the vCloud Director client including org and vdc names.
type Config struct {
client *govcd.VCDClient
org string
vdc string
}

// Discoverer implements the Prometheus discoverer interface.
type Discoverer struct {
configs map[string]*Config
configs map[string]*client.Client
logger log.Logger
refresh int
separator string
Expand Down Expand Up @@ -79,8 +69,21 @@ func (d *Discoverer) getTargets(ctx context.Context) ([]*targetgroup.Group, erro
targets := make([]*targetgroup.Group, 0)

for project, config := range d.configs {
if err := config.Authenticate(); err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to authenticate",
"project", project,
"err", err,
)

requestFailures.WithLabelValues(project, "auth").Inc()
continue
}

defer config.Disconnect()

nowOrg := time.Now()
org, err := config.client.GetOrgByNameOrId(config.org)
org, err := config.Upstream.GetOrgByNameOrId(config.Organization)
requestDuration.WithLabelValues(project, "org").Observe(time.Since(nowOrg).Seconds())

if err != nil {
Expand All @@ -95,7 +98,7 @@ func (d *Discoverer) getTargets(ctx context.Context) ([]*targetgroup.Group, erro
}

nowVdc := time.Now()
vdc, err := org.GetVDCByNameOrId(config.vdc, false)
vdc, err := org.GetVDCByNameOrId(config.Datacenter, false)
requestDuration.WithLabelValues(project, "vdc").Observe(time.Since(nowVdc).Seconds())

if err != nil {
Expand Down Expand Up @@ -194,8 +197,8 @@ func (d *Discoverer) getTargets(ctx context.Context) ([]*targetgroup.Group, erro
Labels: model.LabelSet{
model.AddressLabel: model.LabelValue(vm.VM.NetworkConnectionSection.NetworkConnection[0].IPAddress),
model.LabelName(projectLabel): model.LabelValue(project),
model.LabelName(orgLabel): model.LabelValue(config.org),
model.LabelName(vdcLabel): model.LabelValue(config.vdc),
model.LabelName(orgLabel): model.LabelValue(config.Organization),
model.LabelName(vdcLabel): model.LabelValue(config.Datacenter),
model.LabelName(nameLabel): model.LabelValue(vm.VM.Name),
model.LabelName(statusLabel): model.LabelValue(strconv.Itoa(vm.VM.Status)),
},
Expand Down Expand Up @@ -234,6 +237,8 @@ func (d *Discoverer) getTargets(ctx context.Context) ([]*targetgroup.Group, erro
targets = append(targets, target)
}
}

config.Disconnect()
}

for k := range d.lasts {
Expand Down
27 changes: 6 additions & 21 deletions pkg/action/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import (
"github.com/oklog/run"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/promhippie/prometheus-vcd-sd/pkg/adapter"
"github.com/promhippie/prometheus-vcd-sd/pkg/client"
"github.com/promhippie/prometheus-vcd-sd/pkg/config"
"github.com/promhippie/prometheus-vcd-sd/pkg/middleware"
"github.com/promhippie/prometheus-vcd-sd/pkg/version"
"github.com/vmware/go-vcloud-director/v2/govcd"
)

// Server handles the server sub-command.
Expand All @@ -35,7 +35,7 @@ func Server(cfg *config.Config, logger log.Logger) error {

{
ctx := context.Background()
configs := make(map[string]*Config, len(cfg.Target.Credentials))
configs := make(map[string]*client.Client, len(cfg.Target.Credentials))

for _, credential := range cfg.Target.Credentials {
parsed, err := url.ParseRequestURI(credential.URL)
Expand All @@ -49,29 +49,14 @@ func Server(cfg *config.Config, logger log.Logger) error {
return ErrClientEndpoint
}

client := govcd.NewVCDClient(
*parsed,
configs[credential.Project] = client.New(
parsed,
credential.Insecure,
)

if err := client.Authenticate(
credential.Username,
credential.Password,
credential.Org,
); err != nil {
level.Error(logger).Log(
"msg", ErrClientAuth,
"project", credential.Project,
)

return ErrClientAuth
}

configs[credential.Project] = &Config{
client: client,
org: credential.Org,
vdc: credential.Vdc,
}
credential.Vdc,
)
}

disc := Discoverer{
Expand Down
Loading

0 comments on commit 82f96af

Please sign in to comment.