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

chore(build): Refactor BuildService and separate Maven/Docker specific parts. #1116

Open
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

rhuss
Copy link
Collaborator

@rhuss rhuss commented Oct 18, 2018

No description provided.

} catch (IOException e) {
throw new MojoExecutionException("Cannot create archive " + archive, e);
throw new IOException("Cannot create archive " + archive, e);
} catch (RuntimeException e) {
e.printStackTrace();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Use a logger to log this exception. rule

@codecov
Copy link

codecov bot commented Oct 18, 2018

Codecov Report

Merging #1116 into master will increase coverage by 0.16%.
The diff coverage is 55.75%.

@@             Coverage Diff              @@
##             master    #1116      +/-   ##
============================================
+ Coverage     52.31%   52.48%   +0.16%     
+ Complexity     1473     1469       -4     
============================================
  Files           150      161      +11     
  Lines          7854     7934      +80     
  Branches       1168     1150      -18     
============================================
+ Hits           4109     4164      +55     
- Misses         3343     3348       +5     
- Partials        402      422      +20
Impacted Files Coverage Δ Complexity Δ
.../main/java/io/fabric8/maven/docker/RemoveMojo.java 0% <ø> (ø) 0 <0> (ø) ⬇️
.../fabric8/maven/docker/util/ImageNameFormatter.java 94.11% <ø> (ø) 11 <0> (ø) ⬇️
...r/build/maven/assembly/AllFilesExecCustomizer.java 0% <ø> (ø) 0 <0> (?)
.../docker/config/handler/property/ValueProvider.java 86.73% <ø> (ø) 11 <0> (ø) ⬇️
...fabric8/maven/docker/config/run/RestartPolicy.java 100% <ø> (ø) 4 <0> (?)
...java/io/fabric8/maven/docker/VolumeRemoveMojo.java 30% <ø> (ø) 2 <0> (ø) ⬇️
...abric8/maven/docker/config/build/AssemblyMode.java 0% <ø> (ø) 0 <0> (?)
...o/fabric8/maven/docker/util/VolumeBindingUtil.java 80.39% <ø> (ø) 22 <0> (ø) ⬇️
...ava/io/fabric8/maven/docker/access/UrlBuilder.java 66.38% <ø> (ø) 21 <0> (ø) ⬇️
...ic8/maven/docker/config/run/WaitConfiguration.java 72.52% <ø> (ø) 10 <0> (?)
... and 109 more

@rhuss rhuss force-pushed the pr/1115/refactor-build-service branch from 42077e8 to c7c06c6 Compare October 18, 2018 06:32
@@ -54,8 +58,8 @@ public WatchService(ArchiveService archiveService, BuildService buildService, Do
this.log = log;
}

public synchronized void watch(WatchContext context, BuildService.BuildContext buildContext, List<ImageConfiguration> images) throws DockerAccessException,
MojoExecutionException {
public synchronized void watch(WatchContext watchContext, MavenBuildContext buildContext, List<ImageConfiguration> images) throws
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed. rule

private String name;

@Parameter
private int retry;

public RestartPolicy() {};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. rule
MINOR Remove this empty statement. rule

return soft;
}

Pattern ULIMIT_PATTERN = Pattern.compile("^(?<name>[^=]+)=(?<hard>[^:]*):?(?<soft>[^:]*)$");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Rename this field "ULIMIT_PATTERN" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. rule

return new BZip2CompressorOutputStream(out);
}
};
none("tar"),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule

}
};
none("tar"),
gzip("tar.gz"),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule

};
none("tar"),
gzip("tar.gz"),
bzip2("tar.bz");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule

private File dockerFileFile, dockerArchiveFile;

public BuildImageConfiguration() {}
public BuildConfiguration() {}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. rule

return config;
}
}

