datadog-agent icon indicating copy to clipboard operation
datadog-agent copied to clipboard

Update the APIKey in the Forwarder using config.OnUpdate

Open dustmop opened this issue 1 year ago • 3 comments

What does this PR do?

When the API Key is refreshed using the secret Component, respond to the config.OnUpdate event by updating the API Key in the forwarder and update its health state.

Motivation

Part of the api key refresh initiative.

Additional Notes

Possible Drawbacks / Trade-offs

Describe how to test/QA your changes

Setup

Create two Datadog API Keys, assign them to the environment variables:

export DD_API_KEY0=[first api key...]
export DD_API_KEY1=[second api key...]

Create the following script named secret-script.py in the working directory:

#!/usr/bin/env python
import datetime
import json
import os
import sys

def main():
  content = sys.stdin.read()
  obj = json.loads(content)
  handles = obj['secrets']
  result = {}
  for h in handles:
    if h == 'my_api_key':
      if not os.path.isfile('alt.cfg'):
        result[h] = {'value': os.environ.get('DD_API_KEY0')}
      else:
        result[h] = {'value': os.environ.get('DD_API_KEY1')}
      continue
    result[h] = {
      'value': 'decoded_%s' % h,
    }
  print(json.dumps(result))

  dt = datetime.datetime.now()
  fout = open('secret-script.log', 'a')
  fout.write('[%s] %s\n' % (dt, result))
  fout.close()

if __name__ == '__main__':
  main()

Set its permissions properly:

chmod 500 secret-script.py

Configure the secrets backend in your datadog.yml file, as well as the api_key:

api_key: ENC[my_api_key]
secret_backend_command: script-script.py 

Tail the log file to see that the secret decoder is invoked every 4 seconds:

tail -f secret-script.log

Run the agent and check status

  1. Run your agent: agent run

  2. In another terminal, get the status to verify that your first api key is seen by the forwarder: agent status

check both the "Endpoints" and "API Keys status" sections

=========
Endpoints
=========

  https://app.datadoghq.com - API Key ending with:
      - abcde

...

  API Keys status
  ===============
    API key ending with abcde: API Key valid

Refresh the key

  1. Activate the switch to change to the second api key touch alt.cfg (in the same working directory)

  2. Refresh the api key: agent secrets refresh

  3. Get the status again, the api key should display the second api key: agent status

dustmop avatar Feb 29 '24 23:02 dustmop

Bloop Bleep... Dogbot Here

Regression Detector Results

Run ID: 163aa721-36db-497f-a357-af9f14b0dc1f Baseline: d2baec44ac3d78b115c52cafb8ad1e87e80d3475 Comparison: 74221ed45d19c26f39e5e31c89a261b25562dcb7

Performance changes are noted in the perf column of each table:

  • ✅ = significantly better comparison variant performance
  • ❌ = significantly worse comparison variant performance
  • ➖ = no significant change in performance

Experiments with missing or malformed data

  • basic_py_check

Usually, this warning means that there is no usable optimization goal data for that experiment, which could be a result of misconfiguration.

No significant changes in experiment optimization goals

Confidence level: 90.00% Effect size tolerance: |Δ mean %| ≥ 5.00%

There were no significant changes in experiment optimization goals at this confidence level and effect size tolerance.

Experiments ignored for regressions

Regressions in experiments with settings containing erratic: true are ignored.

perf experiment goal Δ mean % Δ mean % CI
file_to_blackhole % cpu utilization -0.55 [-7.05, +5.95]

Fine details of change detection per experiment

