Skip to content

Commit

Permalink
Refactor Datadog clients (#408)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikita-tkachenko-datadog authored Sep 11, 2024
1 parent 0ea6b40 commit 0bac4ae
Show file tree
Hide file tree
Showing 31 changed files with 562 additions and 805 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ of this software and associated documentation files (the "Software"), to deal
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import hudson.Extension;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.security.ACL;
Expand All @@ -45,20 +47,20 @@ of this software and associated documentation files (the "Software"), to deal
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.management.InvalidAttributeValueException;
import javax.servlet.ServletException;
import jenkins.model.GlobalConfiguration;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.datadog.jenkins.plugins.datadog.clients.ClientFactory;
import org.datadog.jenkins.plugins.datadog.clients.ClientHolder;
import org.datadog.jenkins.plugins.datadog.clients.DatadogAgentClient;
import org.datadog.jenkins.plugins.datadog.clients.DatadogApiClient;
import org.datadog.jenkins.plugins.datadog.clients.HttpClient;
import org.datadog.jenkins.plugins.datadog.traces.write.TraceWriterFactory;
import org.datadog.jenkins.plugins.datadog.util.SuppressFBWarnings;
import org.datadog.jenkins.plugins.datadog.util.config.DatadogAgentConfiguration;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
Expand Down Expand Up @@ -183,6 +185,15 @@ public DatadogGlobalConfiguration() {
loadEnvVariables(); // Load environment variables after as they should take precedence.
}

@Initializer(after = InitMilestone.PLUGINS_STARTED)
public void onStartup() {
try {
ClientHolder.setClient(createClient());
} catch (Exception e) {
DatadogUtilities.logException(logger, Level.INFO, "Could not init Datadog client", e);
}
}

public void loadEnvVariables() {
String reportWithEnvVar = System.getenv(REPORT_WITH_PROPERTY);
if(StringUtils.isNotBlank(reportWithEnvVar) &&
Expand Down Expand Up @@ -442,7 +453,7 @@ public FormValidation doTestConnection(
throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
final Secret secret = findSecret(targetApiKey, targetCredentialsApiKey);
if (DatadogApiClient.validateDefaultIntakeConnection(new HttpClient(60_000), targetApiURL, secret)) {
if (DatadogApiClient.validateDefaultIntakeConnection(targetApiURL, secret)) {
return FormValidation.ok("Great! Your API key is valid.");
} else {
return FormValidation.error("Hmmm, your API key seems to be invalid.");
Expand All @@ -461,7 +472,7 @@ public ListBoxModel doFillTargetCredentialsApiKeyItems(
@QueryParameter("targetCredentialsApiKey") String targetCredentialsApiKey
) {
StandardListBoxModel result = new StandardListBoxModel();
// If the users does not have permissions to list credentials, only list the current value
// If the user does not have permissions to list credentials, only list the current value
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(targetCredentialsApiKey);
Expand Down Expand Up @@ -504,7 +515,7 @@ public FormValidation doTestFilteringConfig(


/**
* Tests the targetCredentialsApiKey field from the configuration screen, to check its' validity.
* Tests the targetCredentialsApiKey field from the configuration screen, to check its validity.
*
* @param item - The context within which to list available credentials.
* @param targetCredentialsApiKey - A String containing the API key as a credential
Expand Down Expand Up @@ -720,7 +731,6 @@ public String getDisplayName() {
@SuppressFBWarnings("REC_CATCH_EXCEPTION")
public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException {
try {

if(!super.configure(req, formData)){
return false;
}
Expand Down Expand Up @@ -828,16 +838,8 @@ public boolean configure(final StaplerRequest req, final JSONObject formData) th
final Secret apiKeySecret = findSecret(formData.getString("targetApiKey"), formData.getString("targetCredentialsApiKey"));
this.setUsedApiKey(apiKeySecret);

//When form is saved....
DatadogClient client = ClientFactory.getClient(DatadogClient.ClientType.valueOf(this.getReportWith()), this.getTargetApiURL(),
this.getTargetLogIntakeURL(), this.getTargetWebhookIntakeURL(), this.getUsedApiKey(), this.getTargetHost(),
this.getTargetPort(), this.getTargetLogCollectionPort(), this.getTargetTraceCollectionPort(), this.getCiInstanceName());
// ...reinitialize the DatadogClient
if(client == null) {
return false;
}

TraceWriterFactory.onDatadogClientUpdate(client);
DatadogClient client = createClient();
ClientHolder.setClient(client);

// Persist global configuration information
save();
Expand All @@ -851,12 +853,26 @@ public boolean configure(final StaplerRequest req, final JSONObject formData) th
DatadogUtilities.severe(logger, e, "Failed to save configuration");
return false;
}

}
public boolean reportWithEquals(String value){
return this.reportWith.equals(value);

@Nullable
public DatadogClient createClient() {
if (StringUtils.isBlank(reportWith)) {
return null;
}

DatadogClient.ClientType type = DatadogClient.ClientType.valueOf(reportWith);
switch(type){
case HTTP:
return new DatadogApiClient(targetApiURL, targetLogIntakeURL, targetWebhookIntakeURL, usedApiKey);
case DSD:
return new DatadogAgentClient(targetHost, targetPort, targetLogCollectionPort, targetTraceCollectionPort);
default:
throw new IllegalArgumentException("Unsupported client type: " + type);
}
}


/**
* Getter function for the reportWith global configuration.
*
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
The MIT License
Copyright (c) 2015-Present Datadog, Inc <[email protected]>
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package org.datadog.jenkins.plugins.datadog.clients;

import java.util.Objects;
import javax.annotation.Nullable;
import org.datadog.jenkins.plugins.datadog.DatadogClient;
import org.datadog.jenkins.plugins.datadog.DatadogGlobalConfiguration;
import org.datadog.jenkins.plugins.datadog.DatadogUtilities;
import org.datadog.jenkins.plugins.datadog.traces.write.TraceWriterFactory;

public class ClientHolder {
private static volatile DatadogClient CLIENT;

public static synchronized void setClient(DatadogClient client) {
if (!Objects.equals(CLIENT, client)) {
CLIENT = client;
TraceWriterFactory.onDatadogClientUpdate(client);
}
}

@Nullable
public static DatadogClient getClient() {
return CLIENT;
}
}
Loading

0 comments on commit 0bac4ae

Please sign in to comment.