Skip to content

Commit

Permalink
[JENKINS-50331] Ensure client connections are released
Browse files Browse the repository at this point in the history
  • Loading branch information
Dohbedoh committed Feb 18, 2020
1 parent f1387fc commit 302ac3c
Show file tree
Hide file tree
Showing 14 changed files with 295 additions and 267 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,9 @@ private JenkinsEventNotifier() { }
public static void sendJobCompletionEvent(final JSONObject payload) {
final List<TeamCollectionConfiguration> connectedCollections = TeamCollectionConfiguration.getConnectedCollections();
for (final TeamCollectionConfiguration c : connectedCollections) {
try {
// Check to see if there are any collections "connected" to this Jenkins server
final ConnectionParameters connectionParameters = c.getConnectionParameters();
final TeamRestClient client = new TeamRestClient(URI.create(c.getCollectionUrl()));
// Check to see if there are any collections "connected" to this Jenkins server
final ConnectionParameters connectionParameters = c.getConnectionParameters();
try (final TeamRestClient client = new TeamRestClient(URI.create(c.getCollectionUrl()))) {
payload.put("server", connectionParameters.getConnectionKey());
final String jsonPayload = payload.toString();
final JobCompletionEventArgs args = new JobCompletionEventArgs(
Expand Down
12 changes: 5 additions & 7 deletions tfs/src/main/java/hudson/plugins/tfs/TFSLabeler.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,12 @@ public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListen

final Launcher localLauncher = launcher != null ? launcher : new Launcher.LocalLauncher(listener);
Server server = tfsScm.createServer(localLauncher, listener, build.getRootBuild());

Computer computer = Computer.currentComputer();
String normalizedLabelName = computeDynamicValue(build, getLabelName());
String tfsWorkspace = tfsScm.getWorkspaceName(build.getRootBuild(), computer);
String tfsProjectPath = computeDynamicValue(build, tfsScm.getProjectPath());

try {
Computer computer = Computer.currentComputer();
String normalizedLabelName = computeDynamicValue(build, getLabelName());
String tfsWorkspace = tfsScm.getWorkspaceName(build.getRootBuild(), computer);
String tfsProjectPath = computeDynamicValue(build, tfsScm.getProjectPath());

logger.info(String.format("Create label '%s' on workspace '%s' with project path '%s' ", normalizedLabelName, tfsWorkspace, tfsProjectPath));
LabelCommand labelCommand = new LabelCommand(server, normalizedLabelName, tfsWorkspace, tfsProjectPath);
server.execute(labelCommand.getCallable());
Expand All @@ -89,7 +88,6 @@ public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListen
TelemetryHelper.sendEvent("team-label", new TelemetryHelper.PropertyMapBuilder()
.serverContext(server.getUrl(), server.getUrl())
.build());

} finally {
server.close();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,13 @@ static FormValidation testConnection(final String collectionUri, final StandardU
catch (final TFSUnauthorizedException e) {
// performing TFVC requires All Scopes and someone might be setting up for Git only; ignore
}
final TeamRestClient client = new TeamRestClient(collectionUri, credentials);

try {
try (final TeamRestClient client = new TeamRestClient(collectionUri, credentials)) {
final ListOfGitRepositories repositories = client.getRepositories();
if (repositories.count < 1) {
return FormValidation.warning("There does not seem to be any Git repositories");
}
return FormValidation.ok("Success via REST API.");
}
catch (final IOException e) {
} catch (final IOException e) {
return FormValidation.error("Error: " + e.getMessage());
}
}
Expand Down
72 changes: 35 additions & 37 deletions tfs/src/main/java/hudson/plugins/tfs/TeamFoundationServerScm.java
Original file line number Diff line number Diff line change
Expand Up @@ -699,52 +699,50 @@ public PollingResult compareRemoteRevisionWith(
Run<?, ?> build = project.getLastBuild();
final Server server = createServer(localLauncher, listener, build);

if (!(baseline instanceof TFSRevisionState)) {
// This plugin was just upgraded, we don't yet have a new-style baseline,
// so we perform an old-school poll
if (project instanceof AbstractProject) {
boolean shouldBuild = pollChanges((AbstractProject) project, localLauncher, workspace, listener);
return shouldBuild ? PollingResult.BUILD_NOW : PollingResult.NO_CHANGES;
} else {
// On the pipeline case, we can't call pollChanges. Query the TFS Server directly instead
if (build == null) {
return PollingResult.BUILD_NOW;
try {
if (!(baseline instanceof TFSRevisionState)) {
// This plugin was just upgraded, we don't yet have a new-style baseline,
// so we perform an old-school poll
if (project instanceof AbstractProject) {
boolean shouldBuild = pollChanges((AbstractProject) project, localLauncher, workspace, listener);
return shouldBuild ? PollingResult.BUILD_NOW : PollingResult.NO_CHANGES;
} else {
try {
// On the pipeline case, we can't call pollChanges. Query the TFS Server directly instead
if (build == null) {
return PollingResult.BUILD_NOW;
} else {
return (server.getProject(getProjectPath(build)).getDetailedHistoryWithoutCloakedPaths(
build.getTimestamp(),
Calendar.getInstance(),
getCloakedPaths(build)
).size() > 0) ? PollingResult.BUILD_NOW : PollingResult.NO_CHANGES;
} finally {
server.close();
}
}
}
}
final TFSRevisionState tfsBaseline = (TFSRevisionState) baseline;
if (!projectPath.equalsIgnoreCase(tfsBaseline.projectPath)) {
// There's no PollingResult.INCOMPARABLE, so we use the next closest thing
return PollingResult.BUILD_NOW;
}
final Project tfsProject = server.getProject(projectPath);
try {
final ChangeSet latest = tfsProject.getLatestUncloakedChangeset(tfsBaseline.changesetVersion, cloakedPaths);
final TFSRevisionState tfsRemote =
(latest != null)
? new TFSRevisionState(latest.getVersion(), projectPath)
: tfsBaseline;

// TODO: we could return INSIGNIFICANT if all the changesets
// contain the string "***NO_CI***" at the end of their comment
final Change change =
tfsBaseline.changesetVersion == tfsRemote.changesetVersion
? Change.NONE
: Change.SIGNIFICANT;
return new PollingResult(tfsBaseline, tfsRemote, change);
} catch (final Exception e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return PollingResult.NO_CHANGES;
final TFSRevisionState tfsBaseline = (TFSRevisionState) baseline;
if (!projectPath.equalsIgnoreCase(tfsBaseline.projectPath)) {
// There's no PollingResult.INCOMPARABLE, so we use the next closest thing
return PollingResult.BUILD_NOW;
}
final Project tfsProject = server.getProject(projectPath);
try {
final ChangeSet latest = tfsProject.getLatestUncloakedChangeset(tfsBaseline.changesetVersion, cloakedPaths);
final TFSRevisionState tfsRemote =
(latest != null)
? new TFSRevisionState(latest.getVersion(), projectPath)
: tfsBaseline;

// TODO: we could return INSIGNIFICANT if all the changesets
// contain the string "***NO_CI***" at the end of their comment
final Change change =
tfsBaseline.changesetVersion == tfsRemote.changesetVersion
? Change.NONE
: Change.SIGNIFICANT;
return new PollingResult(tfsBaseline, tfsRemote, change);
} catch (final Exception e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return PollingResult.NO_CHANGES;
}
} finally {
server.close();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,18 @@ public void perform(
final ArrayList<ResourceRef> workItems = new ArrayList<ResourceRef>();
final URI collectionUri = TeamPullRequestMergedDetailsAction.addWorkItemsForRun(run, workItems);
if (collectionUri != null) {
final TeamRestClient client = new TeamRestClient(collectionUri);
for (final ResourceRef workItem : workItems) {
final String workItemIdString = workItem.getId();
final Integer workItemId = Integer.valueOf(workItemIdString, 10);
client.addHyperlinkToWorkItem(workItemId, absoluteUrl);
}
try (final TeamRestClient client = new TeamRestClient(collectionUri)) {
for (final ResourceRef workItem : workItems) {
final String workItemIdString = workItem.getId();
final Integer workItemId = Integer.valueOf(workItemIdString, 10);
client.addHyperlinkToWorkItem(workItemId, absoluteUrl);
}

// Send telemetry
TelemetryHelper.sendEvent("team-workitem-update", new TelemetryHelper.PropertyMapBuilder()
.serverContext(collectionUri.toString(), collectionUri.toString())
.build());
// Send telemetry
TelemetryHelper.sendEvent("team-workitem-update", new TelemetryHelper.PropertyMapBuilder()
.serverContext(collectionUri.toString(), collectionUri.toString())
.build());
}
}
} catch (final IllegalArgumentException e) {
listener.error(e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,38 +41,42 @@ public Callable<Void, IOException> getCallable() {

public Void call() throws IOException {
final Server server = createServer();
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TaskListener listener = server.getListener();
final PrintStream logger = listener.getLogger();
try {
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TaskListener listener = server.getListener();
final PrintStream logger = listener.getLogger();

final String computerName = (DeleteWorkspaceCommand.this.computerName == null)
? LocalHost.getShortName()
: DeleteWorkspaceCommand.this.computerName;
final String deletingMessage = String.format(DeletingTemplate, workspaceName, computerName);
logger.println(deletingMessage);
final String computerName = (DeleteWorkspaceCommand.this.computerName == null)
? LocalHost.getShortName()
: DeleteWorkspaceCommand.this.computerName;
final String deletingMessage = String.format(DeletingTemplate, workspaceName, computerName);
logger.println(deletingMessage);

final WorkspacePermissions filter = WorkspacePermissions.NONE_OR_NOT_SUPPORTED;
final Workspace[] workspaces = vcc.queryWorkspaces(workspaceName, null, computerName, filter);
int numDeletions = 0;
for (final Workspace innerWorkspace : workspaces) {
vcc.deleteWorkspace(innerWorkspace);
final WorkspacePermissions filter = WorkspacePermissions.NONE_OR_NOT_SUPPORTED;
final Workspace[] workspaces = vcc.queryWorkspaces(workspaceName, null, computerName, filter);
int numDeletions = 0;
for (final Workspace innerWorkspace : workspaces) {
vcc.deleteWorkspace(innerWorkspace);

// work around a defect in the TFS SDK for Java
// TODO: check if this workaround is still necessary after upgrading
final WorkspaceInfo workspaceInfo = vcc.removeCachedWorkspace(workspaceName, VersionControlConstants.AUTHENTICATED_USER);
if (workspaceInfo != null) {
final TFSTeamProjectCollection tpc = vcc.getConnection();
final PersistenceStoreProvider provider = tpc.getPersistenceStoreProvider();
final Workstation currentWorkstation = Workstation.getCurrent(provider);
currentWorkstation.saveConfigIfDirty();
// work around a defect in the TFS SDK for Java
// TODO: check if this workaround is still necessary after upgrading
final WorkspaceInfo workspaceInfo = vcc.removeCachedWorkspace(workspaceName, VersionControlConstants.AUTHENTICATED_USER);
if (workspaceInfo != null) {
final TFSTeamProjectCollection tpc = vcc.getConnection();
final PersistenceStoreProvider provider = tpc.getPersistenceStoreProvider();
final Workstation currentWorkstation = Workstation.getCurrent(provider);
currentWorkstation.saveConfigIfDirty();
}

numDeletions++;
}

numDeletions++;
final String deletedMessage = String.format(DeletedTemplate, numDeletions, workspaceName);
logger.println(deletedMessage);
} finally {
server.close();
}

final String deletedMessage = String.format(DeletedTemplate, numDeletions, workspaceName);
logger.println(deletedMessage);

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,28 +52,32 @@ void setLogger(final PrintStream logger) {

public Void call() throws Exception {
final Server server = createServer();
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TaskListener listener = server.getListener();
logger = listener.getLogger();

final VersionSpec getVersionSpec;
if (versionSpec != null) {
getVersionSpec = VersionSpec.parseSingleVersionFromSpec(versionSpec, null);
} else {
getVersionSpec = LatestVersionSpec.INSTANCE;
try {
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TaskListener listener = server.getListener();
logger = listener.getLogger();

final VersionSpec getVersionSpec;
if (versionSpec != null) {
getVersionSpec = VersionSpec.parseSingleVersionFromSpec(versionSpec, null);
} else {
getVersionSpec = LatestVersionSpec.INSTANCE;
}
final String versionSpecString = RemoteChangesetVersionCommand.toString(getVersionSpec);
final String gettingMessage = String.format(GettingTemplate, versionSpecString, workFolder);
logger.println(gettingMessage);

final Workspace workspace = vcc.getWorkspace(workFolder);
final VersionControlEventEngine eventEngine = vcc.getEventEngine();
eventEngine.addGetListener(this);
workspace.get(getVersionSpec, useOverwrite ? GetOptions.OVERWRITE : GetOptions.NONE);
eventEngine.removeGetListener(this);

final String gotMessage = String.format(GotTemplate, versionSpecString, getCount);
logger.println(gotMessage);
} finally {
server.close();
}
final String versionSpecString = RemoteChangesetVersionCommand.toString(getVersionSpec);
final String gettingMessage = String.format(GettingTemplate, versionSpecString, workFolder);
logger.println(gettingMessage);

final Workspace workspace = vcc.getWorkspace(workFolder);
final VersionControlEventEngine eventEngine = vcc.getEventEngine();
eventEngine.addGetListener(this);
workspace.get(getVersionSpec, useOverwrite ? GetOptions.OVERWRITE : GetOptions.NONE);
eventEngine.removeGetListener(this);

final String gotMessage = String.format(GotTemplate, versionSpecString, getCount);
logger.println(gotMessage);

return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,27 @@ public Callable<String, Exception> getCallable() {
@Override
public String call() throws Exception {
final Server server = createServer();
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TFSTeamProjectCollection connection = vcc.getConnection();
updateCache(connection);
final TaskListener listener = server.getListener();
final PrintStream logger = listener.getLogger();

final String checkingMessage = String.format(CheckingMappingTemplate, localPath);
logger.print(checkingMessage);

final Workspace workspace = vcc.tryGetWorkspace(localPath);
final boolean existsMapping = workspace != null;
final String result = existsMapping ? workspace.getName() : null;

final String resultMessage = existsMapping ? String.format(FoundResultTemplate, result) : "no.";
logger.println(resultMessage);

return result;
try {
final MockableVersionControlClient vcc = server.getVersionControlClient();
final TFSTeamProjectCollection connection = vcc.getConnection();
updateCache(connection);
final TaskListener listener = server.getListener();
final PrintStream logger = listener.getLogger();

final String checkingMessage = String.format(CheckingMappingTemplate, localPath);
logger.print(checkingMessage);

final Workspace workspace = vcc.tryGetWorkspace(localPath);
final boolean existsMapping = workspace != null;
final String result = existsMapping ? workspace.getName() : null;

final String resultMessage = existsMapping ? String.format(FoundResultTemplate, result) : "no.";
logger.println(resultMessage);

return result;
} finally {
server.close();
}
}

}
Loading

0 comments on commit 302ac3c

Please sign in to comment.