Skip to content

Commit

Permalink
Address sonarcloud issues
Browse files Browse the repository at this point in the history
  • Loading branch information
mackdk committed Jun 21, 2023
1 parent 44eae92 commit 290e6d7
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public static Optional<PaygSshData> lookupById(Integer id) {
* @return list of payg ssh daa objects
*/
public static List<PaygSshData> lookupPaygSshData() {
return getSession().createQuery("FROM PaygSshData").list();
return getSession().createQuery("FROM PaygSshData", PaygSshData.class).list();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ private void refreshRepositoriesAuthentication(String mirrorUrl) throws ContentS
}
catch (SCCClientException e) {
// test for OES credentials
if (!accessibleUrl(OES_URL, c.getUsername(), c.getPassword())) {
if (c == null || !accessibleUrl(OES_URL, c.getUsername(), c.getPassword())) {
LOG.info("Credential is not an OES credentials");
throw new ContentSyncException(e);
}
Expand Down Expand Up @@ -678,10 +678,10 @@ public void linkAndRefreshContentSource(String mirrorUrl) {
orphanChannels.forEach(c -> Opt.consume(ChannelFactory.findVendorRepositoryByChannel(c),
() -> LOG.error("No repository found for channel: '{}'", c.getLabel()),
repo -> {
LOG.debug("configure orphan repo {}", repo.toString());
LOG.debug("configure orphan repo {}", repo);
repo.getBestAuth().ifPresentOrElse(
a -> createOrUpdateContentSource(a, c, mirrorUrl),
() -> LOG.info("No Auth available for {}", repo.toString())
() -> LOG.info("No Auth available for {}", repo)
);
}
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ public class PaygAuthDataExtractor {
private PaygInstanceInfo processOutput(int exitStatus, String error, String output) {
if (exitStatus != 0 || error.length() > 0) {
LOG.error("Exit status: {}", exitStatus);
LOG.error("stderr:\n{}", error.toString());
throw new PaygDataExtractException(error.toString());
LOG.error("stderr:\n{}", error);
throw new PaygDataExtractException(error);
}
if (output.length() == 0) {
LOG.error("Exit status was success but no data retrieved");
throw new PaygDataExtractException("No data retrieved from the instance.");
}
return GSON.fromJson(output.toString(), PaygInstanceInfo.class);
return GSON.fromJson(output, PaygInstanceInfo.class);
}


Expand All @@ -88,16 +88,14 @@ private PaygInstanceInfo extractAuthDataSSH(PaygSshData instance) throws Excepti
try {
JSch.setConfig("StrictHostKeyChecking", "no");
JSch sshTarget = new JSch();
//sshTarget.setKnownHosts(KNOWN_HOSTS);
if (!StringUtils.isEmpty(instance.getKey())) {
String authKeypassIn = instance.getKeyPassword() != null ? instance.getKeyPassword() : "";
sshTarget.addIdentity("targetkey", instance.getKey().getBytes(), null, authKeypassIn.getBytes());
}
Integer sshPortIn = instance.getPort() != null ? instance.getPort() : 22;
int sshPortIn = instance.getPort() != null ? instance.getPort() : 22;

if (!StringUtils.isEmpty(instance.getBastionHost())) {
JSch sshBastion = new JSch();
//sshBastion.setKnownHosts(KNOWN_HOSTS);
if (!StringUtils.isEmpty(instance.getBastionKey())) {
String bastionAuthKeyPassIn = instance.getBastionKeyPassword() != null ?
instance.getBastionKeyPassword() : "";
Expand Down Expand Up @@ -133,7 +131,6 @@ private PaygInstanceInfo extractAuthDataSSH(PaygSshData instance) throws Excepti
channel.setInputStream(PaygAuthDataExtractor.class
.getResourceAsStream("script/payg_extract_repo_data.py"));

//channel.setInputStream(null);
InputStream stdout = channel.getInputStream();
InputStream stderr = channel.getErrStream();
channel.connect();
Expand Down Expand Up @@ -211,7 +208,11 @@ protected PaygInstanceInfo extractAuthDataLocal() {
//TODO: add additional product information
return processOutput(exitStatus, error, output);
}
catch (IOException | InterruptedException e) {
catch (IOException e) {
LOG.error(e);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error(e);
}
return null;
Expand Down Expand Up @@ -269,6 +270,7 @@ private void waitForChannelClosed(ChannelExec channel) {
Thread.sleep(RESPONSE_TIMEOUT / 10);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Should not happen
LOG.error("error when waiting for channel to be closed", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,8 @@
import com.suse.cloud.CloudPaygManager;
import com.suse.manager.admin.PaygAdminManager;


import com.jcraft.jsch.JSchException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobExecutionContext;

import java.util.Collections;
Expand All @@ -48,8 +45,6 @@ public class PaygUpdateAuthTask extends RhnJavaJob {

private CloudPaygManager cloudPaygManager = GlobalInstanceHolder.PAYG_MANAGER;

private static final Logger LOG = LogManager.getLogger(PaygUpdateAuthTask.class);

private static final String KEY_ID = "sshData_id";

@Override
Expand All @@ -59,16 +54,15 @@ public String getConfigNamespace() {

private void manageLocalHostPayg() {
if (cloudPaygManager.isPaygInstance()) {
PaygSshDataFactory.lookupByHostname("localhost").orElseGet(() -> {
if (PaygSshDataFactory.lookupByHostname("localhost").isEmpty()) {
PaygSshData paygSshData = PaygSshDataFactory.createPaygSshData();
paygSshData.setHost("localhost");
paygSshData.setDescription("SUSE Manager Pay-as-you-go");
paygSshData.setUsername("root");
PaygSshDataFactory.savePaygSshData(paygSshData);
HibernateFactory.getSession().flush();
HibernateFactory.commitTransaction();
return paygSshData;
});
}
}
else {
try {
Expand Down Expand Up @@ -124,12 +118,12 @@ private void updateInstanceData(PaygSshData instance) {

}
catch (PaygDataExtractException | JSchException e) {
LOG.error("error getting instance data ", e);
log.error("error getting instance data ", e);
saveError(instance, e.getMessage());

}
catch (Exception e) {
LOG.error("error processing instance data", e);
log.error("error processing instance data", e);
// Error message will be empty because we don't want to show this error on UI
saveError(instance, "");
}
Expand Down
8 changes: 2 additions & 6 deletions java/code/src/com/suse/cloud/CloudPaygManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,18 @@
*/
package com.suse.cloud;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.file.Files;
import java.nio.file.Path;

/**
* Public Cloud Pay-as-you-go management class
*/
public class CloudPaygManager {
private final Logger LOG = LogManager.getLogger(CloudPaygManager.class);

private boolean isPaygInstance = false;
private CloudProvider cloudProvider;
public enum CloudProvider {
None,
NONE,
AWS,
AZURE,
GCE
Expand All @@ -38,7 +34,7 @@ public enum CloudProvider {
* Constructor
*/
public CloudPaygManager() {
cloudProvider = CloudProvider.None;
cloudProvider = CloudProvider.NONE;
if (isFileExecutable("/usr/bin/ec2metadata")) {
cloudProvider = CloudProvider.AWS;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class CloudPaygManagerTest extends BaseTestCaseWithUser {
public void testCloudProvider() {
CloudPaygManager cpm = new CloudPaygManager();
CloudPaygManager.CloudProvider prv = cpm.getCloudProvider();
assertEquals(CloudPaygManager.CloudProvider.None, prv);
assertEquals(CloudPaygManager.CloudProvider.NONE, prv);

CloudPaygManager cpmAWS = new CloudPaygManager() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ public class RegistrationUtils {
private static final String OS_ARCH = "osarch";

private static final Logger LOG = LogManager.getLogger(RegistrationUtils.class);
public static final String OS_MAJOR_RELEASE = "osmajorrelease";
public static final String OS_RELEASE = "osrelease";

private static SystemEntitlementManager systemEntitlementManager = GlobalInstanceHolder.SYSTEM_ENTITLEMENT_MANAGER;

Expand Down Expand Up @@ -366,7 +368,7 @@ public static boolean isAllowedOnPayg(SystemQuery systemQuery, String minionId,
if (isPaygClient) {
return true;
}
return identifyProduct(systemQuery, minionId, grains.getValueAsString("osarch"), channels, grains)
return identifyProduct(systemQuery, minionId, grains.getValueAsString(OS_ARCH), channels, grains)
.stream()
.allMatch(p -> {
if (p.getFree()) {
Expand All @@ -386,10 +388,12 @@ private static Set<SUSEProduct> identifyProduct(SystemQuery systemQuery, MinionS
}
private static Set<SUSEProduct> identifyProduct(SystemQuery systemQuery, String minionId, String arch,
Set<Channel> channels, ValueMap grains) {
if ("suse".equalsIgnoreCase(grains.getValueAsString(OS))) {
String osGrain = grains.getValueAsString(OS);
String osArchGrain = grains.getValueAsString(OS_ARCH);
if ("suse".equalsIgnoreCase(osGrain)) {
Optional<List<Zypper.ProductInfo>> productList =
systemQuery.getProducts(minionId);
return Opt.stream(productList).flatMap(pl -> pl.stream()
return productList.stream().flatMap(pl -> pl.stream()
.flatMap(pi -> {
String osName = pi.getName().toLowerCase();
String osVersion = pi.getVersion();
Expand All @@ -398,14 +402,14 @@ private static Set<SUSEProduct> identifyProduct(SystemQuery systemQuery, String
Optional<SUSEProduct> suseProduct =
ofNullable(SUSEProductFactory.findSUSEProduct(osName,
osVersion, osRelease, osArch, true));
if (!suseProduct.isPresent()) {
if (suseProduct.isEmpty()) {
LOG.warn("No product match found for: {} {} {} {}", osName, osVersion, osRelease, osArch);
}
return Opt.stream(suseProduct);
return suseProduct.stream();
})).collect(toSet());
}
else if (Set.of("redhat", "centos", "oel", "alibaba cloud (aliyun)", "almalinux", "amazon", "rocky")
.contains(grains.getValueAsString(OS).toLowerCase())) {
.contains(osGrain.toLowerCase())) {

Optional<RedhatProductInfo> redhatProductInfo = systemQuery.redhatProductInfo(minionId);

Expand All @@ -424,22 +428,21 @@ else if (Set.of("redhat", "centos", "oel", "alibaba cloud (aliyun)", "almalinux"
return rhel.getAllSuseProducts().stream();
}).collect(toSet());
}
else if ("ubuntu".equalsIgnoreCase(grains.getValueAsString(OS))) {
else if ("ubuntu".equalsIgnoreCase(osGrain)) {
SUSEProduct product = SUSEProductFactory.findSUSEProduct("ubuntu-client",
grains.getValueAsString("osrelease"), null, grains.getValueAsString(OS_ARCH) + "-deb", false);
grains.getValueAsString(OS_RELEASE), null, osArchGrain + "-deb", false);
if (product != null) {
return Collections.singleton(product);
}
}
else if ("debian".equalsIgnoreCase(grains.getValueAsString(OS))) {
else if ("debian".equalsIgnoreCase(osGrain)) {
SUSEProduct product = SUSEProductFactory.findSUSEProduct("debian-client",
grains.getValueAsString("osmajorrelease"), null, grains.getValueAsString(OS_ARCH) + "-deb", false);
grains.getValueAsString(OS_MAJOR_RELEASE), null, osArchGrain + "-deb", false);
if (product != null) {
return Collections.singleton(product);
}
}
LOG.warn("No product match found. OS grain is {}, arch is {}", grains.getValueAsString(OS),
grains.getValueAsString(OS_ARCH));
LOG.warn("No product match found. OS grain is {}, arch is {}", osGrain, osArchGrain);
return emptySet();
}

Expand Down

0 comments on commit 290e6d7

Please sign in to comment.