public String initAndValidate(Logger log) throws IllegalArgumentException {
public String validate() throws IllegalArgumentException {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception. rule

return build;
}

public static class Builder extends ImageConfiguration.Builder {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this class. rule

return nocache.length() == 0 || Boolean.valueOf(nocache);
} else {
BuildConfiguration buildConfig = imageConfig.getBuildConfiguration();
return buildConfig.getNoCache() != null ? buildConfig.getNoCache() : false;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Remove the literal "false" boolean value. rule

public Object handleResponse(HttpResponse response) throws IOException {
try (InputStream stream = response.getEntity().getContent();
OutputStream out = compression.wrapOutputStream(new FileOutputStream(filename))) {
private ResponseHandler<Object> getImageResponseHandler(final String filename) throws FileNotFoundException {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Remove the declaration of thrown exception 'java.io.FileNotFoundException', as it cannot be thrown from method's body. rule

return inline;
}

public static class Builder extends AssemblyConfiguration.Builder {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this class. rule

return assembly;
}

public static class Builder extends BuildConfiguration.Builder {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Rename this class. rule

AssemblyConfiguration config = new AssemblyConfiguration.Builder().ignorePermissions(false).permissions("ignore").build();
assertTrue(config.isIgnorePermissions());;
AssemblyConfiguration config = new AssemblyConfiguration.Builder().permissions("ignore").build();
assertSame(config.getPermissions(), AssemblyConfiguration.PermissionMode.ignore);;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Swap these 2 arguments so they are in the correct order: expected value, actual value. rule

@@ -237,6 +244,13 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}
}

private List<ImageConfiguration> convertToPlainImageConfigurations(List<MavenImageConfiguration> images) {
if (images == null) {
return null;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Return an empty collection instead of null. rule

.user(valueProvider.getString(USER, config == null ? null : config.getUser()))
.healthCheck(extractHealthCheck(config == null ? null : config.getHealthCheck(), valueProvider))
.build();
}

private RunImageConfiguration extractRunConfiguration(ImageConfiguration fromConfig, ValueProvider valueProvider) {
RunImageConfiguration config = fromConfig.getRunConfiguration();
private RunConfiguration extractRunConfiguration(ImageConfiguration fromConfig, ValueProvider valueProvider) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Refactor this method to reduce its Cognitive Complexity from 39 to the 15 allowed. rule

.exportBasedir(valueProvider.getBoolean(ASSEMBLY_EXPORT_BASEDIR, config == null ? null : config.getExportTargetDir()))
.ignorePermissions(valueProvider.getBoolean(ASSEMBLY_IGNORE_PERMISSIONS, config == null ? null : config.getIgnorePermissions()))
.permissions(valueProvider.getString(ASSEMBLY_PERMISSIONS, config == null ? null : config.getPermissionsRaw()))
.permissions(valueProvider.getString(ASSEMBLY_PERMISSIONS, config == null ? null : config.getPermissions() != null ? config.getPermissions().name() : null))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Extract this nested ternary operation into an independent statement. rule

.user(valueProvider.getString(ASSEMBLY_USER, config == null ? null : config.getUser()))
.mode(valueProvider.getString(ASSEMBLY_MODE, config == null ? null : config.getModeRaw()))
.mode(valueProvider.getString(ASSEMBLY_MODE, config == null ? null : config.getMode() != null ? config.getMode().name() : null))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Extract this nested ternary operation into an independent statement. rule

Logger log) {
// Init and validate configs. After this step, getResolvedImages() contains the valid configuration.
for (ImageConfiguration imageConfiguration : images) {
apiVersion = EnvUtil.extractLargerVersion(apiVersion, imageConfiguration.initAndValidate(nameFormatter, log));
for (String version : imageConfiguration.validate(nameFormatter))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Use curly braces or indentation to denote the code conditionally executed by this "for". rule

@@ -118,11 +122,12 @@ public static String getExternalConfigActivationProperty(MavenProject project) {
* @param log a logger for printing out diagnostic messages
* @return the minimal API Docker API required to be used for the given configuration.
*/
public static String initAndValidate(List<ImageConfiguration> images, String apiVersion, NameFormatter nameFormatter,
public static String initAndValidate(List<ImageConfiguration> images, String apiVersion, ImageConfiguration.NameFormatter nameFormatter,
Logger log) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Remove this unused method parameter "log". rule

* @param finalCustomizer finalCustomizer to be applied to the tar archive
* @return file holding the path to the created assembly tar file
* @throws MojoExecutionException
*/
public File createDockerTarArchive(String imageName, final MojoParameters params, final BuildImageConfiguration buildConfig, Logger log, ArchiverCustomizer finalCustomizer)
throws MojoExecutionException {
public File createDockerTarArchive(String imageName, final MavenBuildContext context, final BuildConfiguration buildConfig, ArchiverCustomizer finalCustomizer, Logger log)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. rule

@@ -202,7 +183,7 @@ private void interpolateDockerfile(File dockerFile, BuildDirs params, FixedStrin
}

// visible for testing
void verifyGivenDockerfile(File dockerFile, BuildImageConfiguration buildConfig, FixedStringSearchInterpolator interpolator, Logger log) throws IOException {
void verifyGivenDockerfile(File dockerFile, BuildConfiguration buildConfig, Function<String, String> interpolator, Logger log) throws IOException {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. rule

@@ -65,13 +63,13 @@
private BuildImageSelectMode sourceMode = BuildImageSelectMode.first;

@Override
protected void executeInternal(ServiceHub hub) throws DockerAccessException, MojoExecutionException {
MojoParameters params = createMojoParameters();
protected void executeInternal(ServiceHub hub) throws IOException {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed. rule

private String postExec;

public WatchImageConfiguration() {};
public WatchConfiguration() {};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. rule
MINOR Remove this empty statement. rule

private Integer time;

/**
* @deprecated Use &lt;http&gt;&lturl&gt;&lt;/url&gt;&lt;/http&gt; instead
*/
@Parameter
private String url;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Add the missing @deprecated annotation. rule
INFO Do not forget to remove this deprecated code someday. rule

package io.fabric8.maven.docker.config.build;

/*
*
* Copyright 2014 Roland Huss
*
* Licensed under the Apache License, Version 2.0 (the "License");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR This block of commented-out lines of code should be removed. rule

@@ -327,25 +329,33 @@ private void startImage(final ImageConfiguration imageConfig,
return ret;
}


// Prepare start like creating custom networks, auto pull images, map aliases and return the list of images
// to start in the correct order
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Remove this unused method parameter "queryService". rule

if (!runConfig.getNetworkingConfig().isCustomNetwork() && runConfig.getLinks() != null) {
runConfig.getLinks()
.stream()
.map(s -> !s.contains(":") ? s : s.substring(0, s.lastIndexOf(":")))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Put single-quotes around ':' to use the faster "lastIndexOf(char)" method. rule

@Test
public void testEmpty() throws Exception {
setupDefaultAuthConfigFactory();
executeWithTempHomeDir(homeDir -> assertEquals(factory.createAuthConfig(kind, null, "blubberbla:1611"), RegistryAuth.EMPTY_REGISTRY_AUTH));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Swap these 2 arguments so they are in the correct order: expected value, actual value. rule


executeWithTempHomeDir(homeDir -> {
setupServers();
assertEquals(factory.createAuthConfig(kind, "roland", "another.repo.org"), RegistryAuth.EMPTY_REGISTRY_AUTH);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Swap these 2 arguments so they are in the correct order: expected value, actual value. rule

@@ -0,0 +1,95 @@
package io.fabric8.maven.docker.build.maven;

import java.util.Optional;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Remove this unused import 'java.util.Optional'. rule

public class RegistryAuthConfig {

private Map<String, Map<String, String>> handlerConfig = new HashMap<>();
private Map<Kind, Map<String, String>> kindConfig = new HashMap<>();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Convert this Map to an EnumMap. rule

try {
JsonObject creds = new GetCommand().getCredentialNode(registryToLookup);
if (creds == null) {
creds = new GetCommand().getCredentialNode(EnvUtil.ensureRegistryHttpUrl(registryToLookup));
}
return toAuthConfig(creds);
} catch (IOException e) {
throw new MojoExecutionException("Error getting the credentials for " + registryToLookup + " from the configured credential helper",e);
throw new RuntimeException("Error getting the credentials for " + registryToLookup + " from the configured credential helper",e);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Define and throw a dedicated exception instead of using a generic one. rule

try {
return new VersionCommand().getVersion();
} catch (IOException e) {
throw new MojoExecutionException("Error getting the version of the configured credential helper",e);
throw new RuntimeException("Error getting the version of the configured credential helper",e);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Define and throw a dedicated exception instead of using a generic one. rule

String useOpenAuthMode = registryAuthConfig.extractFromProperties(props, kind, AUTH_USE_OPENSHIFT_AUTH);
// Check for system property
if (useOpenAuthMode != null) {
boolean useOpenShift = Boolean.valueOf(useOpenAuthMode);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Use "Boolean.parseBoolean" for this string-to-boolean conversion. rule


import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Remove this unused import 'java.util.TreeMap'. rule

*/
public class RegistryAuth {

public final static RegistryAuth EMPTY_REGISTRY_AUTH =
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Reorder the modifiers to comply with the Java Language Specification. rule

new RegistryAuth.Builder().username("").password("").email("").auth("").build();

public static final String USERNAME = "username";
public static final String PASSWORD = "password";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BLOCKER 'PASSWORD' detected in this expression, review this potentially hard-coded credential. rule

public static final String EMAIL = "email";
public static final String AUTH = "authToken";

private String username, password, email, auth, authEncoded;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BLOCKER Rename field "username" to prevent any misunderstanding/clash with field "USERNAME" defined on line 22. rule
BLOCKER Rename field "password" to prevent any misunderstanding/clash with field "PASSWORD" defined on line 23. rule
BLOCKER Rename field "email" to prevent any misunderstanding/clash with field "EMAIL" defined on line 24. rule
BLOCKER Rename field "auth" to prevent any misunderstanding/clash with field "AUTH" defined on line 25. rule
MINOR Declare "password" on a separate line. rule
MINOR Declare "email" on a separate line. rule
MINOR Declare "auth" on a separate line. rule
MINOR Declare "authEncoded" on a separate line. rule


// ======================================================================================================

private String createAuthEncoded() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR Move this method into "Builder". rule

private RegistryAuth extractAuthConfigFromDocker(JsonObject dockerConfig, String registry) {
String registryToLookup = registry != null ? registry : DOCKER_LOGIN_DEFAULT_REGISTRY;

if (dockerConfig.has("credHelpers") || dockerConfig.has("credsStore")) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL Define a constant instead of duplicating this literal "credsStore" 3 times. rule
CRITICAL Define a constant instead of duplicating this literal "credHelpers" 3 times. rule

@ghost
Copy link

ghost commented Oct 22, 2018

SonarQube analysis reported 153 issues

  • BLOCKER 7 blocker
  • CRITICAL 49 critical
  • MAJOR 32 major
  • MINOR 59 minor
  • INFO 6 info

Watch the comments in this conversation to review them.

Top 10 extra issues

Note: The following issues were found on lines that were not modified in the pull request. Because these issues can't be reported as line comments, they are summarized here:

  1. BLOCKER DockerFileBuilder.java#L259: End this switch case with an unconditional break, return or throw statement. rule
  2. BLOCKER DockerFileBuilder.java#L262: End this switch case with an unconditional break, return or throw statement. rule
  3. CRITICAL ExternalCommand.java#L101: Make sure that executing this OS command is safe here. rule
  4. CRITICAL DockerFileBuilder.java#L341: Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. rule
  5. CRITICAL MappingTrackArchiver.java#L127: Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed. rule
  6. CRITICAL AssemblyConfiguration.java#L151: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule
  7. CRITICAL AssemblyConfiguration.java#L156: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule
  8. CRITICAL AssemblyConfiguration.java#L161: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule
  9. CRITICAL AssemblyConfiguration.java#L166: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule
  10. CRITICAL AssemblyMode.java#L31: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'. rule

@rhuss rhuss force-pushed the pr/1115/refactor-build-service branch from 1898156 to 9969472 Compare December 12, 2018 09:45
@rhuss rhuss force-pushed the pr/1115/refactor-build-service branch from 9969472 to 90e9dbd Compare December 13, 2018 14:00
@rhuss rhuss added WIP Work in Progress size/XXL labels Apr 6, 2019
@rhuss rhuss self-assigned this Apr 6, 2019
@rhuss rhuss mentioned this pull request Jun 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/XXL WIP Work in Progress
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant