[router] make a distinction between fatal errors, warnings and unknown as healthcheck result (#10710)

* [routers] distiction between fatal failure and warning or unknown on healthchecks

* UI status for router health checks

* status from scripts varied

* automation signalled errors

* revert removal of update sql

* upgradeversion

* move config item and further cleanup

* handling services better

* backwards compatible response

---------

Co-authored-by: Daan Hoogland <dahn@apache.org>
This commit is contained in:
dahn 2025-09-22 08:09:05 +02:00 committed by GitHub
parent 3ef2556900
commit aca8732102
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 543 additions and 715 deletions

View File

@ -108,36 +108,22 @@ public interface ConfigurationService {
/**
* Updates a service offering
*
* @param serviceOfferingId
* @param userId
* @param name
* @param displayText
* @param offerHA
* @param useVirtualNetwork
* @param tags
* @return updated service offering
*/
ServiceOffering updateServiceOffering(UpdateServiceOfferingCmd cmd);
/**
* Deletes a service offering
*
* @param userId
* @param serviceOfferingId
*/
boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd);
/**
* Retrieve ID of domains for a service offering
*
* @param serviceOfferingId
*/
List<Long> getServiceOfferingDomains(Long serviceOfferingId);
/**
* Retrieve ID of domains for a service offering
*
* @param serviceOfferingId
*/
List<Long> getServiceOfferingZones(Long serviceOfferingId);
@ -147,7 +133,6 @@ public interface ConfigurationService {
* @param cmd
* - the command specifying diskOfferingId, name, description, tags
* @return updated disk offering
* @throws
*/
DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd);
@ -157,34 +142,22 @@ public interface ConfigurationService {
* @param cmd
* - the command specifying disk offering id
* @return true or false
* @throws
*/
boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd);
/**
* Creates a new disk offering
*
* @param domainId
* @param name
* @param description
* @param numGibibytes
* @param mirrored
* @param size
* @return ID
*/
DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd);
/**
* Retrieve ID of domains for a disk offering
*
* @param diskOfferingId
*/
List<Long> getDiskOfferingDomains(Long diskOfferingId);
/**
* Retrieve ID of domains for a disk offering
*
* @param diskOfferingId
*/
List<Long> getDiskOfferingZones(Long diskOfferingId);
@ -207,8 +180,6 @@ public interface ConfigurationService {
* TODO
* @param storageAccessGroups
* @return the new pod if successful, null otherwise
* @throws
* @throws
*/
Pod createPod(long zoneId, String name, String startIp, String endIp, String gateway, String netmask, String allocationState, List<String> storageAccessGroups);
@ -228,8 +199,7 @@ public interface ConfigurationService {
/**
* Updates a mutually exclusive IP range in the pod.
* @param cmd - The command specifying pod ID, current Start IP, current End IP, new Start IP, new End IP.
* @throws com.cloud.exception.ConcurrentOperationException
* @return Success
* @throws com.cloud.exception.ConcurrentOperationException when this pod is already being accessed
*/
void updatePodIpRange(UpdatePodManagementNetworkIpRangeCmd cmd) throws ConcurrentOperationException;
@ -250,9 +220,6 @@ public interface ConfigurationService {
/**
* Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system.
*
* @param UpdatePodCmd
* api command
*/
Pod editPod(UpdatePodCmd cmd);
@ -262,17 +229,12 @@ public interface ConfigurationService {
* @param cmd
* - the command containing podId
* @return true or false
* @throws ,
*/
boolean deletePod(DeletePodCmd cmd);
/**
* Creates a new zone
*
* @param cmd
* @return the zone if successful, null otherwise
* @throws
* @throws
*/
DataCenter createZone(CreateZoneCmd cmd);
@ -295,22 +257,7 @@ public interface ConfigurationService {
* Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on
* the
* virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs
*
* @param userId
* @param vlanType
* - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be
* directly
* attached to UserVMs)
* @param zoneId
* @param accountId
* @param podId
* @param add
* @param vlanId
* @param gateway
* @param startIP
* @param endIP
* @throws ResourceAllocationException TODO
* @throws
* @return The new Vlan object
*/
Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException,
@ -325,9 +272,6 @@ public interface ConfigurationService {
/**
* Marks the account with the default zone-id.
*
* @param accountName
* @param domainId
* @param defaultZoneId
* @return The new account object
*/
Account markDefaultZone(String accountName, long domainId, long defaultZoneId);
@ -349,14 +293,12 @@ public interface ConfigurationService {
/**
* Retrieve ID of domains for a network offering
*
* @param networkOfferingId
*/
List<Long> getNetworkOfferingDomains(Long networkOfferingId);
/**
* Retrieve ID of domains for a network offering
*
* @param networkOfferingId
*/
List<Long> getNetworkOfferingZones(Long networkOfferingId);

View File

@ -26,7 +26,7 @@ public interface RouterHealthCheckResult {
String getCheckType();
boolean getCheckResult();
VirtualNetworkApplianceService.RouterHealthStatus getCheckResult();
Date getLastUpdateTime();

View File

@ -87,4 +87,8 @@ public interface VirtualNetworkApplianceService {
Pair<Boolean, String> performRouterHealthChecks(long routerId);
<T extends VirtualRouter> void collectNetworkStatistics(T router, Nic nic);
enum RouterHealthStatus{
SUCCESS, FAILED, WARNING, UNKNOWN;
}
}

View File

@ -41,13 +41,23 @@ import com.cloud.utils.net.Ip;
public interface LoadBalancingRulesService {
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param xId an existing UUID for this rule (for instance a device generated one)
* @param name
* @param description
* @param srcPortStart
* @param srcPortEnd
* @param defPortStart
* @param defPortEnd
* @param ipAddrId
* @param protocol
* @param algorithm
* @param networkId
* @param lbOwnerId
* @param openFirewall
* TODO
* @param forDisplay TODO
* @param cmd
* the command specifying the ip address, public port, protocol, private port, and algorithm
*
* @param lbProtocol
* @param forDisplay
* @return the newly created LoadBalancerVO if successful, null otherwise
* @throws NetworkRuleConflictException
* @throws InsufficientAddressCapacityException
*/
LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd,

View File

@ -19,6 +19,7 @@ package org.apache.cloudstack.api.response;
import java.util.Date;
import com.cloud.network.VirtualNetworkApplianceService.RouterHealthStatus;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
@ -35,9 +36,13 @@ public class RouterHealthCheckResultResponse extends BaseResponse {
private String checkType;
@SerializedName(ApiConstants.SUCCESS)
@Param(description = "result of the health check")
@Param(description = "result of the health check if available")
private boolean result;
@SerializedName(ApiConstants.STATUS)
@Param(description = "the result of the health check in enum form: {SUCCESS, FAILURE, WARNING, UNKNOWN}")
private RouterHealthStatus state;
@SerializedName(ApiConstants.LAST_UPDATED)
@Param(description = "the date this VPC was created")
private Date lastUpdated;
@ -54,10 +59,14 @@ public class RouterHealthCheckResultResponse extends BaseResponse {
return checkType;
}
public boolean getResult() {
public Boolean getResult() {
return result;
}
public RouterHealthStatus getState() {
return state;
}
public Date getLastUpdated() {
return lastUpdated;
}
@ -74,10 +83,14 @@ public class RouterHealthCheckResultResponse extends BaseResponse {
this.checkType = checkType;
}
public void setResult(boolean result) {
public void setResult(Boolean result) {
this.result = result;
}
public void setState(RouterHealthStatus state) {
this.state = state;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}

View File

@ -76,44 +76,52 @@ public interface NetworkOrchestrationService {
*/
Long RVRHandoverTime = 10000L;
ConfigKey<String> MinVRVersion = new ConfigKey<String>(String.class, MinVRVersionCK, "Advanced", "4.10.0",
ConfigKey<String> MinVRVersion = new ConfigKey<>(String.class, MinVRVersionCK, "Advanced", "4.10.0",
"What version should the Virtual Routers report", true, ConfigKey.Scope.Zone, null);
ConfigKey<Integer> NetworkLockTimeout = new ConfigKey<Integer>(Integer.class, NetworkLockTimeoutCK, "Network", "600",
"Lock wait timeout (seconds) while implementing network", true, Scope.Global, null);
ConfigKey<Integer> NetworkLockTimeout = new ConfigKey<>(Integer.class, NetworkLockTimeoutCK, "Network", "600",
"Lock wait timeout (seconds) while implementing network", true, Scope.Global, null);
ConfigKey<String> DeniedRoutes = new ConfigKey<String>(String.class, "denied.routes", "Network", "",
ConfigKey<String> DeniedRoutes = new ConfigKey<>(String.class, "denied.routes", "Network", "",
"Routes that are denied, can not be used for Static Routes creation for the VPC Private Gateway", true, ConfigKey.Scope.Zone, null);
ConfigKey<String> GuestDomainSuffix = new ConfigKey<String>(String.class, GuestDomainSuffixCK, "Network", "cloud.internal",
"Default domain name for vms inside virtualized networks fronted by router", true, ConfigKey.Scope.Zone, null);
ConfigKey<String> GuestDomainSuffix = new ConfigKey<>(String.class, GuestDomainSuffixCK, "Network", "cloud.internal",
"Default domain name for vms inside virtualized networks fronted by router", true, ConfigKey.Scope.Zone, null);
ConfigKey<Integer> NetworkThrottlingRate = new ConfigKey<Integer>("Network", Integer.class, NetworkThrottlingRateCK, "200",
"Default data transfer rate in megabits per second allowed in network.", true, ConfigKey.Scope.Zone);
ConfigKey<Integer> NetworkThrottlingRate = new ConfigKey<>("Network", Integer.class, NetworkThrottlingRateCK, "200",
"Default data transfer rate in megabits per second allowed in network.", true, ConfigKey.Scope.Zone);
ConfigKey<Boolean> PromiscuousMode = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.promiscuous.mode", "false",
ConfigKey<Boolean> PromiscuousMode = new ConfigKey<>("Advanced", Boolean.class, "network.promiscuous.mode", "false",
"Whether to allow or deny promiscuous mode on nics for applicable network elements such as for vswitch/dvswitch portgroups.", true);
ConfigKey<Boolean> MacAddressChanges = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.mac.address.changes", "true",
ConfigKey<Boolean> MacAddressChanges = new ConfigKey<>("Advanced", Boolean.class, "network.mac.address.changes", "true",
"Whether to allow or deny mac address changes on nics for applicable network elements such as for vswitch/dvswitch porgroups.", true);
ConfigKey<Boolean> ForgedTransmits = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.forged.transmits", "true",
ConfigKey<Boolean> ForgedTransmits = new ConfigKey<>("Advanced", Boolean.class, "network.forged.transmits", "true",
"Whether to allow or deny forged transmits on nics for applicable network elements such as for vswitch/dvswitch portgroups.", true);
ConfigKey<Boolean> MacLearning = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.mac.learning", "false",
ConfigKey<Boolean> MacLearning = new ConfigKey<>("Advanced", Boolean.class, "network.mac.learning", "false",
"Whether to allow or deny MAC learning on nics for applicable network elements such as for dvswitch portgroups.", true);
ConfigKey<Boolean> RollingRestartEnabled = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.rolling.restart", "true",
ConfigKey<Boolean> RollingRestartEnabled = new ConfigKey<>("Advanced", Boolean.class, "network.rolling.restart", "true",
"Whether to allow or deny rolling restart of network routers.", true);
static final ConfigKey<Boolean> TUNGSTEN_ENABLED = new ConfigKey<>(Boolean.class, "tungsten.plugin.enable", "Advanced", "false",
ConfigKey<Boolean> TUNGSTEN_ENABLED = new ConfigKey<>(Boolean.class, "tungsten.plugin.enable", "Advanced", "false",
"Indicates whether to enable the Tungsten plugin", false, ConfigKey.Scope.Zone, null);
static final ConfigKey<Boolean> NSX_ENABLED = new ConfigKey<>(Boolean.class, "nsx.plugin.enable", "Advanced", "false",
ConfigKey<Boolean> NSX_ENABLED = new ConfigKey<>(Boolean.class, "nsx.plugin.enable", "Advanced", "false",
"Indicates whether to enable the NSX plugin", false, ConfigKey.Scope.Zone, null);
ConfigKey<Boolean> NETRIS_ENABLED = new ConfigKey<>(Boolean.class, "netris.plugin.enable", "Advanced", "false",
"Indicates whether to enable the Netris plugin", false, ConfigKey.Scope.Zone, null);
ConfigKey<Integer> NETWORK_LB_HAPROXY_MAX_CONN = new ConfigKey<>(
"Network",
Integer.class,
"network.loadbalancer.haproxy.max.conn",
"4096",
"Load Balancer(haproxy) maximum number of concurrent connections(global max)",
true,
Scope.Global);
List<? extends Network> setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, String displayText, boolean isDefault)
throws ConcurrentOperationException;
@ -129,7 +137,7 @@ public interface NetworkOrchestrationService {
* configures the provided dhcp options on the given nic.
* @param network of the nic
* @param nicId
* @param extraDhcpOptions
* @param extraDhcpOptions a map of rank:value pairs
*/
void configureExtraDhcpOptions(Network network, long nicId, Map<Integer, String> extraDhcpOptions);
@ -158,16 +166,15 @@ public interface NetworkOrchestrationService {
Pair<? extends NetworkGuru, ? extends Network> implementNetwork(long networkId, DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
Map<Integer, String> getExtraDhcpOptions(long nicId);
/**
* Returns all extra dhcp options which are set on the provided nic
* @param nicId
* @return map which maps the dhcp value on it's option code
*/
Map<Integer, String> getExtraDhcpOptions(long nicId);
/**
* prepares vm nic change for migration
*
* This method will be called in migration transaction before the vm migration.
* @param vm
* @param dest
@ -176,7 +183,6 @@ public interface NetworkOrchestrationService {
/**
* commit vm nic change for migration
*
* This method will be called in migration transaction after the successful
* vm migration.
* @param src
@ -186,7 +192,6 @@ public interface NetworkOrchestrationService {
/**
* rollback vm nic change for migration
*
* This method will be called in migaration transaction after vm migration
* failure.
* @param src
@ -266,7 +271,7 @@ public interface NetworkOrchestrationService {
void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException;
NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare)
throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException,
throws ConcurrentOperationException, InsufficientCapacityException,
ResourceUnavailableException;
NetworkProfile convertNetworkToNetworkProfile(long networkId);
@ -277,7 +282,7 @@ public interface NetworkOrchestrationService {
boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean b, Network network);
void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, Network network, NetworkOffering findById)
throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException;
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
Map<String, String> finalizeServicesAndProvidersForNetwork(NetworkOffering offering, Long physicalNetworkId);

View File

@ -56,10 +56,10 @@ import com.cloud.utils.net.NetUtils;
*/
public interface ConfigurationManager {
public static final String MESSAGE_CREATE_POD_IP_RANGE_EVENT = "Message.CreatePodIpRange.Event";
public static final String MESSAGE_DELETE_POD_IP_RANGE_EVENT = "Message.DeletePodIpRange.Event";
public static final String MESSAGE_CREATE_VLAN_IP_RANGE_EVENT = "Message.CreateVlanIpRange.Event";
public static final String MESSAGE_DELETE_VLAN_IP_RANGE_EVENT = "Message.DeleteVlanIpRange.Event";
String MESSAGE_CREATE_POD_IP_RANGE_EVENT = "Message.CreatePodIpRange.Event";
String MESSAGE_DELETE_POD_IP_RANGE_EVENT = "Message.DeletePodIpRange.Event";
String MESSAGE_CREATE_VLAN_IP_RANGE_EVENT = "Message.CreateVlanIpRange.Event";
String MESSAGE_DELETE_VLAN_IP_RANGE_EVENT = "Message.DeleteVlanIpRange.Event";
public static final ConfigKey<Boolean> AllowNonRFC1918CompliantIPs = new ConfigKey<>(Boolean.class,
"allow.non.rfc1918.compliant.ips", "Advanced", "false",
@ -72,8 +72,9 @@ public interface ConfigurationManager {
true, ConfigKey.Scope.Global);
/**
* @param offering
* @return
* Is this for a VPC
* @param offering the offering to check
* @return true or false
*/
boolean isOfferingForVpc(NetworkOffering offering);
@ -83,80 +84,12 @@ public interface ConfigurationManager {
/**
* Updates a configuration entry with a new value
* @param userId
* @param name
* @param category
* @param value
* @param scope
* @param id
*/
String updateConfiguration(long userId, String name, String category, String value, ConfigKey.Scope scope, Long id);
// /**
// * Creates a new service offering
// *
// * @param name
// * @param cpu
// * @param ramSize
// * @param speed
// * @param displayText
// * @param localStorageRequired
// * @param offerHA
// * @param domainId
// * @param volatileVm
// * @param hostTag
// * @param networkRate
// * @param id
// * @param useVirtualNetwork
// * @param deploymentPlanner
// * @param details
// * @param bytesReadRate
// * @param bytesWriteRate
// * @param iopsReadRate
// * @param iopsWriteRate
// * @return ID
// */
// ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_typeType, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired,
// boolean offerHA, boolean limitResourceUse, boolean volatileVm, String tags, Long domainId, String hostTag, Integer networkRate, String deploymentPlanner, Map<String, String> details,
// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);
// /**
// * Creates a new disk offering
// *
// * @param domainId
// * @param name
// * @param description
// * @param numGibibytes
// * @param tags
// * @param isCustomized
// * @param localStorageRequired
// * @param isDisplayOfferingEnabled
// * @param isCustomizedIops (is admin allowing users to set custom iops?)
// * @param minIops
// * @param maxIops
// * @param bytesReadRate
// * @param bytesWriteRate
// * @param iopsReadRate
// * @param iopsWriteRate
// * @return newly created disk offering
// */
// DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized,
// boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,
// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);
/**
* Creates a new pod
*
* @param userId
* @param podName
* @param zone
* @param gateway
* @param cidr
* @param startIp
* @param endIp
* @param allocationState
* @param skipGatewayOverlapCheck (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD)
* @param storageAccessGroups
* @return Pod
*/
HostPodVO createPod(long userId, String podName, DataCenter zone, String gateway, String cidr, String startIp, String endIp, String allocationState,
@ -164,7 +97,6 @@ public interface ConfigurationManager {
/**
* Creates a new zone
*
* @param userId
* @param zoneName
* @param dns1
@ -172,16 +104,18 @@ public interface ConfigurationManager {
* @param internalDns1
* @param internalDns2
* @param guestCidr
* @param domain
* @param domainId
* @param zoneType
* @param allocationState
* @param networkDomain
* @param isSecurityGroupEnabled
* @param isLocalStorageEnabled
* @param ip6Dns1
* @param ip6Dns2
* @param isEdge
* @param storageAccessGroups
* @return
* @throws
* @throws
*/
DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain,
Long domainId, NetworkType zoneType, String allocationState, String networkDomain, boolean isSecurityGroupEnabled, boolean isLocalStorageEnabled, String ip6Dns1,
@ -191,9 +125,7 @@ public interface ConfigurationManager {
* Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated
* IP addresses.
*
* @param userId
* @param vlanDbId
* @param caller
* @param caller TODO
* @return success/failure
*/
VlanVO deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller);
@ -204,31 +136,39 @@ public interface ConfigurationManager {
/**
* Creates a new network offering
*
* @param name
* @param displayText
* @param trafficType
* @param tags
* @param specifyVlan
* @param availability
* @param networkRate
* @param serviceProviderMap
* @param isDefault
* @param type
* @param systemOnly
* @param serviceOfferingId
* @param conserveMode ;
* @param conserveMode
* @param serviceCapabilityMap
* @param specifyIpRanges
* @param isPersistent ;
* @param isPersistent
* @param details
* @param egressDefaultPolicy
* @param maxconn
* @param enableKeepAlive
* @param forVpc
* @param forTungsten
* @param forNsx
* @param forNetris
* @param networkMode
* @param domainIds
* @param zoneIds
* @return network offering object
* @param enableOffering
* @param internetProtocol
* @param routingMode
* @param specifyAsNumber
* @return the network offering
*/
NetworkOfferingVO createNetworkOffering(String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability,
Integer networkRate, Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId,
boolean conserveMode, Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent,
@ -245,7 +185,6 @@ public interface ConfigurationManager {
/**
* Release dedicated virtual ip ranges of a domain.
*
* @param domainId
* @return success/failure
*/
boolean releaseDomainSpecificVirtualRanges(Domain domain);
@ -253,7 +192,6 @@ public interface ConfigurationManager {
/**
* Release dedicated virtual ip ranges of an account.
*
* @param accountId
* @return success/failure
*/
boolean releaseAccountSpecificVirtualRanges(Account account);
@ -261,16 +199,7 @@ public interface ConfigurationManager {
/**
* Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system.
*
* @param id
* @param name
* @param startIp
* @param endIp
* @param gateway
* @param netmask
* @param allocationState
* @return Pod
* @throws
* @throws
*/
Pod editPod(long id, String name, String startIp, String endIp, String gateway, String netmask, String allocationState);

View File

@ -454,7 +454,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
SearchBuilder<IPAddressVO> AssignIpAddressSearch;
SearchBuilder<IPAddressVO> AssignIpAddressFromPodVlanSearch;
HashMap<Long, Long> _lastNetworkIdsToFree = new HashMap<Long, Long>();
HashMap<Long, Long> _lastNetworkIdsToFree = new HashMap<>();
private void updateRouterDefaultDns(final VirtualMachineProfile vmProfile, final NicProfile nicProfile) {
if (!Type.DomainRouter.equals(vmProfile.getType()) || !nicProfile.isDefaultNic()) {
@ -492,8 +492,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
// populate providers
final Map<Network.Service, Set<Network.Provider>> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>();
final Map<Network.Service, Set<Network.Provider>> defaultSharedNetworkOfferingProviders = new HashMap<>();
final Set<Network.Provider> defaultProviders = new HashSet<>();
final Set<Network.Provider> tungstenProvider = new HashSet<>();
defaultProviders.add(Network.Provider.VirtualRouter);
@ -512,11 +512,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
defaultIsolatedNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders);
defaultIsolatedNetworkOfferingProviders.put(Service.Vpn, defaultProviders);
final Map<Network.Service, Set<Network.Provider>> defaultSharedSGEnabledNetworkOfferingProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Map<Network.Service, Set<Network.Provider>> defaultSharedSGEnabledNetworkOfferingProviders = new HashMap<>();
defaultSharedSGEnabledNetworkOfferingProviders.put(Service.Dhcp, defaultProviders);
defaultSharedSGEnabledNetworkOfferingProviders.put(Service.Dns, defaultProviders);
defaultSharedSGEnabledNetworkOfferingProviders.put(Service.UserData, defaultProviders);
final Set<Provider> sgProviders = new HashSet<Provider>();
final Set<Provider> sgProviders = new HashSet<>();
sgProviders.add(Provider.SecurityGroupProvider);
defaultSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders);
@ -529,7 +529,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
defaultTungstenSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, tungstenProvider);
final Map<Network.Service, Set<Network.Provider>> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Map<Network.Service, Set<Network.Provider>> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<>();
defaultProviders.clear();
defaultProviders.add(Network.Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, defaultProviders);
@ -543,7 +543,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders);
final Map<Network.Service, Set<Network.Provider>> defaultVPCOffProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Map<Network.Service, Set<Network.Provider>> defaultVPCOffProviders = new HashMap<>();
defaultProviders.clear();
defaultProviders.add(Network.Provider.VPCVirtualRouter);
defaultVPCOffProviders.put(Service.Dhcp, defaultProviders);
@ -560,11 +560,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
NetworkOfferingVO offering = null;
NetworkOfferingVO offering;
//#1 - quick cloud network offering
if (_networkOfferingDao.findByUniqueName(NetworkOffering.QuickCloudNoServices) == null) {
offering = _configMgr.createNetworkOffering(NetworkOffering.QuickCloudNoServices, "Offering for QuickCloud with no services", TrafficType.Guest, null, true,
Availability.Optional, null, new HashMap<Network.Service, Set<Network.Provider>>(), true, Network.GuestType.Shared, false, null, true, null, true,
Availability.Optional, null, new HashMap<>(), true, Network.GuestType.Shared, false, null, true, null, true,
false, null, false, null, true, false, false, false, false, null, null, null, true, null, null, false);
}
@ -622,11 +622,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
}
//#8 - network offering with internal lb service
final Map<Network.Service, Set<Network.Provider>> internalLbOffProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Set<Network.Provider> defaultVpcProvider = new HashSet<Network.Provider>();
final Map<Network.Service, Set<Network.Provider>> internalLbOffProviders = new HashMap<>();
final Set<Network.Provider> defaultVpcProvider = new HashSet<>();
defaultVpcProvider.add(Network.Provider.VPCVirtualRouter);
final Set<Network.Provider> defaultInternalLbProvider = new HashSet<Network.Provider>();
final Set<Network.Provider> defaultInternalLbProvider = new HashSet<>();
defaultInternalLbProvider.add(Network.Provider.InternalLbVm);
internalLbOffProviders.put(Service.Dhcp, defaultVpcProvider);
@ -646,12 +646,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
_networkOfferingDao.update(offering.getId(), offering);
}
final Map<Network.Service, Set<Network.Provider>> netscalerServiceProviders = new HashMap<Network.Service, Set<Network.Provider>>();
final Set<Network.Provider> vrProvider = new HashSet<Network.Provider>();
final Map<Network.Service, Set<Network.Provider>> netscalerServiceProviders = new HashMap<>();
final Set<Network.Provider> vrProvider = new HashSet<>();
vrProvider.add(Provider.VirtualRouter);
final Set<Network.Provider> sgProvider = new HashSet<Network.Provider>();
final Set<Network.Provider> sgProvider = new HashSet<>();
sgProvider.add(Provider.SecurityGroupProvider);
final Set<Network.Provider> nsProvider = new HashSet<Network.Provider>();
final Set<Network.Provider> nsProvider = new HashSet<>();
nsProvider.add(Provider.Netscaler);
netscalerServiceProviders.put(Service.Dhcp, vrProvider);
netscalerServiceProviders.put(Service.Dns, vrProvider);
@ -660,10 +660,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
netscalerServiceProviders.put(Service.StaticNat, nsProvider);
netscalerServiceProviders.put(Service.Lb, nsProvider);
final Map<Service, Map<Capability, String>> serviceCapabilityMap = new HashMap<Service, Map<Capability, String>>();
final Map<Capability, String> elb = new HashMap<Capability, String>();
final Map<Service, Map<Capability, String>> serviceCapabilityMap = new HashMap<>();
final Map<Capability, String> elb = new HashMap<>();
elb.put(Capability.ElasticLb, "true");
final Map<Capability, String> eip = new HashMap<Capability, String>();
final Map<Capability, String> eip = new HashMap<>();
eip.put(Capability.ElasticIp, "true");
serviceCapabilityMap.put(Service.Lb, elb);
serviceCapabilityMap.put(Service.StaticNat, eip);
@ -726,11 +726,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
return true;
}
@Override
public boolean stop() {
return true;
}
protected NetworkOrchestrator() {
setStateMachine();
}
@ -772,7 +767,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
}
}
final List<NetworkVO> networks = new ArrayList<NetworkVO>();
final List<NetworkVO> networks = new ArrayList<>();
long related = -1;
@ -895,7 +890,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
Arrays.fill(deviceIds, false);
List<Pair<Network, NicProfile>> profilesList = getOrderedNetworkNicProfileMapping(networks);
final List<NicProfile> nics = new ArrayList<NicProfile>(size);
final List<NicProfile> nics = new ArrayList<>(size);
NicProfile defaultNic = null;
Network nextNetwork = null;
for (Pair<Network, NicProfile> networkNicPair : profilesList) {
@ -972,16 +967,16 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
for (final Map.Entry<? extends Network, List<? extends NicProfile>> network : networks.entrySet()) {
List<? extends NicProfile> requestedProfiles = network.getValue();
if (requestedProfiles == null) {
requestedProfiles = new ArrayList<NicProfile>();
requestedProfiles = new ArrayList<>();
}
if (requestedProfiles.isEmpty()) {
requestedProfiles.add(null);
}
for (final NicProfile requested : requestedProfiles) {
profilesList.add(new Pair<Network, NicProfile>(network.getKey(), requested));
profilesList.add(new Pair<>(network.getKey(), requested));
}
}
profilesList.sort(new Comparator<Pair<Network, NicProfile>>() {
profilesList.sort(new Comparator<>() {
@Override
public int compare(Pair<Network, NicProfile> pair1, Pair<Network, NicProfile> pair2) {
int profile1Order = Integer.MAX_VALUE;
@ -1064,7 +1059,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
}
private NicVO persistNicAfterRaceCheck(final NicVO nic, final Long networkId, final NicProfile profile, int deviceId) {
return Transaction.execute(new TransactionCallback<NicVO>() {
return Transaction.execute(new TransactionCallback<>() {
@Override
public NicVO doInTransaction(TransactionStatus status) {
NicVO vo = _nicDao.findNonPlaceHolderByIp4AddressAndNetworkId(profile.getIPv4Address(), networkId);
@ -1085,7 +1080,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
logger.debug("Allocating nic for vm {} in network {} with requested profile {}", vm.getVirtualMachine(), network, requested);
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, ntwkVO.getGuruName());
NicVO vo = null;
NicVO vo;
boolean retryIpAllocation;
do {
retryIpAllocation = false;
@ -1161,7 +1156,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
_nicDao.update(vo.getId(), vo);
setMtuInVRNicProfile(networks, network.getTrafficType(), vmNic);
}
return new Pair<NicProfile, Integer>(vmNic, Integer.valueOf(deviceId));
return new Pair<>(vmNic, Integer.valueOf(deviceId));
}
private boolean isNicAllocatedForProviderPublicNetworkOnVR(Network network, NicProfile requested, VirtualMachineProfile vm, Provider provider) {
@ -1443,7 +1438,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
Pair<NetworkGuru, NetworkVO> implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context, final boolean isRouter) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
Pair<NetworkGuru, NetworkVO> implemented = null;
Pair<NetworkGuru, NetworkVO> implemented;
if (!isRouter) {
implemented = implementNetwork(networkId, dest, context);
} else {
@ -1454,7 +1449,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
// in issues. In order to avoid it, implementNetwork() call for VR is replaced with below code.
final NetworkVO network = _networksDao.findById(networkId);
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
implemented = new Pair<NetworkGuru, NetworkVO>(guru, network);
implemented = new Pair<>(guru, network);
}
return implemented;
}
@ -1542,7 +1537,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
@DB
public Pair<NetworkGuru, NetworkVO> implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
final Pair<NetworkGuru, NetworkVO> implemented = new Pair<NetworkGuru, NetworkVO>(null, null);
final Pair<NetworkGuru, NetworkVO> implemented = new Pair<>(null, null);
NetworkVO network = _networksDao.findById(networkId);
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
@ -1609,10 +1604,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
return implemented;
} catch (final NoTransitionException e) {
logger.error(e.getMessage());
return new Pair<NetworkGuru, NetworkVO>(null, null);
return new Pair<>(null, null);
} catch (final CloudRuntimeException | OperationTimedoutException e) {
logger.error("Caught exception: {}", e.getMessage());
return new Pair<NetworkGuru, NetworkVO>(null, null);
return new Pair<>(null, null);
} finally {
if (implemented.first() == null) {
logger.debug("Cleaning up because we're unable to implement the network {}", network);
@ -1656,7 +1651,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
&& (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) || _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Gateway))
&& (network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) {
List<IPAddressVO> ips = null;
List<IPAddressVO> ips;
final Account owner = _entityMgr.findById(Account.class, network.getAccountId());
if (network.getVpcId() != null) {
ips = _ipAddressDao.listByAssociatedVpc(network.getVpcId(), true);
@ -2145,7 +2140,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
// we have to implement default nics first - to ensure that default network elements start up first in multiple
//nics case
// (need for setting DNS on Dhcp to domR's Ip4 address)
Collections.sort(nics, new Comparator<NicVO>() {
Collections.sort(nics, new Comparator<>() {
@Override
public int compare(final NicVO nic1, final NicVO nic2) {
@ -2183,7 +2178,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
final NicVO nic = _nicDao.findById(nicId);
NicProfile profile = null;
NicProfile profile;
if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) {
nic.setState(Nic.State.Reserving);
nic.setReservationId(context.getReservationId());
@ -2344,7 +2339,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
vm.addNic(profile);
}
final List<String> addedURIs = new ArrayList<String>();
final List<String> addedURIs = new ArrayList<>();
if (guestNetworkId != null) {
final List<IPAddressVO> publicIps = _ipAddressDao.listByAssociatedNetwork(guestNetworkId, null);
for (final IPAddressVO userIp : publicIps) {
@ -2992,7 +2987,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
final Network network = Transaction.execute(new TransactionCallback<>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
@ -3097,7 +3092,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
userNetwork.setNetworkCidrSize(networkCidrSize);
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
Network network;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
@ -3226,10 +3221,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final boolean success = shutdownNetworkElementsAndResources(context, cleanupElements, network);
final NetworkVO networkFinal = network;
final boolean result = Transaction.execute(new TransactionCallback<Boolean>() {
final boolean result = Transaction.execute(new TransactionCallback<>() {
@Override
public Boolean doInTransaction(final TransactionStatus status) {
boolean result = false;
boolean result;
if (success) {
logger.debug("Network {} is shutdown successfully, cleaning up corresponding resources now.", networkFinal);
@ -3447,7 +3442,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final NetworkVO networkFinal = network;
try {
final List<VlanVO> deletedVlanRangeToPublish = Transaction.execute(new TransactionCallback<List<VlanVO>>() {
final List<VlanVO> deletedVlanRangeToPublish = Transaction.execute(new TransactionCallback<>() {
@Override
public List<VlanVO> doInTransaction(TransactionStatus status) {
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
@ -3503,7 +3498,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
publishDeletedVlanRanges(deletedVlanRangeToPublish);
if (_networksDao.findById(network.getId()) == null) {
// remove its related ACL permission
final Pair<Class<?>, Long> networkMsg = new Pair<Class<?>, Long>(Network.class, networkFinal.getId());
final Pair<Class<?>, Long> networkMsg = new Pair<>(Network.class, networkFinal.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
}
UsageEventUtils.publishNetworkDeletion(network);
@ -3586,9 +3581,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
public void reallyRun() {
try {
final List<Long> shutdownList = new ArrayList<Long>();
final List<Long> shutdownList = new ArrayList<>();
final long currentTime = System.currentTimeMillis() / 1000;
final HashMap<Long, Long> stillFree = new HashMap<Long, Long>();
final HashMap<Long, Long> stillFree = new HashMap<>();
final List<Long> networkIds = _networksDao.findNetworksToGarbageCollect();
final int netGcWait = NumbersUtil.parseInt(_configDao.getValue(NetworkGcWait.key()), 60);
@ -3958,7 +3953,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
@Override
public List<? extends Nic> listVmNics(final long vmId, final Long nicId, final Long networkId, String keyword) {
List<NicVO> result = null;
List<NicVO> result;
if (keyword == null || keyword.isEmpty()) {
if (nicId == null && networkId == null) {
@ -4001,8 +3996,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
if (dc.getNetworkType() == NetworkType.Basic) {
final List<NicVO> nics = _nicDao.listByVmId(vmInstance.getId());
final NetworkVO network = _networksDao.findById(nics.get(0).getNetworkId());
final LinkedHashMap<Network, List<? extends NicProfile>> profiles = new LinkedHashMap<Network, List<? extends NicProfile>>();
profiles.put(network, new ArrayList<NicProfile>());
final LinkedHashMap<Network, List<? extends NicProfile>> profiles = new LinkedHashMap<>();
profiles.put(network, new ArrayList<>());
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
@Override
@ -4136,7 +4131,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
// Mark all static rules as revoked and apply them on the backend (not in the DB)
final List<FirewallRuleVO> firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.StaticNat);
final List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
final List<StaticNatRule> staticNatRules = new ArrayList<>();
logger.debug("Releasing {} static nat rules for network {} as a part of shutdownNetworkRules", firewallStaticNatRules.size(), network);
for (final FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) {
@ -4258,7 +4253,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
// Get all ip addresses, mark as releasing and release them on the backend
final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
final List<PublicIp> publicIpsToRelease = new ArrayList<PublicIp>();
final List<PublicIp> publicIpsToRelease = new ArrayList<>();
if (userIps != null && !userIps.isEmpty()) {
for (final IPAddressVO userIp : userIps) {
userIp.setState(IpAddress.State.Releasing);
@ -4307,7 +4302,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final String dataCenter = startup.getDataCenter();
long dcId = -1;
long dcId;
DataCenterVO dc = _dcDao.findByName(dataCenter);
if (dc == null) {
try {
@ -4324,7 +4319,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
logger.debug("Host's hypervisorType is: {}", hypervisorType);
final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<PhysicalNetworkSetupInfo>();
final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<>();
// list all physicalnetworks in the zone & for each get the network names
final List<PhysicalNetworkVO> physicalNtwkList = _physicalNetworkDao.listByZone(dcId);
@ -4403,8 +4398,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
@Override
public Map<String, String> finalizeServicesAndProvidersForNetwork(final NetworkOffering offering, final Long physicalNetworkId) {
final Map<String, String> svcProviders = new HashMap<String, String>();
final Map<String, List<String>> providerSvcs = new HashMap<String, List<String>>();
final Map<String, String> svcProviders = new HashMap<>();
final Map<String, List<String>> providerSvcs = new HashMap<>();
final List<NetworkOfferingServiceMapVO> servicesMap = _ntwkOfferingSrvcDao.listByNetworkOfferingId(offering.getId());
final boolean checkPhysicalNetwork = physicalNetworkId != null ? true : false;
@ -4434,7 +4429,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
svcProviders.put(service, provider);
List<String> l = providerSvcs.get(provider);
if (l == null) {
providerSvcs.put(provider, l = new ArrayList<String>());
providerSvcs.put(provider, l = new ArrayList<>());
}
l.add(service);
}
@ -4444,7 +4439,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
private List<Provider> getNetworkProviders(final long networkId) {
final List<String> providerNames = _ntwkSrvcDao.getDistinctProviders(networkId);
final List<Provider> providers = new ArrayList<Provider>();
final List<Provider> providers = new ArrayList<>();
for (final String providerName : providerNames) {
providers.add(Network.Provider.getProvider(providerName));
}
@ -4539,7 +4534,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
@Override
public List<NicProfile> getNicProfiles(final Long vmId, HypervisorType hypervisorType) {
final List<NicVO> nics = _nicDao.listByVmId(vmId);
final List<NicProfile> profiles = new ArrayList<NicProfile>();
final List<NicProfile> profiles = new ArrayList<>();
if (nics != null) {
for (final Nic nic : nics) {
@ -4605,12 +4600,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
}
private Map<Service, Set<Provider>> getServiceProvidersMap(final long networkId) {
final Map<Service, Set<Provider>> map = new HashMap<Service, Set<Provider>>();
final Map<Service, Set<Provider>> map = new HashMap<>();
final List<NetworkServiceMapVO> nsms = _ntwkSrvcDao.getServicesInNetwork(networkId);
for (final NetworkServiceMapVO nsm : nsms) {
Set<Provider> providers = map.get(Service.getService(nsm.getService()));
if (providers == null) {
providers = new HashSet<Provider>();
providers = new HashSet<>();
}
providers.add(Provider.getProvider(nsm.getProvider()));
map.put(Service.getService(nsm.getService()), providers);
@ -4622,14 +4617,14 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
public List<Provider> getProvidersForServiceInNetwork(final Network network, final Service service) {
final Map<Service, Set<Provider>> service2ProviderMap = getServiceProvidersMap(network.getId());
if (service2ProviderMap.get(service) != null) {
final List<Provider> providers = new ArrayList<Provider>(service2ProviderMap.get(service));
final List<Provider> providers = new ArrayList<>(service2ProviderMap.get(service));
return providers;
}
return null;
}
protected List<NetworkElement> getElementForServiceInNetwork(final Network network, final Service service) {
final List<NetworkElement> elements = new ArrayList<NetworkElement>();
final List<NetworkElement> elements = new ArrayList<>();
final List<Provider> providers = getProvidersForServiceInNetwork(network, service);
//Only support one provider now
if (providers == null) {
@ -4663,7 +4658,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
final List<NetworkElement> lbElements = getElementForServiceInNetwork(network, Service.Lb);
NetworkElement lbElement = null;
if (lbElements.size() > 1) {
String providerName = null;
String providerName;
//get network offering details
final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (lbScheme == Scheme.Public) {
@ -4751,7 +4746,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
}
}
final String finalSelectedIp = selectedIp;
final NicVO vo = Transaction.execute(new TransactionCallback<NicVO>() {
final NicVO vo = Transaction.execute(new TransactionCallback<>() {
@Override
public NicVO doInTransaction(TransactionStatus status) {
if (StringUtils.isBlank(macAddress)) {
@ -4901,9 +4896,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
return NetworkOrchestrationService.class.getSimpleName();
}
public static final ConfigKey<Integer> NetworkGcWait = new ConfigKey<Integer>(Integer.class, "network.gc.wait", "Advanced", "600",
public static final ConfigKey<Integer> NetworkGcWait = new ConfigKey<>(Integer.class, "network.gc.wait", "Advanced", "600",
"Time (in seconds) to wait before shutting down a network that's not in used", false, Scope.Global, null);
public static final ConfigKey<Integer> NetworkGcInterval = new ConfigKey<Integer>(Integer.class, "network.gc.interval", "Advanced", "600",
public static final ConfigKey<Integer> NetworkGcInterval = new ConfigKey<>(Integer.class, "network.gc.interval", "Advanced", "600",
"Seconds to wait before checking for networks to shutdown", true, Scope.Global, null);
@Override
@ -4911,6 +4906,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra
return new ConfigKey<?>[]{NetworkGcWait, NetworkGcInterval, NetworkLockTimeout, DeniedRoutes,
GuestDomainSuffix, NetworkThrottlingRate, MinVRVersion,
PromiscuousMode, MacAddressChanges, ForgedTransmits, MacLearning, RollingRestartEnabled,
TUNGSTEN_ENABLED, NSX_ENABLED, NETRIS_ENABLED };
TUNGSTEN_ENABLED, NSX_ENABLED, NETRIS_ENABLED, NETWORK_LB_HAPROXY_MAX_CONN};
}
}

View File

@ -29,6 +29,7 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.cloud.network.RouterHealthCheckResult;
import com.cloud.network.VirtualNetworkApplianceService;
import com.cloud.utils.StringUtils;
@Entity
@ -49,7 +50,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult {
private String checkType;
@Column(name = "check_result")
private boolean checkResult;
private VirtualNetworkApplianceService.RouterHealthStatus checkResult;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_update", updatable = true, nullable = true)
@ -87,7 +88,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult {
}
@Override
public boolean getCheckResult() {
public VirtualNetworkApplianceService.RouterHealthStatus getCheckResult() {
return checkResult;
}
@ -105,7 +106,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult {
return checkDetails;
}
public void setCheckResult(boolean checkResult) {
public void setCheckResult(VirtualNetworkApplianceService.RouterHealthStatus checkResult) {
this.checkResult = checkResult;
}

View File

@ -1,20 +0,0 @@
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--;
-- Schema upgrade from 4.20.1.0 to 4.21.0.0
--;

View File

@ -19,5 +19,9 @@
-- Schema upgrade from 4.21.0.0 to 4.22.0.0
--;
-- health check status as enum
CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('router_health_check', 'check_result', 'check_result', 'varchar(16) NOT NULL COMMENT "check executions result: SUCCESS, FAILURE, WARNING, UNKNOWN"');
-- Increase length of scripts_version column to 128 due to md5sum to sha512sum change
CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('cloud.domain_router', 'scripts_version', 'scripts_version', 'VARCHAR(128)');

View File

@ -378,23 +378,21 @@ public class ConfigKey<T> {
if (type.isAssignableFrom(Boolean.class)) {
return (T)Boolean.valueOf(value);
} else if (type.isAssignableFrom(Integer.class)) {
return (T)new Integer(Integer.parseInt(value) * multiplier.intValue());
return (T)Integer.valueOf(Integer.parseInt(value) * multiplier.intValue());
} else if (type.isAssignableFrom(Long.class)) {
return (T)new Long(Long.parseLong(value) * multiplier.longValue());
return (T)Long.valueOf(Long.parseLong(value) * multiplier.longValue());
} else if (type.isAssignableFrom(Short.class)) {
return (T)new Short(Short.parseShort(value));
return (T)Short.valueOf(Short.parseShort(value));
} else if (type.isAssignableFrom(String.class)) {
return (T)value;
} else if (type.isAssignableFrom(Float.class)) {
return (T)new Float(Float.parseFloat(value) * multiplier.floatValue());
return (T)Float.valueOf(Float.parseFloat(value) * multiplier.floatValue());
} else if (type.isAssignableFrom(Double.class)) {
return (T)new Double(Double.parseDouble(value) * multiplier.doubleValue());
} else if (type.isAssignableFrom(String.class)) {
return (T)value;
return (T)Double.valueOf(Double.parseDouble(value) * multiplier.doubleValue());
} else if (type.isAssignableFrom(Date.class)) {
return (T)Date.valueOf(value);
} else if (type.isAssignableFrom(Character.class)) {
return (T)new Character(value.charAt(0));
return (T)Character.valueOf(value.charAt(0));
} else {
throw new CloudRuntimeException("Unsupported data type for config values: " + type);
}

View File

@ -32,6 +32,7 @@ import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd;
import org.apache.cloudstack.config.ApiServiceConfiguration;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.springframework.stereotype.Component;
@ -201,7 +202,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast
NetworkOffering offering = _networkOfferingDao.findById(guestNetworkId);
String maxconn = null;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
maxconn = NetworkOrchestrationService.NETWORK_LB_HAPROXY_MAX_CONN.value().toString();
} else {
maxconn = offering.getConcurrentConnections().toString();
}

View File

@ -488,7 +488,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
String maxconn = null;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
maxconn = NetworkOrchestrationService.NETWORK_LB_HAPROXY_MAX_CONN.value().toString();
} else {
maxconn = offering.getConcurrentConnections().toString();
}

View File

@ -5100,7 +5100,17 @@ public class ApiResponseHelper implements ResponseGenerator {
healthCheckResponse.setObjectName("routerhealthchecks");
healthCheckResponse.setCheckName(hcResult.getCheckName());
healthCheckResponse.setCheckType(hcResult.getCheckType());
healthCheckResponse.setResult(hcResult.getCheckResult());
switch (hcResult.getCheckResult()) {
case SUCCESS:
healthCheckResponse.setResult(true);
break;
case FAILED:
healthCheckResponse.setResult(false);
break;
default:
// no result if not definite
}
healthCheckResponse.setState(hcResult.getCheckResult());
healthCheckResponse.setLastUpdated(hcResult.getLastUpdateTime());
healthCheckResponse.setDetails(hcResult.getParsedCheckDetails());
responses.add(healthCheckResponse);

View File

@ -255,14 +255,6 @@ public enum Config {
"8081",
"Load Balancer(haproxy) stats port number.",
null),
NetworkLBHaproxyMaxConn(
"Network",
ManagementServer.class,
Integer.class,
"network.loadbalancer.haproxy.max.conn",
"4096",
"Load Balancer(haproxy) maximum number of concurrent connections(global max)",
null),
NetworkRouterRpFilter(
"Network",
ManagementServer.class,
@ -1714,11 +1706,11 @@ public enum Config {
private static final HashMap<Integer, List<Config>> s_scopeLevelConfigsMap = new HashMap<>();
static {
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Zone.getBitValue(), new ArrayList<Config>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster.getBitValue(), new ArrayList<Config>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool.getBitValue(), new ArrayList<Config>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Account.getBitValue(), new ArrayList<Config>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Global.getBitValue(), new ArrayList<Config>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Zone.getBitValue(), new ArrayList<>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster.getBitValue(), new ArrayList<>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool.getBitValue(), new ArrayList<>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Account.getBitValue(), new ArrayList<>());
s_scopeLevelConfigsMap.put(ConfigKey.Scope.Global.getBitValue(), new ArrayList<>());
for (Config c : Config.values()) {
//Creating group of parameters per each level (zone/cluster/pool/account)
@ -1731,23 +1723,22 @@ public enum Config {
}
}
private static final HashMap<String, List<Config>> Configs = new HashMap<String, List<Config>>();
private static final HashMap<String, List<Config>> Configs = new HashMap<>();
static {
// Add categories
Configs.put("Alert", new ArrayList<Config>());
Configs.put("Storage", new ArrayList<Config>());
Configs.put("Snapshots", new ArrayList<Config>());
Configs.put("Network", new ArrayList<Config>());
Configs.put("Usage", new ArrayList<Config>());
Configs.put("Console Proxy", new ArrayList<Config>());
Configs.put("Advanced", new ArrayList<Config>());
Configs.put("Usage", new ArrayList<Config>());
Configs.put("Developer", new ArrayList<Config>());
Configs.put("Hidden", new ArrayList<Config>());
Configs.put("Account Defaults", new ArrayList<Config>());
Configs.put("Domain Defaults", new ArrayList<Config>());
Configs.put("Project Defaults", new ArrayList<Config>());
Configs.put("Secure", new ArrayList<Config>());
Configs.put("Account Defaults", new ArrayList<>());
Configs.put("Advanced", new ArrayList<>());
Configs.put("Alert", new ArrayList<>());
Configs.put("Console Proxy", new ArrayList<>());
Configs.put("Developer", new ArrayList<>());
Configs.put("Domain Defaults", new ArrayList<>());
Configs.put("Hidden", new ArrayList<>());
Configs.put("Network", new ArrayList<>());
Configs.put("Secure", new ArrayList<>());
Configs.put("Snapshots", new ArrayList<>());
Configs.put("Storage", new ArrayList<>());
Configs.put("Usage", new ArrayList<>());
Configs.put("Project Defaults", new ArrayList<>());
// Add values into HashMap
for (Config c : Config.values()) {
@ -1758,11 +1749,11 @@ public enum Config {
}
}
private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) {
Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) {
this(category, componentClass, type, name, defaultValue, description, range, null, null);
}
private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range, ConfigKey.Kind kind, String options) {
Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range, ConfigKey.Kind kind, String options) {
_category = category;
_componentClass = componentClass;
_type = type;
@ -1867,7 +1858,7 @@ public enum Config {
public static List<String> getCategories() {
Object[] keys = Configs.keySet().toArray();
List<String> categories = new ArrayList<String>();
List<String> categories = new ArrayList<>();
for (Object key : keys) {
categories.add((String)key);
}

View File

@ -6810,7 +6810,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) {
maxconn = cmd.getMaxconnections();
if (maxconn == null) {
maxconn = Integer.parseInt(_configDao.getValue(Config.NetworkLBHaproxyMaxConn.key()));
maxconn = NetworkOrchestrationService.NETWORK_LB_HAPROXY_MAX_CONN.value();
}
}
if (cmd.getKeepAliveEnabled() != null && cmd.getKeepAliveEnabled()) {

View File

@ -2138,32 +2138,33 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
//Included revoked rules to remove the rules of ips which are in revoke state
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.LoadBalancing);
if (deleteRulesFails(caller, callerUserId, rules)) return false;
return true;
}
private boolean deleteRulesFails(Account caller, long callerUserId, List<FirewallRuleVO> rules) {
if (rules != null) {
logger.debug("Found " + rules.size() + " lb rules to cleanup");
logger.debug("Found {} lb rules to cleanup", rules.size());
for (FirewallRule rule : rules) {
boolean result = deleteLoadBalancerRule(rule.getId(), true, caller, callerUserId, false);
if (result == false) {
logger.warn("Unable to remove load balancer rule {}", rule);
return false;
}
if (deleteRuleFails(caller, callerUserId, rule)) return true;
}
}
return true;
return false;
}
private boolean deleteRuleFails(Account caller, long callerUserId, FirewallRule rule) {
boolean result = deleteLoadBalancerRule(rule.getId(), true, caller, callerUserId, false);
if (result == false) {
logger.warn("Unable to remove load balancer rule {}", rule);
return true;
}
return false;
}
@Override
public boolean removeAllLoadBalanacersForNetwork(long networkId, Account caller, long callerUserId) {
List<FirewallRuleVO> rules = _firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.LoadBalancing);
if (rules != null) {
logger.debug("Found " + rules.size() + " lb rules to cleanup");
for (FirewallRule rule : rules) {
boolean result = deleteLoadBalancerRule(rule.getId(), true, caller, callerUserId, false);
if (result == false) {
logger.warn("Unable to remove load balancer rule {}", rule);
return false;
}
}
}
if (deleteRulesFails(caller, callerUserId, rules)) return false;
return true;
}
@ -2792,5 +2793,4 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
}
return null;
}
}

View File

@ -28,19 +28,19 @@ import java.util.Set;
import javax.inject.Inject;
import com.cloud.agent.api.HandleCksIsoCommand;
import com.cloud.network.rules.PortForwardingRuleVO;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.network.BgpPeer;
import org.apache.cloudstack.network.BgpPeerTO;
import org.apache.cloudstack.network.dao.BgpPeerDetailsDao;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.cloud.agent.api.HandleCksIsoCommand;
import com.cloud.agent.api.SetupGuestNetworkCommand;
import com.cloud.agent.api.routing.CreateIpAliasCommand;
import com.cloud.agent.api.routing.DeleteIpAliasCommand;
@ -122,6 +122,7 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.vpc.NetworkACLItem;
@ -255,8 +256,8 @@ public class CommandSetupHelper {
}
public void createApplyVpnUsersCommand(final List<? extends VpnUser> users, final VirtualRouter router, final Commands cmds) {
final List<VpnUser> addUsers = new ArrayList<VpnUser>();
final List<VpnUser> removeUsers = new ArrayList<VpnUser>();
final List<VpnUser> addUsers = new ArrayList<>();
final List<VpnUser> removeUsers = new ArrayList<>();
for (final VpnUser user : users) {
if (user.getState() == VpnUser.State.Add || user.getState() == VpnUser.State.Active) {
addUsers.add(user);
@ -319,7 +320,7 @@ public class CommandSetupHelper {
public void configDnsMasq(final VirtualRouter router, final Network network, final Commands cmds) {
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
final List<NicIpAliasVO> ipAliasVOList = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.State.active);
final List<DhcpTO> ipList = new ArrayList<DhcpTO>();
final List<DhcpTO> ipList = new ArrayList<>();
final NicVO router_guest_nic = _nicDao.findByNtwkIdAndInstanceId(network.getId(), router.getId());
final String cidr = NetUtils.getCidrFromGatewayAndNetmask(router_guest_nic.getIPv4Gateway(), router_guest_nic.getIPv4Netmask());
@ -384,9 +385,9 @@ public class CommandSetupHelper {
final NicProfile nicProfile = new NicProfile(nic, guestNetwork, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(guestNetwork.getId(),
router.getId()), _networkModel.isSecurityGroupSupportedInNetwork(guestNetwork), _networkModel.getNetworkTag(router.getHypervisorType(), guestNetwork));
final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
String maxconn = null;
String maxconn;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
maxconn = NetworkOrchestrationService.NETWORK_LB_HAPROXY_MAX_CONN.value().toString();
} else {
maxconn = offering.getConcurrentConnections().toString();
}
@ -408,7 +409,7 @@ public class CommandSetupHelper {
}
public void createApplyPortForwardingRulesCommands(final List<? extends PortForwardingRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<PortForwardingRuleTO> rulesTO = new ArrayList<PortForwardingRuleTO>();
final List<PortForwardingRuleTO> rulesTO = new ArrayList<>();
if (rules != null) {
for (final PortForwardingRule rule : rules) {
_rulesDao.loadSourceCidrs((PortForwardingRuleVO) rule);
@ -418,7 +419,7 @@ public class CommandSetupHelper {
}
}
SetPortForwardingRulesCommand cmd = null;
SetPortForwardingRulesCommand cmd;
if (router.getVpcId() != null) {
cmd = new SetPortForwardingRulesVpcCommand(rulesTO);
@ -436,7 +437,7 @@ public class CommandSetupHelper {
}
public void createApplyStaticNatRulesCommands(final List<? extends StaticNatRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
final List<StaticNatRuleTO> rulesTO = new ArrayList<>();
if (rules != null) {
for (final StaticNatRule rule : rules) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
@ -455,11 +456,11 @@ public class CommandSetupHelper {
}
public void createApplyFirewallRulesCommands(final List<? extends FirewallRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
final List<FirewallRuleTO> rulesTO = new ArrayList<>();
String systemRule = null;
Boolean defaultEgressPolicy = false;
if (rules != null) {
if (rules.size() > 0) {
if (!rules.isEmpty()) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
@ -506,9 +507,9 @@ public class CommandSetupHelper {
String systemRule = null;
final NetworkVO network = _networkDao.findById(guestNetworkId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
Boolean defaultEgressPolicy = offering.isEgressDefaultPolicy();;
Boolean defaultEgressPolicy = offering.isEgressDefaultPolicy();
if (rules != null) {
if (rules.size() > 0) {
if (!rules.isEmpty()) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
@ -543,14 +544,13 @@ public class CommandSetupHelper {
}
public void createFirewallRulesCommands(final List<? extends FirewallRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
final List<FirewallRuleTO> rulesTO = new ArrayList<>();
String systemRule = null;
Boolean defaultEgressPolicy = false;
if (rules != null) {
if (rules.size() > 0) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
boolean isSystemFirewallEgressRule = !rules.isEmpty() && rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System;
if (isSystemFirewallEgressRule) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
for (final FirewallRule rule : rules) {
_rulesDao.loadSourceCidrs((FirewallRuleVO) rule);
@ -597,7 +597,7 @@ public class CommandSetupHelper {
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
Boolean defaultEgressPolicy = offering.isEgressDefaultPolicy();
if (rules != null) {
if (rules.size() > 0) {
if (!rules.isEmpty()) {
if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
}
@ -638,7 +638,7 @@ public class CommandSetupHelper {
public void createNetworkACLsCommands(final List<? extends NetworkACLItem> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId,
final boolean privateGateway) {
final List<NetworkACLTO> rulesTO = new ArrayList<NetworkACLTO>();
final List<NetworkACLTO> rulesTO = new ArrayList<>();
String guestVlan = null;
final Network guestNtwk = _networkDao.findById(guestNetworkId);
final URI uri = guestNtwk.getBroadcastUri();
@ -687,7 +687,7 @@ public class CommandSetupHelper {
}
public void createApplyStaticNatCommands(final List<? extends StaticNat> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
final List<StaticNatRuleTO> rulesTO = new ArrayList<>();
if (rules != null) {
for (final StaticNat rule : rules) {
final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
@ -811,7 +811,7 @@ public class CommandSetupHelper {
Boolean addSourceNat = null;
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<>();
for (final PublicIpAddress ipAddress : ips) {
String vlanTag = ipAddress.getVlanTag();
if (Objects.isNull(vlanTag)) {
@ -819,7 +819,7 @@ public class CommandSetupHelper {
}
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
ipList = new ArrayList<>();
}
// VR doesn't support release for sourceNat IP address; so reset the
// state
@ -847,7 +847,7 @@ public class CommandSetupHelper {
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
Collections.sort(ipAddrList, new Comparator<>() {
@Override
public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
final boolean s1 = o1.isSourceNat();
@ -896,7 +896,7 @@ public class CommandSetupHelper {
}
ipsToSend[i++] = ip;
if (ipAddr.isSourceNat()) {
sourceNatIpAdd = new Pair<IpAddressTO, Long>(ip, ipAddr.getNetworkId());
sourceNatIpAdd = new Pair<>(ip, ipAddr.getNetworkId());
addSourceNat = add;
}
@ -934,12 +934,12 @@ public class CommandSetupHelper {
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<>();
for (final PublicIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PublicIpAddress>();
ipList = new ArrayList<>();
}
// domR doesn't support release for sourceNat IP address; so reset
// the state
@ -952,7 +952,7 @@ public class CommandSetupHelper {
final List<NicVO> nics = _nicDao.listByVmId(router.getId());
String baseMac = null;
Map<String, String> vlanMacAddress = new HashMap<String, String>();;
Map<String, String> vlanMacAddress = new HashMap<>();
Long guestNetworkId = null;
for (final NicVO nic : nics) {
final NetworkVO nw = _networkDao.findById(nic.getNetworkId());
@ -973,7 +973,7 @@ public class CommandSetupHelper {
final String vlanTagKey = vlanAndIp.getKey();
final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
// Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
Collections.sort(ipAddrList, new Comparator<>() {
@Override
public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
final boolean s1 = o1.isSourceNat();
@ -1001,7 +1001,7 @@ public class CommandSetupHelper {
final String vlanId = ipAddr.getVlanTag();
final String vlanGateway = ipAddr.getGateway();
final String vlanNetmask = ipAddr.getNetmask();
String vifMacAddress = null;
String vifMacAddress;
final String vlanTag = BroadcastDomainType.getValue(BroadcastDomainType.fromString(ipAddr.getVlanTag()));
if (vlanMacAddress.containsKey(vlanTag)) {
vifMacAddress = vlanMacAddress.get(vlanTag);
@ -1077,7 +1077,7 @@ public class CommandSetupHelper {
private Map<String, Boolean> getVlanLastIpMap(Long vpcId, Long guestNetworkId) {
// for network if the ips does not have any rules, then only last ip
final Map<String, Boolean> vlanLastIpMap = new HashMap<String, Boolean>();
final Map<String, Boolean> vlanLastIpMap = new HashMap<>();
final List<IPAddressVO> userIps;
if (vpcId != null) {
userIps = _ipAddressDao.listByAssociatedVpc(vpcId, null);
@ -1145,12 +1145,12 @@ public class CommandSetupHelper {
// Ensure that in multiple vlans case we first send all ip addresses of
// vlan1, then all ip addresses of vlan2, etc..
final Map<String, ArrayList<PrivateIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PrivateIpAddress>>();
final Map<String, ArrayList<PrivateIpAddress>> vlanIpMap = new HashMap<>();
for (final PrivateIpAddress ipAddress : ips) {
final String vlanTag = ipAddress.getBroadcastUri();
ArrayList<PrivateIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) {
ipList = new ArrayList<PrivateIpAddress>();
ipList = new ArrayList<>();
}
ipList.add(ipAddress);

View File

@ -29,7 +29,7 @@ def main():
if "maxCpuUsage" not in data:
print("Missing maxCpuUsage in health_checks_data systemThresholds, skipping")
exit(0)
exit(3)
maxCpuUsage = float(data["maxCpuUsage"])
cmd = "top -b -n2 -p 1 | fgrep \"Cpu(s)\" | tail -1 | " \
@ -48,7 +48,7 @@ def main():
exit(0)
else:
print("Failed to retrieve cpu usage using " + cmd)
exit(1)
exit(3)
if __name__ == "__main__":

View File

@ -25,7 +25,7 @@ def main():
if vMs is None or len(vMs) == 0:
print("No VMs running data available, skipping")
exit(0)
exit(3)
try:
with open('/etc/dhcphosts.txt', 'r') as hostsFile:

View File

@ -28,7 +28,7 @@ def main():
if "minDiskNeeded" not in data:
print("Missing minDiskNeeded in health_checks_data systemThresholds, skipping")
exit(0)
exit(3)
minDiskNeeded = float(data["minDiskNeeded"]) * 1024
s = statvfs('/')

View File

@ -34,6 +34,13 @@ class StatusCodes:
STOPPED = 4
STARTING = 5
# see com.cloud.network.VirtualNetworkApplianceService.RouterHealthStatus and make sure to keep it aligned
class RouterHealthStatus:
SUCCESS = "SUCCESS"
FAILED = "FAILED"
WARNING = "WARNING"
UNKNOWN = "UNKNOWN"
class Log:
INFO = 'INFO'
ALERT = 'ALERT'
@ -267,24 +274,35 @@ def monitProcess( processes_info ):
printd ("---------------------------\nchecking the service %s\n---------------------------- " %process)
serviceName = process + ".service"
processStatus, wasRestarted = checkProcessStatus(properties)
if processStatus != StatusCodes.RUNNING:
printd( "\n Service %s is not Running"%process)
checkEndTime = time.time()
service_status[serviceName] = {
"success": "false",
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": "service down at last check " + str(csec)
}
routerHealth = RouterHealthStatus.UNKNOWN
match processStatus:
case StatusCodes.RUNNING:
routerHealth = RouterHealthStatus.SUCCESS
routerMessage = "service is running" + (", was restarted" if wasRestarted else "")
case StatusCodes.STARTING:
routerHealth = RouterHealthStatus.WARNING
routerMessage = "service is starting at " + str(csec)
case StatusCodes.STOPPED:
routerHealth = RouterHealthStatus.WARNING
routerMessage = "service down at last check " + str(csec)
case StatusCodes.SUCCESS:
routerHealth = RouterHealthStatus.UNKNOWN
routerMessage = "service exisits but no status"
case StatusCodes.FAILED | StatusCodes.INVALID_INP:
routerHealth = RouterHealthStatus.FAILED
routerMessage = "service down at last check " + str(csec)
printd( "\n Service %s is status == " % routerHealth)
checkEndTime = time.time()
service_status[serviceName] = {
"success": routerHealth,
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": routerMessage
}
if routerHealth != RouterHealthStatus.SUCCESS:
failing_services.append(serviceName)
else:
checkEndTime = time.time()
service_status[serviceName] = {
"success": "true",
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": "service is running" + (", was restarted" if wasRestarted else "")
}
return service_status, failing_services
@ -299,24 +317,26 @@ def execute(script, checkType = "basic"):
output = pout.communicate()[0].decode().strip()
checkEndTime = time.time()
if exitStatus == 0:
if len(output) > 0:
printd("Successful execution of " + script)
return {
"success": "true",
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": output
}
return {} #Skip script if no output is received
else:
printd("Script execution failed " + script)
return {
"success": "false",
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": output
}
# we run all scripts and have to ignore the ones that do nothing
if not len(output) > 0 and exitStatus == 0:
return {}
routerHealth = RouterHealthStatus.SUCCESS
match exitStatus:
case 1:
routerHealth = RouterHealthStatus.FAILED
case 2:
routerHealth = RouterHealthStatus.WARNING
case 3:
routerHealth = RouterHealthStatus.UNKNOWN
printd("Ended execution of " + script)
return {
"success": routerHealth,
"lastUpdate": str(int(checkStartTime * 1000)),
"lastRunDuration": str((checkEndTime - checkStartTime) * 1000),
"message": output
}
def main(checkType = "basic"):
startTime = time.time()
@ -349,7 +369,7 @@ def main(checkType = "basic"):
ret = execute(fpath, checkType)
if len(ret) == 0:
continue
if "success" in ret and ret["success"].lower() == "false":
if "success" in ret and ret["success"].upper() == RouterHealthStatus.FAILED:
failingChecks.append(f)
monitResult[f] = ret

View File

@ -35,7 +35,7 @@
size="large">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<status class="status" :text="record.success === true ? 'True' : 'False'" displayText />
<status class="status" :text="record.status" displayText />
</template>
</template>
</a-table>
@ -113,6 +113,7 @@ export default {
},
{
key: 'status',
dataIndex: 'status',
title: this.$t('label.router.health.check.success')
},
{