perf experiment goal Δ mean % Δ mean % CI
idle memory utilization +1.82 [+1.78, +1.85]
otel_to_otel_logs ingress throughput +1.19 [+0.53, +1.85]
process_agent_standard_check memory utilization +1.13 [+1.10, +1.17]
process_agent_real_time_mode memory utilization +1.02 [+0.99, +1.06]
process_agent_standard_check_with_stats memory utilization +1.02 [+0.98, +1.05]
tcp_syslog_to_blackhole ingress throughput +0.47 [+0.42, +0.53]
trace_agent_msgpack ingress throughput +0.01 [-0.00, +0.02]
tcp_dd_logs_filter_exclude ingress throughput +0.00 [-0.00, +0.00]
uds_dogstatsd_to_api ingress throughput -0.00 [-0.00, +0.00]
trace_agent_json ingress throughput -0.00 [-0.03, +0.02]
file_to_blackhole % cpu utilization -0.55 [-7.05, +5.95]
file_tree memory utilization -0.61 [-0.70, -0.52]
uds_dogstatsd_to_api_cpu % cpu utilization -1.36 [-2.80, +0.08]

Explanation

A regression test is an A/B test of target performance in a repeatable rig, where "performance" is measured as "comparison variant minus baseline variant" for an optimization goal (e.g., ingress throughput). Due to intrinsic variability in measuring that goal, we can only estimate its mean value for each experiment; we report uncertainty in that value as a 90.00% confidence interval denoted "Δ mean % CI".

For each experiment, we decide whether a change in performance is a "regression" -- a change worth investigating further -- if all of the following criteria are true:

  1. Its estimated |Δ mean %| ≥ 5.00%, indicating the change is big enough to merit a closer look.

  2. Its 90.00% confidence interval "Δ mean % CI" does not contain zero, indicating that if our statistical model is accurate, there is at least a 90.00% chance there is a difference in performance between baseline and comparison variants.

  3. Its configuration does not mark it "erratic".

pr-commenter[bot] avatar Mar 01 '24 00:03 pr-commenter[bot]

❓ In the validateAPIKey function we create an http client for every request we made to the backend:

func (fh *forwarderHealth) validateAPIKey(apiKey, domain string) (bool, error) {
	if apiKey == fakeAPIKey {
		fh.setAPIKeyStatus(apiKey, domain, &apiKeyFake)
		return true, nil
	}

	url := fmt.Sprintf("%s%s?api_key=%s", domain, endpoints.V1ValidateEndpoint, apiKey)

	transport := httputils.CreateHTTPTransport(fh.config)

	client := &http.Client{
		Transport: transport,
		Timeout:   fh.timeout,
	}
.
.
.

Would we benefit from reusing the client rather than creating a new client per request? Since we call validateAPIKey in the healthCheckLoop we might get better performance

GustavoCaso avatar Mar 13 '24 11:03 GustavoCaso

Would we benefit from reusing the client rather than creating a new client per request? Since we call validateAPIKey in the healthCheckLoop we might get better performance

The healthCheckLoop only runs once every hour, so performance isn't a concern there. It's true that checkValidAPIKey can potentially call validateAPIKey multiple times, but that's only the case if the agent is using additional endpoints. In nearly all cases, there will only be 1 call to validateAPIKey. I'd rather keep the code simple and handle all http request construction in a single place.

dustmop avatar Mar 13 '24 19:03 dustmop

/merge

dustmop avatar Mar 15 '24 17:03 dustmop

:steam_locomotive: MergeQueue

This merge request is not mergeable yet, because of pending checks/missing approvals. It will be added to the queue as soon as checks pass and/or get approvals. Note: if you pushed new commits since the last approval, you may need additional approval. You can remove it from the waiting list with /remove command.

Use /merge -c to cancel this operation!

dd-devflow[bot] avatar Mar 15 '24 17:03 dd-devflow[bot]

/merge -c

dustmop avatar Mar 15 '24 18:03 dustmop

:warning: MergeQueue

This merge request was unqueued

If you need support, contact us on Slack #ci-interfaces!

dd-devflow[bot] avatar Mar 15 '24 18:03 dd-devflow[bot]

/merge

dustmop avatar Mar 15 '24 19:03 dustmop

:steam_locomotive: MergeQueue

This merge request is not mergeable yet, because of pending checks/missing approvals. It will be added to the queue as soon as checks pass and/or get approvals. Note: if you pushed new commits since the last approval, you may need additional approval. You can remove it from the waiting list with /remove command.

Use /merge -c to cancel this operation!

dd-devflow[bot] avatar Mar 15 '24 19:03 dd-devflow[bot]

Test changes on VM

Use this command from test-infra-definitions to manually test this PR changes on a VM:

inv create-vm --pipeline-id=30221655 --os-family=ubuntu

pr-commenter[bot] avatar Mar 15 '24 19:03 pr-commenter[bot]

:steam_locomotive: MergeQueue

Added to the queue.

This build is next! (estimated merge in less than 27m)

Use /merge -c to cancel this operation!

dd-devflow[bot] avatar Mar 15 '24 20:03 dd-devflow[bot]

Regression Detector

Regression Detector Results

Run ID: af80942e-2bab-44de-907c-9effba3af917 Baseline: e28da0ffc545969927a951d25dc48caaab383679 Comparison: 3d70f32504e57488d5382649aaaa65a55300340d

Performance changes are noted in the perf column of each table:

  • ✅ = significantly better comparison variant performance
  • ❌ = significantly worse comparison variant performance
  • ➖ = no significant change in performance

No significant changes in experiment optimization goals

Confidence level: 90.00% Effect size tolerance: |Δ mean %| ≥ 5.00%

There were no significant changes in experiment optimization goals at this confidence level and effect size tolerance.

Experiments ignored for regressions

Regressions in experiments with settings containing erratic: true are ignored.

perf experiment goal Δ mean % Δ mean % CI
file_to_blackhole % cpu utilization +1.85 [-4.52, +8.22]

Fine details of change detection per experiment

perf experiment goal Δ mean % Δ mean % CI
file_to_blackhole % cpu utilization +1.85 [-4.52, +8.22]
otel_to_otel_logs ingress throughput +0.14 [-0.28, +0.56]
tcp_dd_logs_filter_exclude ingress throughput +0.03 [+0.01, +0.05]
trace_agent_msgpack ingress throughput +0.02 [+0.01, +0.03]
trace_agent_json ingress throughput -0.00 [-0.02, +0.02]
process_agent_standard_check_with_stats memory utilization -0.03 [-0.07, +0.02]
uds_dogstatsd_to_api ingress throughput -0.05 [-0.25, +0.16]
file_tree memory utilization -0.05 [-0.15, +0.05]
basic_py_check % cpu utilization -0.09 [-2.52, +2.33]
idle memory utilization -0.10 [-0.14, -0.06]
tcp_syslog_to_blackhole ingress throughput -0.22 [-0.32, -0.13]
process_agent_standard_check memory utilization -0.59 [-0.64, -0.55]
uds_dogstatsd_to_api_cpu % cpu utilization -0.81 [-3.53, +1.92]
process_agent_real_time_mode memory utilization -1.15 [-1.20, -1.11]
pycheck_1000_100byte_tags % cpu utilization -1.64 [-6.44, +3.16]

Explanation

A regression test is an A/B test of target performance in a repeatable rig, where "performance" is measured as "comparison variant minus baseline variant" for an optimization goal (e.g., ingress throughput). Due to intrinsic variability in measuring that goal, we can only estimate its mean value for each experiment; we report uncertainty in that value as a 90.00% confidence interval denoted "Δ mean % CI".

For each experiment, we decide whether a change in performance is a "regression" -- a change worth investigating further -- if all of the following criteria are true:

  1. Its estimated |Δ mean %| ≥ 5.00%, indicating the change is big enough to merit a closer look.

  2. Its 90.00% confidence interval "Δ mean % CI" does not contain zero, indicating that if our statistical model is accurate, there is at least a 90.00% chance there is a difference in performance between baseline and comparison variants.

  3. Its configuration does not mark it "erratic".

pr-commenter[bot] avatar Mar 15 '24 20:03 pr-commenter[bot]