diff --git a/opensync-ext-cloud/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/OpensyncExternalIntegrationCloud.java b/opensync-ext-cloud/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/OpensyncExternalIntegrationCloud.java index d429e97..13d8ea1 100644 --- a/opensync-ext-cloud/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/OpensyncExternalIntegrationCloud.java +++ b/opensync-ext-cloud/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/OpensyncExternalIntegrationCloud.java @@ -1,5 +1,6 @@ package com.telecominfraproject.wlan.opensync.external.integration; +import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; @@ -108,2039 +109,2082 @@ import wc.stats.IpDnsTelemetry.WCStatsReport; @Component public class OpensyncExternalIntegrationCloud implements OpensyncExternalIntegrationInterface { - private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); - - @Autowired - private CustomerServiceInterface customerServiceInterface; - @Autowired - private LocationServiceInterface locationServiceInterface; - @Autowired - private OvsdbSessionMapInterface ovsdbSessionMapInterface; - @Autowired - private EquipmentServiceInterface equipmentServiceInterface; - @Autowired - private RoutingServiceInterface routingServiceInterface; - @Autowired - private ProfileServiceInterface profileServiceInterface; - @Autowired - private StatusServiceInterface statusServiceInterface; - @Autowired - private ClientServiceInterface clientServiceInterface; - @Autowired - private FirmwareServiceInterface firmwareServiceInterface; - @Autowired - private OpensyncExternalIntegrationMqttMessageProcessor mqttMessageProcessor; - - @Autowired - private OpensyncCloudGatewayController gatewayController; - - @Value("${tip.wlan.ovsdb.autoProvisionedCustomerId:1970}") - private int autoProvisionedCustomerId; - @Value("${tip.wlan.ovsdb.autoProvisionedLocationId:8}") - private int autoProvisionedLocationId; - @Value("${tip.wlan.ovsdb.autoProvisionedProfileId:1}") - private int autoProvisionedProfileId; - @Value("${tip.wlan.ovsdb.autoProvisionedSsid:DefaultSsid-}") - private String autoProvisionedSsid; - @Value("${tip.wlan.ovsdb.autoprovisionedSsidKey:12345678}") - private String autoprovisionedSsidKey; - @Value("${tip.wlan.ovsdb.isAutoconfigEnabled:true}") - private boolean isAutoconfigEnabled; - @Value("${tip.wlan.ovsdb.defaultFwVersion:r10947-65030d81f3}") - private String defaultFwVersion; - - @Autowired - private CacheManager cacheManagerShortLived; - private Cache cloudEquipmentRecordCache; - - @PostConstruct - private void postCreate() { - LOG.info("Using Cloud integration"); - cloudEquipmentRecordCache = cacheManagerShortLived.getCache("equipment_record_cache"); - } - - public Equipment getCustomerEquipment(String apId) { - Equipment ce = null; - - try { - ce = cloudEquipmentRecordCache.get(apId, () -> equipmentServiceInterface.getByInventoryIdOrNull(apId)); - } catch (Exception e) { - LOG.error("Could not get customer equipment for {}", apId, e); - } - - return ce; - } - - @Override - public void apConnected(String apId, ConnectNodeInfo connectNodeInfo) { - - Equipment ce = getCustomerEquipment(apId); - - try { - if (ce == null) { - - Customer customer = customerServiceInterface.getOrNull(autoProvisionedCustomerId); - if (customer == null) { - LOG.error("Cannot auto-provision equipment because customer with id {} is not found", - autoProvisionedCustomerId); - throw new IllegalStateException("Cannot auto-provision equipment because customer is not found : " - + autoProvisionedCustomerId); - } - - if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) - && !customer.getDetails().getAutoProvisioning().isEnabled()) { - LOG.error( - "Cannot auto-provision equipment because customer with id {} explicitly turned that feature off", - autoProvisionedCustomerId); - throw new IllegalStateException( - "Cannot auto-provision equipment because customer explicitly turned that feature off : " - + autoProvisionedCustomerId); - } - - // String dbUrlString = - // customer.getDetails().getClientFingerPrintsDbUrl(); - ce = new Equipment(); - ce.setEquipmentType(EquipmentType.AP); - ce.setInventoryId(apId); - try { - ce.setBaseMacAddress(new MacAddress(connectNodeInfo.macAddress)); - } catch (RuntimeException e) { - LOG.warn("Auto-provisioning: cannot parse equipment mac address {}", connectNodeInfo.macAddress); - } - - long locationId = autoProvisionedLocationId; - if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) - && customer.getDetails().getAutoProvisioning().isEnabled()) { - locationId = customer.getDetails().getAutoProvisioning().getLocationId(); - } - - try { - Location location = locationServiceInterface.get(locationId); - ce.setLocationId(location.getId()); - } catch (Exception e) { - LOG.error("Cannot auto-provision equipment because customer location with id {} cannot be found", - locationId); - throw new IllegalStateException( - "Cannot auto-provision equipment because customer location cannot be found : " - + locationId); - - } - - ce.setSerial(connectNodeInfo.serialNumber); - ce.setDetails(ApElementConfiguration.createWithDefaults()); - ce.setCustomerId(autoProvisionedCustomerId); - ce.setName(apId); - - ApElementConfiguration apElementConfig = (ApElementConfiguration) ce.getDetails(); - apElementConfig.setDeviceName(ce.getName()); - apElementConfig.setEquipmentModel(connectNodeInfo.model); - Map advancedRadioMap = new HashMap<>(); - Map radioMap = new HashMap<>(); - for (String radio : connectNodeInfo.wifiRadioStates.keySet()) { - RadioConfiguration advancedRadioConfiguration = null; - ElementRadioConfiguration radioConfiguration = null; - RadioType radioType = RadioType.UNSUPPORTED; - if (radio.equals("2.4G")) { - radioType = RadioType.is2dot4GHz; - } else if (radio.equals("5G")) { - radioType = RadioType.is5GHz; - } else if (radio.equals("5GL")) { - radioType = RadioType.is5GHzL; - } else if (radio.equals("5GU")) { - radioType = RadioType.is5GHzU; - } - if (!radioType.equals(RadioType.UNSUPPORTED)) { - advancedRadioConfiguration = RadioConfiguration.createWithDefaults(radioType); - - advancedRadioMap.put(radioType, advancedRadioConfiguration); - radioConfiguration = ElementRadioConfiguration.createWithDefaults(radioType); - radioMap.put(radioType, radioConfiguration); - } - } - - apElementConfig.setRadioMap(radioMap); - apElementConfig.setAdvancedRadioMap(advancedRadioMap); - - ce.setDetails(apElementConfig); - - Long profileId = null; - if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) - && customer.getDetails().getAutoProvisioning().isEnabled() - && (customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() != null)) { - - // try to find auto-provisioning profile for the current - // equipment model - profileId = customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() - .get(ce.getDetails().getEquipmentModel()); - if (profileId == null) { - // could not find profile for the equipment model, - // lets try to find a default profile - profileId = customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() - .get(EquipmentAutoProvisioningSettings.DEFAULT_MODEL_NAME); - } - } - - if (profileId == null) { - // create default apProfile if cannot find applicable - // one: - Profile apProfile = createDefaultApProfile(ce, connectNodeInfo); - profileId = apProfile.getId(); - } - - ce.setProfileId(profileId); - - ce = equipmentServiceInterface.create(ce); - - // update the cache right away, no need to wait until the - // entry expires - cloudEquipmentRecordCache.put(ce.getInventoryId(), ce); - - } else { - // equipment already exists - - MacAddress reportedMacAddress = null; - try { - reportedMacAddress = new MacAddress(connectNodeInfo.macAddress); - } catch (RuntimeException e) { - LOG.warn("AP connect: cannot parse equipment mac address {}", connectNodeInfo.macAddress); - } - - if (reportedMacAddress != null) { - // check if reported mac address matches what is in the - // db - if (!reportedMacAddress.equals(ce.getBaseMacAddress())) { - // need to update base mac address on equipment in - // DB - ce = equipmentServiceInterface.get(ce.getId()); - ce.setBaseMacAddress(reportedMacAddress); - ce = equipmentServiceInterface.update(ce); - - // update the cache right away, no need to wait - // until the entry expires - cloudEquipmentRecordCache.put(ce.getInventoryId(), ce); - } - } - - } - - EquipmentRoutingRecord equipmentRoutingRecord = gatewayController.registerCustomerEquipment(ce.getName(), - ce.getCustomerId(), ce.getId()); - - updateApStatus(ce, connectNodeInfo); - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - ovsdbSession.setRoutingId(equipmentRoutingRecord.getId()); - ovsdbSession.setEquipmentId(ce.getId()); - ovsdbSession.setCustomerId(ce.getCustomerId()); - - LOG.debug("Equipment {}", ce); - LOG.info("AP {} got connected to the gateway", apId); - LOG.info("ConnectNodeInfo {}", connectNodeInfo); - - if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { - reconcileFwVersionToTrack(ce, - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY), - connectNodeInfo.model); - } else { - LOG.info("Cloud based firmware upgrade is not supported for this AP"); - } - - } catch (Exception e) { - LOG.error("Could not process connection from AP {}", apId, e); - throw e; - } - - } - - private Profile createDefaultApProfile(Equipment ce, ConnectNodeInfo connectNodeInfo) { - Profile apProfile = new Profile(); - apProfile.setCustomerId(ce.getCustomerId()); - apProfile.setName("DefaultApProfile for " + ce.getName()); - apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); - apProfile = profileServiceInterface.create(apProfile); - - ApNetworkConfiguration apNetworkConfig = (ApNetworkConfiguration) apProfile.getDetails(); - Map radioProfileMap = new HashMap<>(); - - for (String radioBand : connectNodeInfo.wifiRadioStates.keySet()) { - - RadioType radioType = OvsdbToWlanCloudTypeMappingUtility.getRadioTypeForOvsdbRadioFreqBand(radioBand); - if (!radioType.equals(RadioType.UNSUPPORTED)) { - radioProfileMap.put(radioType, RadioProfileConfiguration.createWithDefaults(radioType)); - } - - } - - apNetworkConfig.setRadioMap(radioProfileMap); - - apProfile.setDetails(apNetworkConfig); - - apProfile = profileServiceInterface.update(apProfile); - - apNetworkConfig = (ApNetworkConfiguration) apProfile.getDetails(); - - Set radioTypes = radioProfileMap.keySet(); - - for (RadioType radioType : radioTypes) { - // SSID Profile init - Profile ssidProfile = new Profile(); - ssidProfile.setCustomerId(ce.getCustomerId()); - ssidProfile.setName(autoProvisionedSsid + radioType.name() + " for " + ce.getName()); - SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); - - ssidConfig.setSsid(ssidProfile.getName()); - ssidConfig.setSsidAdminState(StateSetting.enabled); - ssidConfig.setBroadcastSsid(StateSetting.enabled); - ssidConfig.setSecureMode(SecureMode.wpa2PSK); - ssidConfig.setKeyStr(autoprovisionedSsidKey); - - Set appliedRadios = new HashSet<>(); - appliedRadios.add(radioType); - ssidConfig.setAppliedRadios(appliedRadios); - ssidProfile.setDetails(ssidConfig); - ssidProfile = profileServiceInterface.create(ssidProfile); - - apProfile.getChildProfileIds().add(ssidProfile.getId()); - } - - // RF Profile Init - Profile rfProfile = new Profile(); - rfProfile.setCustomerId(ce.getCustomerId()); - rfProfile.setName("DefaultRf for " + ce.getName()); - RfConfiguration rfConfig = RfConfiguration.createWithDefaults(); - - // Override default values - for (RadioType radioType : radioTypes) { - rfConfig.getRfConfig(radioType).setRf(rfProfile.getName()); - } - - rfProfile.setDetails(rfConfig); - rfProfile = profileServiceInterface.create(rfProfile); - - apProfile.getChildProfileIds().add(rfProfile.getId()); - - // Update AP profile with SSID and RF child profiles - apProfile = profileServiceInterface.update(apProfile); - - return apProfile; - } - - private void updateApStatus(Equipment ce, ConnectNodeInfo connectNodeInfo) { - - try { - - Status statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), - StatusDataType.EQUIPMENT_ADMIN); - if (statusRecord == null) { - statusRecord = new Status(); - statusRecord.setCustomerId(ce.getCustomerId()); - statusRecord.setEquipmentId(ce.getId()); - EquipmentAdminStatusData statusData = new EquipmentAdminStatusData(); - statusRecord.setDetails(statusData); - } - - ((EquipmentAdminStatusData) statusRecord.getDetails()).setStatusCode(StatusCode.normal); - // Update the equipment admin status - statusRecord = statusServiceInterface.update(statusRecord); - - // update LAN status - nothing to do here for now - statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.LANINFO); - if (statusRecord == null) { - statusRecord = new Status(); - statusRecord.setCustomerId(ce.getCustomerId()); - statusRecord.setEquipmentId(ce.getId()); - - EquipmentLANStatusData statusData = new EquipmentLANStatusData(); - statusRecord.setDetails(statusData); - } - - Map vlanStatusDataMap = new HashMap<>(); - ((EquipmentLANStatusData) statusRecord.getDetails()).setVlanStatusDataMap(vlanStatusDataMap); - - statusServiceInterface.update(statusRecord); - - // update protocol status - statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.PROTOCOL); - if (statusRecord == null) { - statusRecord = new Status(); - statusRecord.setCustomerId(ce.getCustomerId()); - statusRecord.setEquipmentId(ce.getId()); - - EquipmentProtocolStatusData statusData = new EquipmentProtocolStatusData(); - statusRecord.setDetails(statusData); - } - - EquipmentProtocolStatusData protocolStatusData = (EquipmentProtocolStatusData) statusRecord.getDetails(); - protocolStatusData.setPoweredOn(true); - protocolStatusData.setCloudProtocolVersion("1100"); - protocolStatusData.setProtocolState(EquipmentProtocolState.ready); - protocolStatusData.setBandPlan("FCC"); - protocolStatusData.setBaseMacAddress(MacAddress.valueOf(connectNodeInfo.macAddress)); - protocolStatusData.setCloudCfgDataVersion(42L); - protocolStatusData.setReportedCfgDataVersion(42L); - protocolStatusData.setCountryCode("CA"); - protocolStatusData.setReportedCC(CountryCode.ca); - protocolStatusData.setReportedHwVersion(connectNodeInfo.platformVersion); - if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { - protocolStatusData.setReportedSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)); - } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { - protocolStatusData.setReportedSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); - } else { - protocolStatusData.setReportedSwVersion("Unknown"); - } - if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { - protocolStatusData.setReportedSwAltVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)); - } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { - protocolStatusData.setReportedSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); - } else { - protocolStatusData.setReportedSwVersion("Unknown"); - } - try { - protocolStatusData.setReportedIpV4Addr(InetAddress.getByName(connectNodeInfo.ipV4Address)); - } catch (UnknownHostException e) { - // do nothing here - } - if ((connectNodeInfo.macAddress != null) && (MacAddress.valueOf(connectNodeInfo.macAddress) != null)) { - protocolStatusData.setReportedMacAddr(MacAddress.valueOf(connectNodeInfo.macAddress)); - } - protocolStatusData.setReportedSku(connectNodeInfo.skuNumber); - protocolStatusData.setSerialNumber(connectNodeInfo.serialNumber); - protocolStatusData.setSystemName(connectNodeInfo.model); - statusRecord.setDetails(protocolStatusData); - statusServiceInterface.update(statusRecord); - - statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.FIRMWARE); - if (statusRecord == null) { - statusRecord = new Status(); - statusRecord.setCustomerId(ce.getCustomerId()); - statusRecord.setEquipmentId(ce.getId()); - EquipmentUpgradeStatusData statusData = new EquipmentUpgradeStatusData(); - statusRecord.setDetails(statusData); - } - - EquipmentUpgradeStatusData fwUpgradeStatusData = (EquipmentUpgradeStatusData) statusRecord.getDetails(); - if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { - fwUpgradeStatusData.setActiveSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)); - } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { - fwUpgradeStatusData - .setActiveSwVersion(connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); - } else { - fwUpgradeStatusData.setActiveSwVersion("Unknown"); - } - if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { - fwUpgradeStatusData.setAlternateSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)); - } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { - fwUpgradeStatusData.setAlternateSwVersion( - connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); - } else { - fwUpgradeStatusData.setAlternateSwVersion("Unknown"); - } - - if (fwUpgradeStatusData.getUpgradeState() == null) { - fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.undefined); - fwUpgradeStatusData.setUpgradeStartTime(null); - - } - - statusRecord.setDetails(fwUpgradeStatusData); - statusServiceInterface.update(statusRecord); - - Status networkAdminStatusRec = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), - StatusDataType.NETWORK_ADMIN); - if (networkAdminStatusRec == null) { - networkAdminStatusRec = new Status(); - networkAdminStatusRec.setCustomerId(ce.getCustomerId()); - networkAdminStatusRec.setEquipmentId(ce.getId()); - NetworkAdminStatusData statusData = new NetworkAdminStatusData(); - networkAdminStatusRec.setDetails(statusData); - } - - NetworkAdminStatusData netAdminStatusData = (NetworkAdminStatusData) networkAdminStatusRec.getDetails(); - netAdminStatusData.setDhcpStatus(StatusCode.normal); - netAdminStatusData.setCloudLinkStatus(StatusCode.normal); - netAdminStatusData.setDnsStatus(StatusCode.normal); - - networkAdminStatusRec.setDetails(netAdminStatusData); - - networkAdminStatusRec = statusServiceInterface.update(networkAdminStatusRec); - - } catch (Exception e) { - LOG.debug("Exception in updateApStatus", e); - } - - } - - private void reconcileFwVersionToTrack(Equipment ce, String reportedFwVersionFromAp, String model) { - - LOG.debug("reconcileFwVersionToTrack for AP {} with active firmware version {} model {}", ce.getInventoryId(), - reportedFwVersionFromAp, model); - Status statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.FIRMWARE); - - EquipmentUpgradeStatusData fwUpgradeStatusData = (EquipmentUpgradeStatusData) statusRecord.getDetails(); - - // default track settings for firmware - CustomerFirmwareTrackSettings trackSettings = firmwareServiceInterface.getDefaultCustomerTrackSetting(); - - // check for updated/modified track settings for this customer - CustomerFirmwareTrackRecord custFwTrackRecord = firmwareServiceInterface - .getCustomerFirmwareTrackRecord(ce.getCustomerId()); - - long trackRecordId = -1; - if (custFwTrackRecord != null) { - trackSettings = custFwTrackRecord.getSettings(); - trackRecordId = custFwTrackRecord.getTrackRecordId(); - } - // determine if AP requires FW upgrade before cloud - // connection/provision - if (trackSettings.getAutoUpgradeDeprecatedOnBind().equals(TrackFlag.ALWAYS) - || trackSettings.getAutoUpgradeUnknownOnBind().equals(TrackFlag.ALWAYS)) { - - LOG.debug("reconcileFwVersionToTrack for AP {} track flag for auto-upgrade {}", ce.getInventoryId(), - trackSettings.getAutoUpgradeDeprecatedOnBind()); - - // check the reported fw version for the AP, if it is < than - // the default version for the cloud, then download and - // flash the firmware before proceeding. - // then return; - FirmwareTrackRecord fwTrackRecord = null; - if (trackRecordId == -1) { - // take the default - fwTrackRecord = firmwareServiceInterface.getFirmwareTrackByName(FirmwareTrackRecord.DEFAULT_TRACK_NAME); - - } else { - // there must be a customer one - fwTrackRecord = firmwareServiceInterface.getFirmwareTrackById(trackRecordId); - } - - if (fwTrackRecord != null) { - - LOG.debug("reconcileFwVersionToTrack for AP {} firmwareTrackRecord {}", ce.getInventoryId(), - fwTrackRecord); - - List fwTrackAssignmentDetails = firmwareServiceInterface - .getFirmwareTrackAssignments(fwTrackRecord.getTrackName()); - - String targetFwVersionNameForTrack = null; - - if (fwTrackAssignmentDetails != null) { - for (FirmwareTrackAssignmentDetails details : fwTrackAssignmentDetails) { - if (model.equalsIgnoreCase(details.getModelId())) { - targetFwVersionNameForTrack = details.getVersionName(); - break; - } - } - } - - if (targetFwVersionNameForTrack == null) { - LOG.info("No target FW version for this track {}", fwTrackRecord); - - } else { - LOG.debug("reconcileFwVersionToTrack for AP {} targetFwVersion for track {}", ce.getInventoryId(), - targetFwVersionNameForTrack); - - if (reportedFwVersionFromAp != null) { - if (!targetFwVersionNameForTrack.equals(reportedFwVersionFromAp)) { - LOG.debug( - "reconcileFwVersionToTrack for AP {} targetFwVersion {} doesn't match reported fw version {}, triggering download and flash", - ce.getInventoryId(), targetFwVersionNameForTrack, reportedFwVersionFromAp); - - fwUpgradeStatusData.setTargetSwVersion(targetFwVersionNameForTrack); - fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.out_of_date); - statusRecord.setDetails(fwUpgradeStatusData); - statusRecord = statusServiceInterface.update(statusRecord); - triggerFwDownload(ce, fwUpgradeStatusData, trackSettings); - } else if (targetFwVersionNameForTrack.equals(reportedFwVersionFromAp)) { - LOG.debug("reconcileFwVersionToTrack for AP {} targetFwVersion {} is active", - ce.getInventoryId(), targetFwVersionNameForTrack); - - fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.up_to_date); - fwUpgradeStatusData.setActiveSwVersion(targetFwVersionNameForTrack); - fwUpgradeStatusData.setAlternateSwVersion(targetFwVersionNameForTrack); - fwUpgradeStatusData.setTargetSwVersion(targetFwVersionNameForTrack); - - statusRecord.setDetails(fwUpgradeStatusData); - statusRecord = statusServiceInterface.update(statusRecord); - - } - } - - } - - } - - } else - - { - LOG.debug("Automatic firmware upgrade is not configured for track {}", trackSettings); - } - } - - private void triggerFwDownload(Equipment ce, EquipmentUpgradeStatusData fwUpgradeStatusData, - CustomerFirmwareTrackSettings trackSettings) { - LOG.debug("triggerFwDownloadAndFlash Automatic firmware upgrade is configured for track {}.", trackSettings); - - try { - FirmwareVersion fwVersion = firmwareServiceInterface - .getFirmwareVersionByName(fwUpgradeStatusData.getTargetSwVersion()); - - if (fwVersion != null) { - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(ce.getInventoryId()); - if (ovsdbSession == null) { - throw new IllegalStateException("AP is not connected " + ce.getInventoryId()); - } - - CEGWFirmwareDownloadRequest fwDownloadRequest = new CEGWFirmwareDownloadRequest(ce.getInventoryId(), - ce.getId(), fwVersion.getVersionName(), fwVersion.getFilename(), - fwVersion.getValidationMethod(), fwVersion.getValidationCode()); - List commands = new ArrayList<>(); - commands.add(fwDownloadRequest); - - gatewayController.updateActiveCustomer(ce.getCustomerId()); - ListOfEquipmentCommandResponses responses = gatewayController.sendCommands(commands); - LOG.debug("FW Download Response {}", responses); - - } - } catch (Exception e) { - LOG.error("Cannot trigger FW download {}", e); - } - } - - @Override - public void apDisconnected(String apId) { - LOG.info("AP {} got disconnected from the gateway", apId); - try { - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession != null) { - // if (ovsdbSession.getCustomerId() > 0 && - // ovsdbSession.getEquipmentId() > 0L) { - // List statusForDisconnectedAp = - // statusServiceInterface.delete(ovsdbSession.getCustomerId(), - // ovsdbSession.getEquipmentId()); - // LOG.info("Deleted status records {} for AP {}", - // statusForDisconnectedAp, apId); - // } - if (ovsdbSession.getRoutingId() > 0L) { - try { - routingServiceInterface.delete(ovsdbSession.getRoutingId()); - } catch (Exception e) { - LOG.warn("Unable to delete routing service Id {} for ap {}. {}", ovsdbSession.getRoutingId(), - apId, e); - } - } - } else { - LOG.warn("Cannot find ap {} in inventory", apId); - } - } catch (Exception e) { - LOG.error("Exception when registering ap routing {}", apId, e); - } - - } - - @Override - public OpensyncAPConfig getApConfig(String apId) { - LOG.info("Retrieving config for AP {} ", apId); - OpensyncAPConfig ret = null; - - try { - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession == null) { - throw new IllegalStateException("AP is not connected " + apId); - } - int customerId = ovsdbSession.getCustomerId(); - Customer customer = customerServiceInterface.getOrNull(customerId); - if ((customer != null) && (customer.getDetails() != null) - && (customer.getDetails().getAutoProvisioning() != null) - && customer.getDetails().getAutoProvisioning().isEnabled()) { - Equipment equipmentConfig = getCustomerEquipment(apId); - - if (equipmentConfig == null) { - throw new IllegalStateException("Cannot retrieve configuration for " + apId); - } - - ret = new OpensyncAPConfig(); - - ret.setCustomerEquipment(equipmentConfig); - - Location eqLocation = locationServiceInterface.get(equipmentConfig.getLocationId()); - - ret.setEquipmentLocation(eqLocation); - - ProfileContainer profileContainer = new ProfileContainer( - profileServiceInterface.getProfileWithChildren(equipmentConfig.getProfileId())); - - ret.setApProfile(profileContainer.getOrNull(equipmentConfig.getProfileId())); - - ret.setRfProfile(profileContainer.getChildOfTypeOrNull(equipmentConfig.getProfileId(), ProfileType.rf)); - - ret.setSsidProfile( - profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.ssid)); - - ret.setMetricsProfiles( - profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.metrics)); - - Set radiusSet = new HashSet<>(); - Set captiveProfileIds = new HashSet<>(); - Set bonjourGatewayProfileIds = new HashSet<>(); - - OpensyncAPHotspot20Config hotspotConfig = new OpensyncAPHotspot20Config(); - - Set hotspot20ProfileSet = new HashSet<>(); - Set hotspot20OperatorSet = new HashSet<>(); - Set hotspot20VenueSet = new HashSet<>(); - Set hotspot20ProviderSet = new HashSet<>(); - - for (Profile ssidProfile : ret.getSsidProfile()) { - - hotspot20ProfileSet - .addAll(profileContainer.getChildrenOfType(ssidProfile.getId(), ProfileType.hotspot_2pt0)); - - radiusSet - .addAll(profileContainer.getChildrenOfType(ret.getApProfile().getId(), ProfileType.radius)); - if (ssidProfile.getDetails() != null) { - Long captivePortId = ((SsidConfiguration) ssidProfile.getDetails()).getCaptivePortalId(); - if (captivePortId != null) { - captiveProfileIds.add(captivePortId); - } - Long bonjourGatewayProfileId = ((SsidConfiguration) ssidProfile.getDetails()) - .getBonjourGatewayProfileId(); - if (bonjourGatewayProfileId != null) { - bonjourGatewayProfileIds.add(bonjourGatewayProfileId); - } - } - } - - if (hotspot20ProfileSet.size() > 0) { - for (Profile hotspot20Profile : hotspot20ProfileSet) { - hotspot20OperatorSet.addAll( - profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.operator)); - hotspot20VenueSet.addAll( - profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.venue)); - hotspot20ProviderSet.addAll( - profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.id_provider)); - } - hotspotConfig.setHotspot20OperatorSet(hotspot20OperatorSet); - hotspotConfig.setHotspot20ProfileSet(hotspot20ProfileSet); - hotspotConfig.setHotspot20ProviderSet(hotspot20ProviderSet); - hotspotConfig.setHotspot20VenueSet(hotspot20VenueSet); - - ret.setHotspotConfig(hotspotConfig); - } - - ret.setRadiusProfiles(new ArrayList<>(radiusSet)); - ret.setCaptiveProfiles(profileServiceInterface.get(captiveProfileIds)); - ret.setBonjourGatewayProfiles(profileServiceInterface.get(bonjourGatewayProfileIds)); - - List blockedClients = clientServiceInterface - .getBlockedClients(customerId); - List blockList = Lists.newArrayList(); - if ((blockedClients != null) && !blockedClients.isEmpty()) { - blockedClients.forEach(client -> blockList.add(client.getMacAddress())); - } - ret.setBlockedClients(blockList); - - LOG.debug("ApConfig {}", ret); - } else { - LOG.info("Autoconfig is not enabled for this AP {}", apId); - } - - } catch (Exception e) { - LOG.error("Cannot read config for AP {}", apId, e); - } - - return ret; - } - - @Override - public void processMqttMessage(String topic, Report report) { - mqttMessageProcessor.processMqttMessage(topic, report); - } - - @Override - public void processMqttMessage(String topic, FlowReport flowReport) { - mqttMessageProcessor.processMqttMessage(topic, flowReport); - } - - @Override - public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { - mqttMessageProcessor.processMqttMessage(topic, wcStatsReport); - } - - @Override - public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { - LOG.debug("Received Wifi_VIF_State table update for AP {}", apId); - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession == null) { - LOG.debug("wifiVIFStateDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } - - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); - - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiVIFStateDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } - - Equipment apNode = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (apNode == null) { - LOG.debug("wifiVIFStateDbTableUpdate::Cannot get EquipmentId for AP {}", apId); - return; // we don't have the required info to get the - // radio type yet - } - ApElementConfiguration apElementConfig = (ApElementConfiguration) apNode.getDetails(); - - ProfileContainer profileContainer = new ProfileContainer( - profileServiceInterface.getProfileWithChildren(apNode.getProfileId())); - RfConfiguration rfConfig = (RfConfiguration) profileContainer - .getChildOfTypeOrNull(apNode.getProfileId(), ProfileType.rf).getDetails(); - - for (OpensyncAPVIFState vifState : vifStateTables) { - - LOG.debug("Processing vifState for interface {} on AP {}", vifState.getIfName(), apId); - - String bssid = vifState.getMac(); - - if ((bssid == null) || bssid.equals("")) { - LOG.warn("BSSID from AP {} for vif {} is null or empty", apId, vifState.getIfName()); - continue; - } - String ssid = vifState.getSsid(); - - if ((ssid == null) || ssid.equals("")) { - LOG.warn("SSID from AP {} interface {} is null or empty", apId, vifState.getIfName()); - continue; - } - - int numClients = vifState.getAssociatedClients().size(); - - int channel = vifState.getChannel(); - - if ((channel < 1)) { - LOG.warn("Channel from AP {} interface {} is null or empty", apId, vifState.getIfName()); - continue; - } - - LOG.debug("Values from Vif State Mac (BSSID) {} SSID {} AssociatedClients {} Channel {}", bssid, ssid, - vifState.getAssociatedClients()); - - RadioType radioType = null; - Map rfElementMap = rfConfig.getRfConfigMap(); - Map elementRadioMap = apElementConfig.getRadioMap(); - for (RadioType rType : elementRadioMap.keySet()) { - boolean autoChannelSelection = rfElementMap.get(rType).getAutoChannelSelection(); - if (elementRadioMap.get(rType).getActiveChannel(autoChannelSelection) == channel) { - radioType = rType; - break; - } - } + private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); + + @Autowired + private CustomerServiceInterface customerServiceInterface; + @Autowired + private LocationServiceInterface locationServiceInterface; + @Autowired + private OvsdbSessionMapInterface ovsdbSessionMapInterface; + @Autowired + private EquipmentServiceInterface equipmentServiceInterface; + @Autowired + private RoutingServiceInterface routingServiceInterface; + @Autowired + private ProfileServiceInterface profileServiceInterface; + @Autowired + private StatusServiceInterface statusServiceInterface; + @Autowired + private ClientServiceInterface clientServiceInterface; + @Autowired + private FirmwareServiceInterface firmwareServiceInterface; + @Autowired + private OpensyncExternalIntegrationMqttMessageProcessor mqttMessageProcessor; + + @Autowired + private OpensyncCloudGatewayController gatewayController; + + @Value("${tip.wlan.ovsdb.autoProvisionedCustomerId:1970}") + private int autoProvisionedCustomerId; + @Value("${tip.wlan.ovsdb.autoProvisionedLocationId:8}") + private int autoProvisionedLocationId; + @Value("${tip.wlan.ovsdb.autoProvisionedProfileId:1}") + private int autoProvisionedProfileId; + @Value("${tip.wlan.ovsdb.autoProvisionedSsid:DefaultSsid-}") + private String autoProvisionedSsid; + @Value("${tip.wlan.ovsdb.autoprovisionedSsidKey:12345678}") + private String autoprovisionedSsidKey; + @Value("${tip.wlan.ovsdb.isAutoconfigEnabled:true}") + private boolean isAutoconfigEnabled; + @Value("${tip.wlan.ovsdb.defaultFwVersion:r10947-65030d81f3}") + private String defaultFwVersion; + @org.springframework.beans.factory.annotation.Value("${tip.wlan.ovsdb.wifi-iface.default_lan_type:bridge}") + public String defaultLanInterfaceType; + @org.springframework.beans.factory.annotation.Value("${tip.wlan.ovsdb.wifi-iface.default_lan_name:lan}") + public String defaultLanInterfaceName; + @org.springframework.beans.factory.annotation.Value("${tip.wlan.ovsdb.wifi-iface.default_wan_type:bridge}") + public String defaultWanInterfaceType; + @org.springframework.beans.factory.annotation.Value("${tip.wlan.ovsdb.wifi-iface.default_wan_name:wan}") + public String defaultWanInterfaceName; + + @Autowired + private CacheManager cacheManagerShortLived; + private Cache cloudEquipmentRecordCache; + + @PostConstruct + private void postCreate() { + LOG.info("Using Cloud integration"); + cloudEquipmentRecordCache = cacheManagerShortLived.getCache("equipment_record_cache"); + } + + public Equipment getCustomerEquipment(String apId) { + Equipment ce = null; + + try { + ce = cloudEquipmentRecordCache.get(apId, () -> equipmentServiceInterface.getByInventoryIdOrNull(apId)); + } catch (Exception e) { + LOG.error("Could not get customer equipment for {}", apId, e); + } + + return ce; + } + + @Override + public void apConnected(String apId, ConnectNodeInfo connectNodeInfo) { + + Equipment ce = getCustomerEquipment(apId); + + try { + if (ce == null) { + + Customer customer = customerServiceInterface.getOrNull(autoProvisionedCustomerId); + if (customer == null) { + LOG.error("Cannot auto-provision equipment because customer with id {} is not found", + autoProvisionedCustomerId); + throw new IllegalStateException("Cannot auto-provision equipment because customer is not found : " + + autoProvisionedCustomerId); + } + + if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) + && !customer.getDetails().getAutoProvisioning().isEnabled()) { + LOG.error( + "Cannot auto-provision equipment because customer with id {} explicitly turned that feature off", + autoProvisionedCustomerId); + throw new IllegalStateException( + "Cannot auto-provision equipment because customer explicitly turned that feature off : " + + autoProvisionedCustomerId); + } + + // String dbUrlString = + // customer.getDetails().getClientFingerPrintsDbUrl(); + ce = new Equipment(); + ce.setEquipmentType(EquipmentType.AP); + ce.setInventoryId(apId); + try { + ce.setBaseMacAddress(new MacAddress(connectNodeInfo.macAddress)); + } catch (RuntimeException e) { + LOG.warn("Auto-provisioning: cannot parse equipment mac address {}", connectNodeInfo.macAddress); + } + + long locationId = autoProvisionedLocationId; + if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) + && customer.getDetails().getAutoProvisioning().isEnabled()) { + locationId = customer.getDetails().getAutoProvisioning().getLocationId(); + } + + try { + Location location = locationServiceInterface.get(locationId); + ce.setLocationId(location.getId()); + } catch (Exception e) { + LOG.error("Cannot auto-provision equipment because customer location with id {} cannot be found", + locationId); + throw new IllegalStateException( + "Cannot auto-provision equipment because customer location cannot be found : " + + locationId); + + } + + ce.setSerial(connectNodeInfo.serialNumber); + ce.setDetails(ApElementConfiguration.createWithDefaults()); + ce.setCustomerId(autoProvisionedCustomerId); + ce.setName(apId); + + ApElementConfiguration apElementConfig = (ApElementConfiguration) ce.getDetails(); + apElementConfig.setDeviceName(ce.getName()); + apElementConfig.setEquipmentModel(connectNodeInfo.model); + Map advancedRadioMap = new HashMap<>(); + Map radioMap = new HashMap<>(); + for (String radio : connectNodeInfo.wifiRadioStates.keySet()) { + RadioConfiguration advancedRadioConfiguration = null; + ElementRadioConfiguration radioConfiguration = null; + RadioType radioType = RadioType.UNSUPPORTED; + if (radio.equals("2.4G")) { + radioType = RadioType.is2dot4GHz; + } else if (radio.equals("5G")) { + radioType = RadioType.is5GHz; + } else if (radio.equals("5GL")) { + radioType = RadioType.is5GHzL; + } else if (radio.equals("5GU")) { + radioType = RadioType.is5GHzU; + } + if (!radioType.equals(RadioType.UNSUPPORTED)) { + advancedRadioConfiguration = RadioConfiguration.createWithDefaults(radioType); + + advancedRadioMap.put(radioType, advancedRadioConfiguration); + radioConfiguration = ElementRadioConfiguration.createWithDefaults(radioType); + radioMap.put(radioType, radioConfiguration); + } + } + + apElementConfig.setRadioMap(radioMap); + apElementConfig.setAdvancedRadioMap(advancedRadioMap); + + ce.setDetails(apElementConfig); + + Long profileId = null; + if ((customer.getDetails() != null) && (customer.getDetails().getAutoProvisioning() != null) + && customer.getDetails().getAutoProvisioning().isEnabled() + && (customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() != null)) { + + // try to find auto-provisioning profile for the current + // equipment model + profileId = customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() + .get(ce.getDetails().getEquipmentModel()); + if (profileId == null) { + // could not find profile for the equipment model, + // lets try to find a default profile + profileId = customer.getDetails().getAutoProvisioning().getEquipmentProfileIdPerModel() + .get(EquipmentAutoProvisioningSettings.DEFAULT_MODEL_NAME); + } + } + + if (profileId == null) { + // create default apProfile if cannot find applicable + // one: + Profile apProfile = createDefaultApProfile(ce, connectNodeInfo); + profileId = apProfile.getId(); + } + + ce.setProfileId(profileId); + + ce = equipmentServiceInterface.create(ce); + + // update the cache right away, no need to wait until the + // entry expires + cloudEquipmentRecordCache.put(ce.getInventoryId(), ce); + + } else { + // equipment already exists + + MacAddress reportedMacAddress = null; + try { + reportedMacAddress = new MacAddress(connectNodeInfo.macAddress); + } catch (RuntimeException e) { + LOG.warn("AP connect: cannot parse equipment mac address {}", connectNodeInfo.macAddress); + } + + if (reportedMacAddress != null) { + // check if reported mac address matches what is in the + // db + if (!reportedMacAddress.equals(ce.getBaseMacAddress())) { + // need to update base mac address on equipment in + // DB + ce = equipmentServiceInterface.get(ce.getId()); + ce.setBaseMacAddress(reportedMacAddress); + ce = equipmentServiceInterface.update(ce); + + // update the cache right away, no need to wait + // until the entry expires + cloudEquipmentRecordCache.put(ce.getInventoryId(), ce); + } + } + + } + + EquipmentRoutingRecord equipmentRoutingRecord = gatewayController.registerCustomerEquipment(ce.getName(), + ce.getCustomerId(), ce.getId()); + + updateApStatus(ce, connectNodeInfo); + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + ovsdbSession.setRoutingId(equipmentRoutingRecord.getId()); + ovsdbSession.setEquipmentId(ce.getId()); + ovsdbSession.setCustomerId(ce.getCustomerId()); + + LOG.debug("Equipment {}", ce); + LOG.info("AP {} got connected to the gateway", apId); + LOG.info("ConnectNodeInfo {}", connectNodeInfo); + + if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { + reconcileFwVersionToTrack(ce, + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY), + connectNodeInfo.model); + } else { + LOG.info("Cloud based firmware upgrade is not supported for this AP"); + } + + } catch (Exception e) { + LOG.error("Could not process connection from AP {}", apId, e); + throw e; + } + + } + + private Profile createDefaultApProfile(Equipment ce, ConnectNodeInfo connectNodeInfo) { + Profile apProfile = new Profile(); + apProfile.setCustomerId(ce.getCustomerId()); + apProfile.setName("DefaultApProfile for " + ce.getName()); + apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); + apProfile = profileServiceInterface.create(apProfile); + + ApNetworkConfiguration apNetworkConfig = (ApNetworkConfiguration) apProfile.getDetails(); + Map radioProfileMap = new HashMap<>(); + + for (String radioBand : connectNodeInfo.wifiRadioStates.keySet()) { + + RadioType radioType = OvsdbToWlanCloudTypeMappingUtility.getRadioTypeForOvsdbRadioFreqBand(radioBand); + if (!radioType.equals(RadioType.UNSUPPORTED)) { + radioProfileMap.put(radioType, RadioProfileConfiguration.createWithDefaults(radioType)); + } + + } + + apNetworkConfig.setRadioMap(radioProfileMap); + + apProfile.setDetails(apNetworkConfig); + + apProfile = profileServiceInterface.update(apProfile); + + apNetworkConfig = (ApNetworkConfiguration) apProfile.getDetails(); + + Set radioTypes = radioProfileMap.keySet(); + + for (RadioType radioType : radioTypes) { + // SSID Profile init + Profile ssidProfile = new Profile(); + ssidProfile.setCustomerId(ce.getCustomerId()); + ssidProfile.setName(autoProvisionedSsid + radioType.name() + " for " + ce.getName()); + SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); + + ssidConfig.setSsid(ssidProfile.getName()); + ssidConfig.setSsidAdminState(StateSetting.enabled); + ssidConfig.setBroadcastSsid(StateSetting.enabled); + ssidConfig.setSecureMode(SecureMode.wpa2PSK); + ssidConfig.setKeyStr(autoprovisionedSsidKey); + + Set appliedRadios = new HashSet<>(); + appliedRadios.add(radioType); + ssidConfig.setAppliedRadios(appliedRadios); + ssidProfile.setDetails(ssidConfig); + ssidProfile = profileServiceInterface.create(ssidProfile); + + apProfile.getChildProfileIds().add(ssidProfile.getId()); + } + + // RF Profile Init + Profile rfProfile = new Profile(); + rfProfile.setCustomerId(ce.getCustomerId()); + rfProfile.setName("DefaultRf for " + ce.getName()); + RfConfiguration rfConfig = RfConfiguration.createWithDefaults(); + + // Override default values + for (RadioType radioType : radioTypes) { + rfConfig.getRfConfig(radioType).setRf(rfProfile.getName()); + } + + rfProfile.setDetails(rfConfig); + rfProfile = profileServiceInterface.create(rfProfile); + + apProfile.getChildProfileIds().add(rfProfile.getId()); + + // Update AP profile with SSID and RF child profiles + apProfile = profileServiceInterface.update(apProfile); + + return apProfile; + } + + private void updateApStatus(Equipment ce, ConnectNodeInfo connectNodeInfo) { + + try { + + Status statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), + StatusDataType.EQUIPMENT_ADMIN); + if (statusRecord == null) { + statusRecord = new Status(); + statusRecord.setCustomerId(ce.getCustomerId()); + statusRecord.setEquipmentId(ce.getId()); + EquipmentAdminStatusData statusData = new EquipmentAdminStatusData(); + statusRecord.setDetails(statusData); + } + + ((EquipmentAdminStatusData) statusRecord.getDetails()).setStatusCode(StatusCode.normal); + // Update the equipment admin status + statusRecord = statusServiceInterface.update(statusRecord); + + // update LAN status - nothing to do here for now + statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.LANINFO); + if (statusRecord == null) { + statusRecord = new Status(); + statusRecord.setCustomerId(ce.getCustomerId()); + statusRecord.setEquipmentId(ce.getId()); + + EquipmentLANStatusData statusData = new EquipmentLANStatusData(); + statusRecord.setDetails(statusData); + } + + Map vlanStatusDataMap = new HashMap<>(); + ((EquipmentLANStatusData) statusRecord.getDetails()).setVlanStatusDataMap(vlanStatusDataMap); + + statusServiceInterface.update(statusRecord); + + // update protocol status + statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.PROTOCOL); + if (statusRecord == null) { + statusRecord = new Status(); + statusRecord.setCustomerId(ce.getCustomerId()); + statusRecord.setEquipmentId(ce.getId()); + + EquipmentProtocolStatusData statusData = new EquipmentProtocolStatusData(); + statusRecord.setDetails(statusData); + } + + EquipmentProtocolStatusData protocolStatusData = (EquipmentProtocolStatusData) statusRecord.getDetails(); + protocolStatusData.setPoweredOn(true); + protocolStatusData.setCloudProtocolVersion("1100"); + protocolStatusData.setProtocolState(EquipmentProtocolState.ready); + protocolStatusData.setBandPlan("FCC"); + protocolStatusData.setBaseMacAddress(MacAddress.valueOf(connectNodeInfo.macAddress)); + protocolStatusData.setCloudCfgDataVersion(42L); + protocolStatusData.setReportedCfgDataVersion(42L); + protocolStatusData.setCountryCode("CA"); + protocolStatusData.setReportedCC(CountryCode.ca); + protocolStatusData.setReportedHwVersion(connectNodeInfo.platformVersion); + if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { + protocolStatusData.setReportedSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)); + } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { + protocolStatusData.setReportedSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); + } else { + protocolStatusData.setReportedSwVersion("Unknown"); + } + if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { + protocolStatusData.setReportedSwAltVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)); + } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { + protocolStatusData.setReportedSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); + } else { + protocolStatusData.setReportedSwVersion("Unknown"); + } + try { + if (connectNodeInfo.ipV4Address != null) { + protocolStatusData.setReportedIpV4Addr(InetAddress.getByName(connectNodeInfo.ipV4Address)); + } + } catch (UnknownHostException e) { + LOG.error("Could not set IpV4Addr {} on AP {} due to UnknownHostException ", + connectNodeInfo.ipV4Address, ce.getName(), e); + } + if ((connectNodeInfo.macAddress != null) && (MacAddress.valueOf(connectNodeInfo.macAddress) != null)) { + protocolStatusData.setReportedMacAddr(MacAddress.valueOf(connectNodeInfo.macAddress)); + } + protocolStatusData.setReportedSku(connectNodeInfo.skuNumber); + protocolStatusData.setSerialNumber(connectNodeInfo.serialNumber); + protocolStatusData.setSystemName(connectNodeInfo.model); + statusRecord.setDetails(protocolStatusData); + Status protocolStatus = statusServiceInterface.update(statusRecord); + LOG.debug("ProtocolStatus for AP {} updated to {}", ce.getName(), protocolStatus); + + statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.FIRMWARE); + if (statusRecord == null) { + statusRecord = new Status(); + statusRecord.setCustomerId(ce.getCustomerId()); + statusRecord.setEquipmentId(ce.getId()); + EquipmentUpgradeStatusData statusData = new EquipmentUpgradeStatusData(); + statusRecord.setDetails(statusData); + } + + EquipmentUpgradeStatusData fwUpgradeStatusData = (EquipmentUpgradeStatusData) statusRecord.getDetails(); + if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { + fwUpgradeStatusData.setActiveSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)); + } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { + fwUpgradeStatusData + .setActiveSwVersion(connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); + } else { + fwUpgradeStatusData.setActiveSwVersion("Unknown"); + } + if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { + fwUpgradeStatusData.setAlternateSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)); + } else if (connectNodeInfo.versionMatrix.containsKey(OvsdbStringConstants.FW_IMAGE_NAME_KEY)) { + fwUpgradeStatusData.setAlternateSwVersion( + connectNodeInfo.versionMatrix.get(OvsdbStringConstants.FW_IMAGE_NAME_KEY)); + } else { + fwUpgradeStatusData.setAlternateSwVersion("Unknown"); + } + + if (fwUpgradeStatusData.getUpgradeState() == null) { + fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.undefined); + fwUpgradeStatusData.setUpgradeStartTime(null); + + } + + statusRecord.setDetails(fwUpgradeStatusData); + statusServiceInterface.update(statusRecord); + + Status networkAdminStatusRec = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), + StatusDataType.NETWORK_ADMIN); + if (networkAdminStatusRec == null) { + networkAdminStatusRec = new Status(); + networkAdminStatusRec.setCustomerId(ce.getCustomerId()); + networkAdminStatusRec.setEquipmentId(ce.getId()); + NetworkAdminStatusData statusData = new NetworkAdminStatusData(); + networkAdminStatusRec.setDetails(statusData); + } + + NetworkAdminStatusData netAdminStatusData = (NetworkAdminStatusData) networkAdminStatusRec.getDetails(); + netAdminStatusData.setDhcpStatus(StatusCode.normal); + netAdminStatusData.setCloudLinkStatus(StatusCode.normal); + netAdminStatusData.setDnsStatus(StatusCode.normal); + + networkAdminStatusRec.setDetails(netAdminStatusData); + + networkAdminStatusRec = statusServiceInterface.update(networkAdminStatusRec); + + } catch (Exception e) { + LOG.debug("Exception in updateApStatus", e); + } + + } + + private void reconcileFwVersionToTrack(Equipment ce, String reportedFwVersionFromAp, String model) { + + LOG.debug("reconcileFwVersionToTrack for AP {} with active firmware version {} model {}", ce.getInventoryId(), + reportedFwVersionFromAp, model); + Status statusRecord = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), StatusDataType.FIRMWARE); + + EquipmentUpgradeStatusData fwUpgradeStatusData = (EquipmentUpgradeStatusData) statusRecord.getDetails(); + + // default track settings for firmware + CustomerFirmwareTrackSettings trackSettings = firmwareServiceInterface.getDefaultCustomerTrackSetting(); + + // check for updated/modified track settings for this customer + CustomerFirmwareTrackRecord custFwTrackRecord = firmwareServiceInterface + .getCustomerFirmwareTrackRecord(ce.getCustomerId()); + + long trackRecordId = -1; + if (custFwTrackRecord != null) { + trackSettings = custFwTrackRecord.getSettings(); + trackRecordId = custFwTrackRecord.getTrackRecordId(); + } + // determine if AP requires FW upgrade before cloud + // connection/provision + if (trackSettings.getAutoUpgradeDeprecatedOnBind().equals(TrackFlag.ALWAYS) + || trackSettings.getAutoUpgradeUnknownOnBind().equals(TrackFlag.ALWAYS)) { + + LOG.debug("reconcileFwVersionToTrack for AP {} track flag for auto-upgrade {}", ce.getInventoryId(), + trackSettings.getAutoUpgradeDeprecatedOnBind()); + + // check the reported fw version for the AP, if it is < than + // the default version for the cloud, then download and + // flash the firmware before proceeding. + // then return; + FirmwareTrackRecord fwTrackRecord = null; + if (trackRecordId == -1) { + // take the default + fwTrackRecord = firmwareServiceInterface.getFirmwareTrackByName(FirmwareTrackRecord.DEFAULT_TRACK_NAME); + + } else { + // there must be a customer one + fwTrackRecord = firmwareServiceInterface.getFirmwareTrackById(trackRecordId); + } + + if (fwTrackRecord != null) { + + LOG.debug("reconcileFwVersionToTrack for AP {} firmwareTrackRecord {}", ce.getInventoryId(), + fwTrackRecord); + + List fwTrackAssignmentDetails = firmwareServiceInterface + .getFirmwareTrackAssignments(fwTrackRecord.getTrackName()); + + String targetFwVersionNameForTrack = null; + + if (fwTrackAssignmentDetails != null) { + for (FirmwareTrackAssignmentDetails details : fwTrackAssignmentDetails) { + if (model.equalsIgnoreCase(details.getModelId())) { + targetFwVersionNameForTrack = details.getVersionName(); + break; + } + } + } + + if (targetFwVersionNameForTrack == null) { + LOG.info("No target FW version for this track {}", fwTrackRecord); + + } else { + LOG.debug("reconcileFwVersionToTrack for AP {} targetFwVersion for track {}", ce.getInventoryId(), + targetFwVersionNameForTrack); + + if (reportedFwVersionFromAp != null) { + if (!targetFwVersionNameForTrack.equals(reportedFwVersionFromAp)) { + LOG.debug( + "reconcileFwVersionToTrack for AP {} targetFwVersion {} doesn't match reported fw version {}, triggering download and flash", + ce.getInventoryId(), targetFwVersionNameForTrack, reportedFwVersionFromAp); + + fwUpgradeStatusData.setTargetSwVersion(targetFwVersionNameForTrack); + fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.out_of_date); + statusRecord.setDetails(fwUpgradeStatusData); + statusRecord = statusServiceInterface.update(statusRecord); + triggerFwDownload(ce, fwUpgradeStatusData, trackSettings); + } else if (targetFwVersionNameForTrack.equals(reportedFwVersionFromAp)) { + LOG.debug("reconcileFwVersionToTrack for AP {} targetFwVersion {} is active", + ce.getInventoryId(), targetFwVersionNameForTrack); + + fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.up_to_date); + fwUpgradeStatusData.setActiveSwVersion(targetFwVersionNameForTrack); + fwUpgradeStatusData.setAlternateSwVersion(targetFwVersionNameForTrack); + fwUpgradeStatusData.setTargetSwVersion(targetFwVersionNameForTrack); + + statusRecord.setDetails(fwUpgradeStatusData); + statusRecord = statusServiceInterface.update(statusRecord); + + } + } + + } + + } + + } else + + { + LOG.debug("Automatic firmware upgrade is not configured for track {}", trackSettings); + } + } + + private void triggerFwDownload(Equipment ce, EquipmentUpgradeStatusData fwUpgradeStatusData, + CustomerFirmwareTrackSettings trackSettings) { + LOG.debug("triggerFwDownloadAndFlash Automatic firmware upgrade is configured for track {}.", trackSettings); + + try { + FirmwareVersion fwVersion = firmwareServiceInterface + .getFirmwareVersionByName(fwUpgradeStatusData.getTargetSwVersion()); + + if (fwVersion != null) { + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(ce.getInventoryId()); + if (ovsdbSession == null) { + throw new IllegalStateException("AP is not connected " + ce.getInventoryId()); + } + + CEGWFirmwareDownloadRequest fwDownloadRequest = new CEGWFirmwareDownloadRequest(ce.getInventoryId(), + ce.getId(), fwVersion.getVersionName(), fwVersion.getFilename(), + fwVersion.getValidationMethod(), fwVersion.getValidationCode()); + List commands = new ArrayList<>(); + commands.add(fwDownloadRequest); + + gatewayController.updateActiveCustomer(ce.getCustomerId()); + ListOfEquipmentCommandResponses responses = gatewayController.sendCommands(commands); + LOG.debug("FW Download Response {}", responses); + + } + } catch (Exception e) { + LOG.error("Cannot trigger FW download {}", e); + } + } + + @Override + public void apDisconnected(String apId) { + LOG.info("AP {} got disconnected from the gateway", apId); + try { + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession != null) { + // if (ovsdbSession.getCustomerId() > 0 && + // ovsdbSession.getEquipmentId() > 0L) { + // List statusForDisconnectedAp = + // statusServiceInterface.delete(ovsdbSession.getCustomerId(), + // ovsdbSession.getEquipmentId()); + // LOG.info("Deleted status records {} for AP {}", + // statusForDisconnectedAp, apId); + // } + if (ovsdbSession.getRoutingId() > 0L) { + try { + routingServiceInterface.delete(ovsdbSession.getRoutingId()); + } catch (Exception e) { + LOG.warn("Unable to delete routing service Id {} for ap {}. {}", ovsdbSession.getRoutingId(), + apId, e); + } + } + } else { + LOG.warn("Cannot find ap {} in inventory", apId); + } + } catch (Exception e) { + LOG.error("Exception when registering ap routing {}", apId, e); + } + + } + + @Override + public OpensyncAPConfig getApConfig(String apId) { + LOG.info("Retrieving config for AP {} ", apId); + OpensyncAPConfig ret = null; + + try { + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + if (ovsdbSession == null) { + throw new IllegalStateException("AP is not connected " + apId); + } + int customerId = ovsdbSession.getCustomerId(); + Customer customer = customerServiceInterface.getOrNull(customerId); + if ((customer != null) && (customer.getDetails() != null) + && (customer.getDetails().getAutoProvisioning() != null) + && customer.getDetails().getAutoProvisioning().isEnabled()) { + Equipment equipmentConfig = getCustomerEquipment(apId); + + if (equipmentConfig == null) { + throw new IllegalStateException("Cannot retrieve configuration for " + apId); + } + + ret = new OpensyncAPConfig(); + + ret.setCustomerEquipment(equipmentConfig); + + Location eqLocation = locationServiceInterface.get(equipmentConfig.getLocationId()); + + ret.setEquipmentLocation(eqLocation); + + ProfileContainer profileContainer = new ProfileContainer( + profileServiceInterface.getProfileWithChildren(equipmentConfig.getProfileId())); + + ret.setApProfile(profileContainer.getOrNull(equipmentConfig.getProfileId())); + + ret.setRfProfile(profileContainer.getChildOfTypeOrNull(equipmentConfig.getProfileId(), ProfileType.rf)); + + ret.setSsidProfile( + profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.ssid)); + + ret.setMetricsProfiles( + profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.metrics)); + + Set radiusSet = new HashSet<>(); + Set captiveProfileIds = new HashSet<>(); + Set bonjourGatewayProfileIds = new HashSet<>(); + + OpensyncAPHotspot20Config hotspotConfig = new OpensyncAPHotspot20Config(); + + Set hotspot20ProfileSet = new HashSet<>(); + Set hotspot20OperatorSet = new HashSet<>(); + Set hotspot20VenueSet = new HashSet<>(); + Set hotspot20ProviderSet = new HashSet<>(); + + for (Profile ssidProfile : ret.getSsidProfile()) { + + hotspot20ProfileSet + .addAll(profileContainer.getChildrenOfType(ssidProfile.getId(), ProfileType.hotspot_2pt0)); + + radiusSet + .addAll(profileContainer.getChildrenOfType(ret.getApProfile().getId(), ProfileType.radius)); + if (ssidProfile.getDetails() != null) { + Long captivePortId = ((SsidConfiguration) ssidProfile.getDetails()).getCaptivePortalId(); + if (captivePortId != null) { + captiveProfileIds.add(captivePortId); + } + Long bonjourGatewayProfileId = ((SsidConfiguration) ssidProfile.getDetails()) + .getBonjourGatewayProfileId(); + if (bonjourGatewayProfileId != null) { + bonjourGatewayProfileIds.add(bonjourGatewayProfileId); + } + } + } + + if (hotspot20ProfileSet.size() > 0) { + for (Profile hotspot20Profile : hotspot20ProfileSet) { + hotspot20OperatorSet.addAll( + profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.operator)); + hotspot20VenueSet.addAll( + profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.venue)); + hotspot20ProviderSet.addAll( + profileContainer.getChildrenOfType(hotspot20Profile.getId(), ProfileType.id_provider)); + } + hotspotConfig.setHotspot20OperatorSet(hotspot20OperatorSet); + hotspotConfig.setHotspot20ProfileSet(hotspot20ProfileSet); + hotspotConfig.setHotspot20ProviderSet(hotspot20ProviderSet); + hotspotConfig.setHotspot20VenueSet(hotspot20VenueSet); + + ret.setHotspotConfig(hotspotConfig); + } + + ret.setRadiusProfiles(new ArrayList<>(radiusSet)); + ret.setCaptiveProfiles(profileServiceInterface.get(captiveProfileIds)); + ret.setBonjourGatewayProfiles(profileServiceInterface.get(bonjourGatewayProfileIds)); + + List blockedClients = clientServiceInterface + .getBlockedClients(customerId); + List blockList = Lists.newArrayList(); + if ((blockedClients != null) && !blockedClients.isEmpty()) { + blockedClients.forEach(client -> blockList.add(client.getMacAddress())); + } + ret.setBlockedClients(blockList); + + LOG.debug("ApConfig {}", ret); + } else { + LOG.info("Autoconfig is not enabled for this AP {}", apId); + } + + } catch (Exception e) { + LOG.error("Cannot read config for AP {}", apId, e); + } + + return ret; + } + + @Override + public void processMqttMessage(String topic, Report report) { + mqttMessageProcessor.processMqttMessage(topic, report); + } + + @Override + public void processMqttMessage(String topic, FlowReport flowReport) { + mqttMessageProcessor.processMqttMessage(topic, flowReport); + } + + @Override + public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { + mqttMessageProcessor.processMqttMessage(topic, wcStatsReport); + } + + @Override + public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { + LOG.debug("Received Wifi_VIF_State table update for AP {}", apId); + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession == null) { + LOG.debug("wifiVIFStateDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } + + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); + + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiVIFStateDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } + + Equipment apNode = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (apNode == null) { + LOG.debug("wifiVIFStateDbTableUpdate::Cannot get EquipmentId for AP {}", apId); + return; // we don't have the required info to get the + // radio type yet + } + ApElementConfiguration apElementConfig = (ApElementConfiguration) apNode.getDetails(); + + ProfileContainer profileContainer = new ProfileContainer( + profileServiceInterface.getProfileWithChildren(apNode.getProfileId())); + RfConfiguration rfConfig = (RfConfiguration) profileContainer + .getChildOfTypeOrNull(apNode.getProfileId(), ProfileType.rf).getDetails(); + + for (OpensyncAPVIFState vifState : vifStateTables) { + + LOG.debug("Processing vifState for interface {} on AP {}", vifState.getIfName(), apId); + + String bssid = vifState.getMac(); + + if ((bssid == null) || bssid.equals("")) { + LOG.warn("BSSID from AP {} for vif {} is null or empty", apId, vifState.getIfName()); + continue; + } + String ssid = vifState.getSsid(); + + if ((ssid == null) || ssid.equals("")) { + LOG.warn("SSID from AP {} interface {} is null or empty", apId, vifState.getIfName()); + continue; + } + + int numClients = vifState.getAssociatedClients().size(); + + int channel = vifState.getChannel(); + + if ((channel < 1)) { + LOG.warn("Channel from AP {} interface {} is null or empty", apId, vifState.getIfName()); + continue; + } + + LOG.debug("Values from Vif State Mac (BSSID) {} SSID {} AssociatedClients {} Channel {}", bssid, ssid, + vifState.getAssociatedClients()); + + RadioType radioType = null; + Map rfElementMap = rfConfig.getRfConfigMap(); + Map elementRadioMap = apElementConfig.getRadioMap(); + for (RadioType rType : elementRadioMap.keySet()) { + boolean autoChannelSelection = rfElementMap.get(rType).getAutoChannelSelection(); + if (elementRadioMap.get(rType).getActiveChannel(autoChannelSelection) == channel) { + radioType = rType; + break; + } + } - updateActiveBssids(customerId, equipmentId, apId, ssid, radioType, bssid, numClients); + updateActiveBssids(customerId, equipmentId, apId, ssid, radioType, bssid, numClients); - } + } - Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); - if (activeBssidsStatus != null) { - updateClientDetailsStatus(customerId, equipmentId, (ActiveBSSIDs) activeBssidsStatus.getDetails()); - } + Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.ACTIVE_BSSIDS); + if (activeBssidsStatus != null) { + updateClientDetailsStatus(customerId, equipmentId, (ActiveBSSIDs) activeBssidsStatus.getDetails()); + } - LOG.info("Finished wifiVIFStateDbTableUpdate updated {}", activeBssidsStatus); + LOG.info("Finished wifiVIFStateDbTableUpdate updated {}", activeBssidsStatus); - } - - private void updateClientDetailsStatus(int customerId, long equipmentId, ActiveBSSIDs statusDetails) { - Status clientDetailsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.CLIENT_DETAILS); - - LOG.debug("Processing updateClientDetailsStatus Status for ActiveBSSIDs {}", statusDetails); - - if (clientDetailsStatus == null) { - clientDetailsStatus = new Status(); - clientDetailsStatus.setCustomerId(customerId); - clientDetailsStatus.setEquipmentId(equipmentId); - clientDetailsStatus.setStatusDataType(StatusDataType.CLIENT_DETAILS); - clientDetailsStatus.setDetails(new ClientConnectionDetails()); - clientDetailsStatus = statusServiceInterface.update(clientDetailsStatus); - - LOG.debug("Processing updateClientDetailsStatus, new ClientDetailsStatus {}", clientDetailsStatus); - } - - ClientConnectionDetails clientConnectionDetails = (ClientConnectionDetails) clientDetailsStatus.getDetails(); - - Map clientsPerRadioType = new HashMap<>(); - - for (ActiveBSSID bssid : statusDetails.getActiveBSSIDs()) { - - if (!clientsPerRadioType.containsKey(bssid.getRadioType())) { - clientsPerRadioType.put(bssid.getRadioType(), 0); - } - int numConnectedForBssid = bssid.getNumDevicesConnected(); - int currentNumberOfClients = clientsPerRadioType.get(bssid.getRadioType()); - clientsPerRadioType.put(bssid.getRadioType(), currentNumberOfClients + numConnectedForBssid); - LOG.debug("Processing updateClientDetailsStatus. Upgrade numClients for RadioType {} from {} to {}", - bssid.getRadioType(), currentNumberOfClients, clientsPerRadioType.get(bssid.getRadioType())); - } + } + + private void updateClientDetailsStatus(int customerId, long equipmentId, ActiveBSSIDs statusDetails) { + Status clientDetailsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.CLIENT_DETAILS); + + LOG.debug("Processing updateClientDetailsStatus Status for ActiveBSSIDs {}", statusDetails); + + if (clientDetailsStatus == null) { + clientDetailsStatus = new Status(); + clientDetailsStatus.setCustomerId(customerId); + clientDetailsStatus.setEquipmentId(equipmentId); + clientDetailsStatus.setStatusDataType(StatusDataType.CLIENT_DETAILS); + clientDetailsStatus.setDetails(new ClientConnectionDetails()); + clientDetailsStatus = statusServiceInterface.update(clientDetailsStatus); + + LOG.debug("Processing updateClientDetailsStatus, new ClientDetailsStatus {}", clientDetailsStatus); + } + + ClientConnectionDetails clientConnectionDetails = (ClientConnectionDetails) clientDetailsStatus.getDetails(); + + Map clientsPerRadioType = new HashMap<>(); + + for (ActiveBSSID bssid : statusDetails.getActiveBSSIDs()) { + + if (!clientsPerRadioType.containsKey(bssid.getRadioType())) { + clientsPerRadioType.put(bssid.getRadioType(), 0); + } + int numConnectedForBssid = bssid.getNumDevicesConnected(); + int currentNumberOfClients = clientsPerRadioType.get(bssid.getRadioType()); + clientsPerRadioType.put(bssid.getRadioType(), currentNumberOfClients + numConnectedForBssid); + LOG.debug("Processing updateClientDetailsStatus. Upgrade numClients for RadioType {} from {} to {}", + bssid.getRadioType(), currentNumberOfClients, clientsPerRadioType.get(bssid.getRadioType())); + } - clientConnectionDetails.setNumClientsPerRadio(clientsPerRadioType); - clientDetailsStatus.setDetails(clientConnectionDetails); - clientDetailsStatus = statusServiceInterface.update(clientDetailsStatus); + clientConnectionDetails.setNumClientsPerRadio(clientsPerRadioType); + clientDetailsStatus.setDetails(clientConnectionDetails); + clientDetailsStatus = statusServiceInterface.update(clientDetailsStatus); - if (LOG.isTraceEnabled()) { - LOG.trace("Processing updateClientDetailsStatus. Updated clientConnectionDetails to {}", - clientDetailsStatus.toPrettyString()); - } + if (LOG.isTraceEnabled()) { + LOG.trace("Processing updateClientDetailsStatus. Updated clientConnectionDetails to {}", + clientDetailsStatus.toPrettyString()); + } - LOG.info("Finished updateClientDetailsStatus updated {}", clientDetailsStatus); + LOG.info("Finished updateClientDetailsStatus updated {}", clientDetailsStatus); - } + } - @Override - public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { - LOG.debug("Received Wifi_Radio_State table update for AP {}", apId); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + @Override + public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { + LOG.debug("Received Wifi_Radio_State table update for AP {}", apId); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession == null) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + if (ovsdbSession == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); - Status protocolStatus = null; - EquipmentProtocolStatusData protocolStatusData = null; - - for (OpensyncAPRadioState radioState : radioStateTables) { - LOG.debug("Processing Wifi_Radio_State table update for AP {} {}", apId, radioState); + Status protocolStatus = null; + EquipmentProtocolStatusData protocolStatusData = null; + + for (OpensyncAPRadioState radioState : radioStateTables) { + LOG.debug("Processing Wifi_Radio_State table update for AP {} {}", apId, radioState); - if (radioState.getFreqBand().equals(RadioType.UNSUPPORTED)) { - LOG.debug("Could not get radio configuration for AP {}", apId); - continue; - } + if (radioState.getFreqBand().equals(RadioType.UNSUPPORTED)) { + LOG.debug("Could not get radio configuration for AP {}", apId); + continue; + } - if (radioState.getAllowedChannels() != null) { - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setAllowedChannels(new ArrayList<>(radioState.getAllowedChannels())); + if (radioState.getAllowedChannels() != null) { + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setAllowedChannels(new ArrayList<>(radioState.getAllowedChannels())); - LOG.debug("Updated AllowedChannels from Wifi_Radio_State table change for AP {}", apId); + LOG.debug("Updated AllowedChannels from Wifi_Radio_State table change for AP {}", apId); - } + } - if (radioState.getTxPower() > 0) { - SourceType txPowerSource = apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .getEirpTxPower().getSource(); - // Preserve the source while updating the value - if (txPowerSource == SourceType.auto) { - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setEirpTxPower(SourceSelectionValue.createAutomaticInstance(radioState.getTxPower())); - } else if (txPowerSource == SourceType.profile) { - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setEirpTxPower(SourceSelectionValue.createProfileInstance(radioState.getTxPower())); - } else { - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setEirpTxPower(SourceSelectionValue.createManualInstance(radioState.getTxPower())); - } - - LOG.debug("Updated TxPower from Wifi_Radio_State table change for AP {}", apId); - } - - StateSetting state = StateSetting.disabled; - if (radioState.isEnabled()) { - state = StateSetting.enabled; - } - - if (!apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).getRadioAdminState() - .equals(state)) { - // only update if changed - apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).setRadioAdminState(state); - - LOG.debug("Updated RadioAdminState from Wifi_Radio_State table change for AP {}", apId); - - } - - protocolStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL); - - if (protocolStatus != null) { - - protocolStatusData = (EquipmentProtocolStatusData) protocolStatus.getDetails(); - if (!protocolStatusData.getReportedCC() - .equals(CountryCode.valueOf(radioState.getCountry().toLowerCase()))) { - protocolStatusData.setReportedCC(CountryCode.valueOf(radioState.getCountry().toLowerCase())); - protocolStatus.setDetails(protocolStatusData); - - } else { - protocolStatus = null; - } + if (radioState.getTxPower() > 0) { + SourceType txPowerSource = apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .getEirpTxPower().getSource(); + // Preserve the source while updating the value + if (txPowerSource == SourceType.auto) { + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setEirpTxPower(SourceSelectionValue.createAutomaticInstance(radioState.getTxPower())); + } else if (txPowerSource == SourceType.profile) { + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setEirpTxPower(SourceSelectionValue.createProfileInstance(radioState.getTxPower())); + } else { + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setEirpTxPower(SourceSelectionValue.createManualInstance(radioState.getTxPower())); + } + + LOG.debug("Updated TxPower from Wifi_Radio_State table change for AP {}", apId); + } + + StateSetting state = StateSetting.disabled; + if (radioState.isEnabled()) { + state = StateSetting.enabled; + } + + if (!apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).getRadioAdminState() + .equals(state)) { + // only update if changed + apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).setRadioAdminState(state); + + LOG.debug("Updated RadioAdminState from Wifi_Radio_State table change for AP {}", apId); + + } + + protocolStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL); + + if (protocolStatus != null) { + + protocolStatusData = (EquipmentProtocolStatusData) protocolStatus.getDetails(); + if (!protocolStatusData.getReportedCC() + .equals(CountryCode.valueOf(radioState.getCountry().toLowerCase()))) { + protocolStatusData.setReportedCC(CountryCode.valueOf(radioState.getCountry().toLowerCase())); + protocolStatus.setDetails(protocolStatusData); + + } else { + protocolStatus = null; + } + + } - } + } - } + if (protocolStatus != null) { + statusServiceInterface.update(protocolStatus); + } + + ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } + + try { + + if (!apElementConfiguration.equals((ce.getDetails()))) { - if (protocolStatus != null) { - statusServiceInterface.update(protocolStatus); - } + ((ApElementConfiguration) ce.getDetails()).setRadioMap(apElementConfiguration.getRadioMap()); + ((ApElementConfiguration) ce.getDetails()) + .setAdvancedRadioMap(apElementConfiguration.getAdvancedRadioMap()); + + apElementConfiguration = (ApElementConfiguration) ce.getDetails(); + ce = equipmentServiceInterface.update(ce); + } + } catch (DsConcurrentModificationException e) { + LOG.debug("Equipment reference changed, update instance and retry.", e.getMessage()); + ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + ce.setDetails(apElementConfiguration); + ce = equipmentServiceInterface.update(ce); + } + LOG.info("Finished wifiRadioStateDbTableUpdate"); + + } + + private void updateActiveBssids(int customerId, long equipmentId, Object apId, String ssid, RadioType freqBand, + String macAddress, int numClients) { + Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.ACTIVE_BSSIDS); + + statusServiceInterface.getForCustomer(customerId, null, ImmutableSet.of(StatusDataType.ACTIVE_BSSIDS), null, + null); + if (activeBssidsStatus == null) { + activeBssidsStatus = new Status(); + activeBssidsStatus.setCustomerId(customerId); + activeBssidsStatus.setEquipmentId(equipmentId); + activeBssidsStatus.setStatusDataType(StatusDataType.ACTIVE_BSSIDS); + + ActiveBSSIDs statusDetails = new ActiveBSSIDs(); + statusDetails.setActiveBSSIDs(new ArrayList()); + + activeBssidsStatus.setDetails(statusDetails); + + activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); + LOG.debug("Processing Wifi_VIF_State table update for AP {}, created new ACTIVE_BSSID Status {}", apId, + activeBssidsStatus); + + } + + ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); + + LOG.debug("Processing Wifi_VIF_State table update for AP {}, activeBSSIDs StatusDetails before update {}", apId, + statusDetails); + + List currentActiveBSSIDs = statusDetails.getActiveBSSIDs(); + if (currentActiveBSSIDs == null) { + currentActiveBSSIDs = new ArrayList<>(); + } else { + currentActiveBSSIDs = currentActiveBSSIDs.stream() + .filter(p -> (!p.getRadioType().equals(freqBand) || !p.getSsid().equals(ssid))) + .collect(Collectors.toList()); + LOG.debug( + "Processing Wifi_VIF_State table update for AP {}, activeBSSIDs bssidList without current radio freq {} and ssid {}", + apId, currentActiveBSSIDs, ssid); + } + + ActiveBSSID activeBssid = new ActiveBSSID(); + activeBssid.setBssid(macAddress); + activeBssid.setSsid(ssid); + activeBssid.setRadioType(freqBand); + activeBssid.setNumDevicesConnected(numClients); + currentActiveBSSIDs.add(activeBssid); + + statusDetails.setActiveBSSIDs(currentActiveBSSIDs); + activeBssidsStatus.setDetails(statusDetails); + + activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); + + if (LOG.isTraceEnabled()) { + LOG.trace("Processing Wifi_VIF_State table update for AP {}, updated ACTIVE_BSSID Status {}", apId, + activeBssidsStatus.toPrettyString()); + } + } + + @Override + public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { + + LOG.debug("Received Wifi_Inet_State table update for AP {}", apId); + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession == null) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } + + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); + + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } + + Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); + + if (ce == null) { + LOG.debug("wifiInetStateDbTableUpdate Cannot get customer Equipment for {}", apId); + return; + } + + Status lanStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.LANINFO); + if (lanStatus == null) { + lanStatus = new Status(); + lanStatus.setCustomerId(customerId); + lanStatus.setEquipmentId(equipmentId); + lanStatus.setStatusDataType(StatusDataType.LANINFO); + lanStatus.setDetails(new EquipmentLANStatusData()); + lanStatus = statusServiceInterface.update(lanStatus); + } + + EquipmentLANStatusData lanStatusData = (EquipmentLANStatusData) lanStatus.getDetails(); + + Status protocolStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL); + if (protocolStatus == null) { + protocolStatus = new Status(); + protocolStatus.setCustomerId(customerId); + protocolStatus.setEquipmentId(equipmentId); + protocolStatus.setStatusDataType(StatusDataType.PROTOCOL); + protocolStatus.setDetails(new EquipmentProtocolStatusData()); + protocolStatus = statusServiceInterface.update(protocolStatus); + } + + EquipmentProtocolStatusData protocolStatusData = (EquipmentProtocolStatusData) protocolStatus.getDetails(); + + for (OpensyncAPInetState inetState : inetStateTables) { + + if (inetState.ifName != null && inetState.ifName.equals(defaultWanInterfaceName)) { + + if (inetState.inetAddr != null) { + try { + protocolStatusData.setReportedIpV4Addr(Inet4Address.getByName(inetState.inetAddr)); + protocolStatus.setDetails(protocolStatusData); + protocolStatus = statusServiceInterface.update(protocolStatus); + LOG.info("Updated IpV4Addr for AP {} to {} from Wifi_Inet_State change for if_name {}", apId, + ((EquipmentProtocolStatusData) protocolStatus.getDetails()).getReportedIpV4Addr(), inetState.ifName); + LOG.debug("ProtocolStatus for AP {} updated to {}", apId, protocolStatus); + + } catch (UnknownHostException e) { + LOG.error("Could not set IpV4Addr {} on AP {} due to UnknownHostException ", inetState.inetAddr, + apId, e); + } + } + + } + + if (inetState.getVlanId() > 1) { + + if (!lanStatusData.getVlanStatusDataMap().containsKey(inetState.getVlanId())) { + lanStatusData.getVlanStatusDataMap().put(inetState.getVlanId(), new VLANStatusData()); + } + + try { + lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) + .setGateway(InetAddress.getByName(inetState.getGateway())); + + String primaryDns = inetState.getDns().get("primary"); + if (primaryDns != null) { + lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) + .setDnsServer1(InetAddress.getByName(primaryDns)); + } + lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) + .setSubnetMask(InetAddress.getByName(inetState.getNetmask())); + + String dhcpOption = inetState.getDhcpd().get("dhcp_option"); + if (dhcpOption != null) { + String dhcpServer = dhcpOption.split(",")[1]; + if (dhcpServer != null) { + lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) + .setDhcpServer(InetAddress.getByName(dhcpServer)); + } + } + String inetAddr = inetState.getInetAddr(); + if (inetAddr != null) { + lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) + .setIpBase(InetAddress.getByName(inetAddr)); + } + + } catch (UnknownHostException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + lanStatus.setDetails(lanStatusData); + lanStatus = statusServiceInterface.update(lanStatus); + + } + } + + } + + @Override + public void wifiInetStateDbTableDelete(List inetStateTables, String apId) { - ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } - - try { + LOG.debug("Received Wifi_Inet_State table delete for AP {}", apId); + + } + + @Override + public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, + String apId) { + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - if (!apElementConfiguration.equals((ce.getDetails()))) { + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); - ((ApElementConfiguration) ce.getDetails()).setRadioMap(apElementConfiguration.getRadioMap()); - ((ApElementConfiguration) ce.getDetails()) - .setAdvancedRadioMap(apElementConfiguration.getAdvancedRadioMap()); - - apElementConfiguration = (ApElementConfiguration) ce.getDetails(); - ce = equipmentServiceInterface.update(ce); - } - } catch (DsConcurrentModificationException e) { - LOG.debug("Equipment reference changed, update instance and retry.", e.getMessage()); - ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - ce.setDetails(apElementConfiguration); - ce = equipmentServiceInterface.update(ce); - } - LOG.info("Finished wifiRadioStateDbTableUpdate"); + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } - } + Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); - private void updateActiveBssids(int customerId, long equipmentId, Object apId, String ssid, RadioType freqBand, - String macAddress, int numClients) { - Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); - - if (activeBssidsStatus == null) { - activeBssidsStatus = new Status(); - activeBssidsStatus.setCustomerId(customerId); - activeBssidsStatus.setEquipmentId(equipmentId); - activeBssidsStatus.setStatusDataType(StatusDataType.ACTIVE_BSSIDS); - - ActiveBSSIDs statusDetails = new ActiveBSSIDs(); - statusDetails.setActiveBSSIDs(new ArrayList()); - - activeBssidsStatus.setDetails(statusDetails); - - activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - LOG.debug("Processing Wifi_VIF_State table update for AP {}, created new ACTIVE_BSSID Status {}", apId, - activeBssidsStatus); - - } - - ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); - - LOG.debug("Processing Wifi_VIF_State table update for AP {}, activeBSSIDs StatusDetails before update {}", apId, - statusDetails); - - List currentActiveBSSIDs = statusDetails.getActiveBSSIDs(); - if (currentActiveBSSIDs == null) { - currentActiveBSSIDs = new ArrayList<>(); - } else { - currentActiveBSSIDs = currentActiveBSSIDs.stream() - .filter(p -> (!p.getRadioType().equals(freqBand) || !p.getSsid().equals(ssid))) - .collect(Collectors.toList()); - LOG.debug( - "Processing Wifi_VIF_State table update for AP {}, activeBSSIDs bssidList without current radio freq {} and ssid {}", - apId, currentActiveBSSIDs, ssid); - } - - ActiveBSSID activeBssid = new ActiveBSSID(); - activeBssid.setBssid(macAddress); - activeBssid.setSsid(ssid); - activeBssid.setRadioType(freqBand); - activeBssid.setNumDevicesConnected(numClients); - currentActiveBSSIDs.add(activeBssid); - - statusDetails.setActiveBSSIDs(currentActiveBSSIDs); - activeBssidsStatus.setDetails(statusDetails); - - activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - - if (LOG.isTraceEnabled()) { - LOG.trace("Processing Wifi_VIF_State table update for AP {}, updated ACTIVE_BSSID Status {}", apId, - activeBssidsStatus.toPrettyString()); - } - } - - @Override - public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { - - LOG.debug("Received Wifi_Inet_State table update for AP {}", apId); - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession == null) { - LOG.debug("wifiInetStateDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } - - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); - - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiInetStateDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } - - Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); - - if (ce == null) { - LOG.debug("wifiInetStateDbTableUpdate Cannot get customer Equipment for {}", apId); - return; - } - - Status lanStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.LANINFO); - if (lanStatus == null) { - lanStatus = new Status(); - lanStatus.setCustomerId(customerId); - lanStatus.setEquipmentId(equipmentId); - lanStatus.setStatusDataType(StatusDataType.LANINFO); - lanStatus.setDetails(new EquipmentLANStatusData()); - lanStatus = statusServiceInterface.update(lanStatus); - } - - EquipmentLANStatusData lanStatusData = (EquipmentLANStatusData) lanStatus.getDetails(); - for (OpensyncAPInetState inetState : inetStateTables) { - - if (inetState.getVlanId() > 1) { - - if (!lanStatusData.getVlanStatusDataMap().containsKey(inetState.getVlanId())) { - lanStatusData.getVlanStatusDataMap().put(inetState.getVlanId(), new VLANStatusData()); - } + if (ce == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate Cannot get customer Equipment for {}", apId); + return; + } - try { - lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) - .setGateway(InetAddress.getByName(inetState.getGateway())); + if ((wifiAssociatedClients == null) || wifiAssociatedClients.isEmpty()) { + return; + } + + for (OpensyncWifiAssociatedClients opensyncWifiAssociatedClients : wifiAssociatedClients) { + com.telecominfraproject.wlan.client.models.Client clientInstance = clientServiceInterface + .getOrNull(customerId, new MacAddress(opensyncWifiAssociatedClients.getMac())); + + boolean isReassociation = true; + if (clientInstance == null) { + clientInstance = new com.telecominfraproject.wlan.client.models.Client(); - String primaryDns = inetState.getDns().get("primary"); - if (primaryDns != null) { - lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) - .setDnsServer1(InetAddress.getByName(primaryDns)); - } - lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) - .setSubnetMask(InetAddress.getByName(inetState.getNetmask())); - - String dhcpOption = inetState.getDhcpd().get("dhcp_option"); - if (dhcpOption != null) { - String dhcpServer = dhcpOption.split(",")[1]; - if (dhcpServer != null) { - lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) - .setDhcpServer(InetAddress.getByName(dhcpServer)); - } - } - String inetAddr = inetState.getInetAddr(); - if (inetAddr != null) { - lanStatusData.getVlanStatusDataMap().get(inetState.getVlanId()) - .setIpBase(InetAddress.getByName(inetAddr)); - } - - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + clientInstance.setCustomerId(customerId); + clientInstance.setMacAddress(new MacAddress(opensyncWifiAssociatedClients.getMac())); + clientInstance.setDetails(new ClientInfoDetails()); + clientInstance = clientServiceInterface.create(clientInstance); - lanStatus.setDetails(lanStatusData); - lanStatus = statusServiceInterface.update(lanStatus); + isReassociation = false; - } - } + } + ClientInfoDetails clientDetails = (ClientInfoDetails) clientInstance.getDetails(); - } + clientInstance.setDetails(clientDetails); - @Override - public void wifiInetStateDbTableDelete(List inetStateTables, String apId) { + clientInstance = clientServiceInterface.update(clientInstance); - LOG.debug("Received Wifi_Inet_State table delete for AP {}", apId); + ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, + clientInstance.getMacAddress()); - } + if (clientSession == null) { + clientSession = new ClientSession(); + clientSession.setCustomerId(customerId); + clientSession.setEquipmentId(equipmentId); + clientSession.setMacAddress(clientInstance.getMacAddress()); + clientSession.setLocationId(ce.getLocationId()); + ClientSessionDetails clientSessionDetails = new ClientSessionDetails(); + clientSessionDetails.setIsReassociation(isReassociation); + clientSessionDetails.setSessionId(clientInstance.getMacAddress().getAddressAsLong()); + clientSession.setDetails(clientSessionDetails); - @Override - public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, - String apId) { + clientSession = clientServiceInterface.updateSession(clientSession); + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + ClientSessionDetails clientSessionDetails = clientSession.getDetails(); + clientSessionDetails.setAssociationState(AssociationState._802_11_Associated); + clientSessionDetails.setAssocTimestamp(System.currentTimeMillis()); + clientSessionDetails.setSessionId(clientInstance.getMacAddress().getAddressAsLong()); + clientSession.getDetails().mergeSession(clientSessionDetails); - if (ovsdbSession == null) { - LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + clientSession = clientServiceInterface.updateSession(clientSession); - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); + } - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } - - Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); - - if (ce == null) { - LOG.debug("wifiAssociatedClientsDbTableUpdate Cannot get customer Equipment for {}", apId); - return; - } - - if ((wifiAssociatedClients == null) || wifiAssociatedClients.isEmpty()) { - return; - } - - for (OpensyncWifiAssociatedClients opensyncWifiAssociatedClients : wifiAssociatedClients) { - com.telecominfraproject.wlan.client.models.Client clientInstance = clientServiceInterface - .getOrNull(customerId, new MacAddress(opensyncWifiAssociatedClients.getMac())); - - boolean isReassociation = true; - if (clientInstance == null) { - clientInstance = new com.telecominfraproject.wlan.client.models.Client(); + } - clientInstance.setCustomerId(customerId); - clientInstance.setMacAddress(new MacAddress(opensyncWifiAssociatedClients.getMac())); - clientInstance.setDetails(new ClientInfoDetails()); - clientInstance = clientServiceInterface.create(clientInstance); + @Override + public void awlanNodeDbTableUpdate(OpensyncAWLANNode opensyncAPState, String apId) { - isReassociation = false; + LOG.debug("AP {} table AWLAN_Node updated {}", apId, opensyncAPState); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - } - ClientInfoDetails clientDetails = (ClientInfoDetails) clientInstance.getDetails(); + if (ovsdbSession == null) { + LOG.debug("awlanNodeDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - clientInstance.setDetails(clientDetails); + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); - clientInstance = clientServiceInterface.update(clientInstance); + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("awlanNodeDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", customerId, + equipmentId, apId); + return; + } + + int upgradeStatusFromAp = opensyncAPState.getUpgradeStatus(); + EquipmentUpgradeState fwUpgradeState = null; + FailureReason fwUpgradeFailureReason = null; + + if (opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) + || opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) + || opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) + || opensyncAPState.getFirmwareUrl().equals("")) { + + fwUpgradeState = EquipmentUpgradeState.undefined; + + } else { + fwUpgradeState = OvsdbToWlanCloudTypeMappingUtility + .getCloudEquipmentUpgradeStateFromOpensyncUpgradeStatus(upgradeStatusFromAp); + + if (upgradeStatusFromAp < 0) { + fwUpgradeFailureReason = OvsdbToWlanCloudTypeMappingUtility + .getCloudEquipmentUpgradeFailureReasonFromOpensyncUpgradeStatus(upgradeStatusFromAp); + } + } + + Status protocolStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL); + if (protocolStatus == null) { + protocolStatus = new Status(); + protocolStatus.setCustomerId(customerId); + protocolStatus.setEquipmentId(equipmentId); + protocolStatus.setStatusDataType(StatusDataType.PROTOCOL); + EquipmentProtocolStatusData protocolStatusData = new EquipmentProtocolStatusData(); + protocolStatus.setDetails(protocolStatusData); + + protocolStatus = statusServiceInterface.update(protocolStatus); + + } + + String reportedFwImageName = null; + String reportedAltFwImageName = null; + + if (opensyncAPState.getVersionMatrix().containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { + reportedFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY); + } else { + reportedFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_NAME_KEY); + + } + + if (opensyncAPState.getVersionMatrix().containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { + reportedAltFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY); + } else { + reportedAltFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_NAME_KEY); + + } + + EquipmentProtocolStatusData protocolStatusData = (EquipmentProtocolStatusData) protocolStatus.getDetails(); + protocolStatusData.setReportedSku(opensyncAPState.getSkuNumber()); + if (reportedFwImageName != null) { + protocolStatusData.setReportedSwVersion(reportedFwImageName); + } + protocolStatusData.setReportedSwAltVersion(reportedAltFwImageName); + protocolStatusData.setReportedHwVersion(opensyncAPState.getPlatformVersion()); + protocolStatusData.setSystemName(opensyncAPState.getModel()); + + List updates = new ArrayList<>(); + + // only post update if there is a change + if (!((EquipmentProtocolStatusData) statusServiceInterface + .getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL).getDetails()).equals(protocolStatusData)) { + protocolStatus.setDetails(protocolStatusData); + updates.add(protocolStatus); + } + + Status firmwareStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.FIRMWARE); + if (firmwareStatus == null) { + firmwareStatus = new Status(); + firmwareStatus.setCustomerId(customerId); + firmwareStatus.setEquipmentId(equipmentId); + firmwareStatus.setStatusDataType(StatusDataType.FIRMWARE); + firmwareStatus.setDetails(new EquipmentUpgradeStatusData()); + firmwareStatus = statusServiceInterface.update(firmwareStatus); + + } + + Equipment ce = getCustomerEquipment(apId); + if (ce != null) { + ce.getDetails(); + + if (fwUpgradeState.equals(EquipmentUpgradeState.up_to_date)) { + LOG.info("Firmware load is up to date."); + + EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus + .getDetails(); + if (reportedFwImageName != null) { + if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) + || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) + || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { + firmwareStatusData.setActiveSwVersion(reportedFwImageName); + firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); + firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); + firmwareStatus.setDetails(firmwareStatusData); + updates.add(firmwareStatus); + } + + } + + if (!updates.isEmpty()) { // may be some updates from protocol + // status + updates = statusServiceInterface.update(updates); + } + + } else if (fwUpgradeState.equals(EquipmentUpgradeState.download_complete) + || fwUpgradeState.equals(EquipmentUpgradeState.apply_complete) + || fwUpgradeState.equals(EquipmentUpgradeState.apply_initiated) + || fwUpgradeState.equals(EquipmentUpgradeState.applying) + || fwUpgradeState.equals(EquipmentUpgradeState.downloading) + || fwUpgradeState.equals(EquipmentUpgradeState.download_initiated) + || fwUpgradeState.equals(EquipmentUpgradeState.reboot_initiated) + || fwUpgradeState.equals(EquipmentUpgradeState.rebooting)) { + + LOG.info("Firmware upgrade is in state {}", fwUpgradeState); + + EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus + .getDetails(); + if (reportedFwImageName != null) { + if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) + || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) + || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { + firmwareStatusData.setActiveSwVersion(reportedFwImageName); + firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); + firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); + if (fwUpgradeState.equals(EquipmentUpgradeState.apply_initiated)) { + firmwareStatusData.setUpgradeStartTime(System.currentTimeMillis()); + } else if (fwUpgradeState.equals(EquipmentUpgradeState.reboot_initiated) + || fwUpgradeState.equals(EquipmentUpgradeState.rebooting)) { + firmwareStatusData.setRebooted(true); + } + firmwareStatus.setDetails(firmwareStatusData); + updates.add(firmwareStatus); + } + } + + if (!updates.isEmpty()) {// may be some updates from protocol + // status + updates = statusServiceInterface.update(updates); + } + + // no other action here, these are just transient states + + } else if (fwUpgradeState.equals(EquipmentUpgradeState.apply_failed) + || fwUpgradeState.equals(EquipmentUpgradeState.download_failed) + || fwUpgradeState.equals(EquipmentUpgradeState.reboot_failed)) { + LOG.warn("Firmware upgrade is in a failed state {} due to {}", fwUpgradeState, fwUpgradeFailureReason); + + EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus + .getDetails(); + if (reportedFwImageName != null) { + if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) + || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName) + || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) + || !firmwareStatusData.getReason().equals(fwUpgradeFailureReason)) { + firmwareStatusData.setActiveSwVersion(reportedFwImageName); + firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); + firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); + firmwareStatus.setDetails(firmwareStatusData); + updates.add(firmwareStatus); + updates = statusServiceInterface.update(updates); + reconcileFwVersionToTrack(ce, reportedFwImageName, opensyncAPState.getModel()); + } else { + if (!updates.isEmpty()) { + updates = statusServiceInterface.update(updates); + } + } + + } else { + if (!updates.isEmpty()) {// may be some updates from + // protocol + // status + updates = statusServiceInterface.update(updates); + } + } + + } else { + LOG.info("Firmware upgrade state is {}", fwUpgradeState); + EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus + .getDetails(); + if (reportedFwImageName != null) { + if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) + || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) + || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { + firmwareStatusData.setActiveSwVersion(reportedFwImageName); + firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); + firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); + firmwareStatus.setDetails(firmwareStatusData); + updates.add(firmwareStatus); + updates = statusServiceInterface.update(updates); + } else { + if (!updates.isEmpty()) {// may be some updates from + // protocol + // status + updates = statusServiceInterface.update(updates); + } + } + } else { + if (!updates.isEmpty()) {// may be some updates from + // protocol + // status + updates = statusServiceInterface.update(updates); + } + + } + } + } + + } + + @Override + public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { + + LOG.info("wifiVIFStateDbTableDelete for AP {} rows {}", apId, vifStateTables); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession == null) { + LOG.debug("wifiVIFStateDbTableDelete::Cannot get Session for AP {}", apId); + return; + } + + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); + + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiVIFStateDbTableDelete::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } + + if (equipmentId < 0L) { + LOG.debug("wifiVIFStateDbTableDelete Cannot get equipmentId {} for session {}", equipmentId); + return; + } + + Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.ACTIVE_BSSIDS); + + if (activeBssidsStatus == null) { + return; // nothing to delete + + } + + ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); + + List bssidList = statusDetails.getActiveBSSIDs(); + List toBeDeleted = new ArrayList<>(); + Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); + List clientSessionsForCustomerAndEquipment = new ArrayList<>(); + if (ce != null) { + PaginationResponse clientSessions = clientServiceInterface.getSessionsForCustomer(customerId, + ImmutableSet.of(equipmentId), ImmutableSet.of(ce.getLocationId()), null, + new PaginationContext()); + clientSessionsForCustomerAndEquipment.addAll(clientSessions.getItems()); + } + for (OpensyncAPVIFState vifState : vifStateTables) { + + if (bssidList != null) { + for (ActiveBSSID activeBSSID : bssidList) { + if (activeBSSID.getBssid().equals(vifState.getMac()) + && activeBSSID.getSsid().equals(vifState.getSsid())) { + toBeDeleted.add(activeBSSID); + + } + } + } - ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, - clientInstance.getMacAddress()); + } - if (clientSession == null) { - clientSession = new ClientSession(); - clientSession.setCustomerId(customerId); - clientSession.setEquipmentId(equipmentId); - clientSession.setMacAddress(clientInstance.getMacAddress()); - clientSession.setLocationId(ce.getLocationId()); - ClientSessionDetails clientSessionDetails = new ClientSessionDetails(); - clientSessionDetails.setIsReassociation(isReassociation); - clientSessionDetails.setSessionId(clientInstance.getMacAddress().getAddressAsLong()); - clientSession.setDetails(clientSessionDetails); + bssidList.removeAll(toBeDeleted); - clientSession = clientServiceInterface.updateSession(clientSession); - } + statusDetails.setActiveBSSIDs(bssidList); - ClientSessionDetails clientSessionDetails = clientSession.getDetails(); - clientSessionDetails.setAssociationState(AssociationState._802_11_Associated); - clientSessionDetails.setAssocTimestamp(System.currentTimeMillis()); - clientSessionDetails.setSessionId(clientInstance.getMacAddress().getAddressAsLong()); - clientSession.getDetails().mergeSession(clientSessionDetails); + activeBssidsStatus.setDetails(statusDetails); - clientSession = clientServiceInterface.updateSession(clientSession); + activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - } + LOG.debug("wifiVIFStateDbTableDelete Updated activeBSSIDs {}", activeBssidsStatus); - } + } - @Override - public void awlanNodeDbTableUpdate(OpensyncAWLANNode opensyncAPState, String apId) { + @Override + public void wifiAssociatedClientsDbTableDelete(String deletedClientMac, String apId) { - LOG.debug("AP {} table AWLAN_Node updated {}", apId, opensyncAPState); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession == null) { - LOG.debug("awlanNodeDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + if (ovsdbSession == null) { + LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Session for AP {}", apId); + return; + } - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("awlanNodeDbTableUpdate::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", customerId, - equipmentId, apId); - return; - } - - int upgradeStatusFromAp = opensyncAPState.getUpgradeStatus(); - EquipmentUpgradeState fwUpgradeState = null; - FailureReason fwUpgradeFailureReason = null; - - if (opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) - || opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) - || opensyncAPState.getFirmwareUrl().equals(OvsdbStringConstants.OVSDB_AWLAN_AP_FACTORY_RESET) - || opensyncAPState.getFirmwareUrl().equals("")) { - - fwUpgradeState = EquipmentUpgradeState.undefined; - - } else { - fwUpgradeState = OvsdbToWlanCloudTypeMappingUtility - .getCloudEquipmentUpgradeStateFromOpensyncUpgradeStatus(upgradeStatusFromAp); - - if (upgradeStatusFromAp < 0) { - fwUpgradeFailureReason = OvsdbToWlanCloudTypeMappingUtility - .getCloudEquipmentUpgradeFailureReasonFromOpensyncUpgradeStatus(upgradeStatusFromAp); - } - } - - Status protocolStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL); - if (protocolStatus == null) { - protocolStatus = new Status(); - protocolStatus.setCustomerId(customerId); - protocolStatus.setEquipmentId(equipmentId); - protocolStatus.setStatusDataType(StatusDataType.PROTOCOL); - EquipmentProtocolStatusData protocolStatusData = new EquipmentProtocolStatusData(); - protocolStatus.setDetails(protocolStatusData); - - protocolStatus = statusServiceInterface.update(protocolStatus); - - } - - String reportedFwImageName = null; - String reportedAltFwImageName = null; - - if (opensyncAPState.getVersionMatrix().containsKey(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY)) { - reportedFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_ACTIVE_KEY); - } else { - reportedFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_NAME_KEY); - - } - - if (opensyncAPState.getVersionMatrix().containsKey(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY)) { - reportedAltFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_INACTIVE_KEY); - } else { - reportedAltFwImageName = opensyncAPState.getVersionMatrix().get(OvsdbStringConstants.FW_IMAGE_NAME_KEY); - - } - - EquipmentProtocolStatusData protocolStatusData = (EquipmentProtocolStatusData) protocolStatus.getDetails(); - protocolStatusData.setReportedSku(opensyncAPState.getSkuNumber()); - if (reportedFwImageName != null) { - protocolStatusData.setReportedSwVersion(reportedFwImageName); - } - protocolStatusData.setReportedSwAltVersion(reportedAltFwImageName); - protocolStatusData.setReportedHwVersion(opensyncAPState.getPlatformVersion()); - protocolStatusData.setSystemName(opensyncAPState.getModel()); - - List updates = new ArrayList<>(); - - // only post update if there is a change - if (!((EquipmentProtocolStatusData) statusServiceInterface - .getOrNull(customerId, equipmentId, StatusDataType.PROTOCOL).getDetails()).equals(protocolStatusData)) { - protocolStatus.setDetails(protocolStatusData); - updates.add(protocolStatus); - } - - Status firmwareStatus = statusServiceInterface.getOrNull(customerId, equipmentId, StatusDataType.FIRMWARE); - if (firmwareStatus == null) { - firmwareStatus = new Status(); - firmwareStatus.setCustomerId(customerId); - firmwareStatus.setEquipmentId(equipmentId); - firmwareStatus.setStatusDataType(StatusDataType.FIRMWARE); - firmwareStatus.setDetails(new EquipmentUpgradeStatusData()); - firmwareStatus = statusServiceInterface.update(firmwareStatus); - - } - - Equipment ce = getCustomerEquipment(apId); - if (ce != null) { - ce.getDetails(); - - if (fwUpgradeState.equals(EquipmentUpgradeState.up_to_date)) { - LOG.info("Firmware load is up to date."); - - EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus - .getDetails(); - if (reportedFwImageName != null) { - if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) - || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) - || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { - firmwareStatusData.setActiveSwVersion(reportedFwImageName); - firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); - firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); - firmwareStatus.setDetails(firmwareStatusData); - updates.add(firmwareStatus); - } - - } - - if (!updates.isEmpty()) { // may be some updates from protocol - // status - updates = statusServiceInterface.update(updates); - } - - } else if (fwUpgradeState.equals(EquipmentUpgradeState.download_complete) - || fwUpgradeState.equals(EquipmentUpgradeState.apply_complete) - || fwUpgradeState.equals(EquipmentUpgradeState.apply_initiated) - || fwUpgradeState.equals(EquipmentUpgradeState.applying) - || fwUpgradeState.equals(EquipmentUpgradeState.downloading) - || fwUpgradeState.equals(EquipmentUpgradeState.download_initiated) - || fwUpgradeState.equals(EquipmentUpgradeState.reboot_initiated) - || fwUpgradeState.equals(EquipmentUpgradeState.rebooting)) { - - LOG.info("Firmware upgrade is in state {}", fwUpgradeState); - - EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus - .getDetails(); - if (reportedFwImageName != null) { - if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) - || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) - || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { - firmwareStatusData.setActiveSwVersion(reportedFwImageName); - firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); - firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); - if (fwUpgradeState.equals(EquipmentUpgradeState.apply_initiated)) { - firmwareStatusData.setUpgradeStartTime(System.currentTimeMillis()); - } else if (fwUpgradeState.equals(EquipmentUpgradeState.reboot_initiated) - || fwUpgradeState.equals(EquipmentUpgradeState.rebooting)) { - firmwareStatusData.setRebooted(true); - } - firmwareStatus.setDetails(firmwareStatusData); - updates.add(firmwareStatus); - } - } - - if (!updates.isEmpty()) {// may be some updates from protocol - // status - updates = statusServiceInterface.update(updates); - } - - // no other action here, these are just transient states - - } else if (fwUpgradeState.equals(EquipmentUpgradeState.apply_failed) - || fwUpgradeState.equals(EquipmentUpgradeState.download_failed) - || fwUpgradeState.equals(EquipmentUpgradeState.reboot_failed)) { - LOG.warn("Firmware upgrade is in a failed state {} due to {}", fwUpgradeState, fwUpgradeFailureReason); - - EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus - .getDetails(); - if (reportedFwImageName != null) { - if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) - || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName) - || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) - || !firmwareStatusData.getReason().equals(fwUpgradeFailureReason)) { - firmwareStatusData.setActiveSwVersion(reportedFwImageName); - firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); - firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); - firmwareStatus.setDetails(firmwareStatusData); - updates.add(firmwareStatus); - updates = statusServiceInterface.update(updates); - reconcileFwVersionToTrack(ce, reportedFwImageName, opensyncAPState.getModel()); - } else { - if (!updates.isEmpty()) { - updates = statusServiceInterface.update(updates); - } - } - - } else { - if (!updates.isEmpty()) {// may be some updates from - // protocol - // status - updates = statusServiceInterface.update(updates); - } - } - - } else { - LOG.info("Firmware upgrade state is {}", fwUpgradeState); - EquipmentUpgradeStatusData firmwareStatusData = (EquipmentUpgradeStatusData) firmwareStatus - .getDetails(); - if (reportedFwImageName != null) { - if (!firmwareStatusData.getActiveSwVersion().equals(reportedFwImageName) - || !firmwareStatusData.getUpgradeState().equals(fwUpgradeState) - || !firmwareStatusData.getAlternateSwVersion().equals(reportedAltFwImageName)) { - firmwareStatusData.setActiveSwVersion(reportedFwImageName); - firmwareStatusData.setAlternateSwVersion(reportedAltFwImageName); - firmwareStatusData.setUpgradeState(fwUpgradeState, fwUpgradeFailureReason); - firmwareStatus.setDetails(firmwareStatusData); - updates.add(firmwareStatus); - updates = statusServiceInterface.update(updates); - } else { - if (!updates.isEmpty()) {// may be some updates from - // protocol - // status - updates = statusServiceInterface.update(updates); - } - } - } else { - if (!updates.isEmpty()) {// may be some updates from - // protocol - // status - updates = statusServiceInterface.update(updates); - } - - } - } - } - - } - - @Override - public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { - - LOG.info("wifiVIFStateDbTableDelete for AP {} rows {}", apId, vifStateTables); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession == null) { - LOG.debug("wifiVIFStateDbTableDelete::Cannot get Session for AP {}", apId); - return; - } - - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); - - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiVIFStateDbTableDelete::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } - - if (equipmentId < 0L) { - LOG.debug("wifiVIFStateDbTableDelete Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); - - if (activeBssidsStatus == null) { - return; // nothing to delete - - } - - ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); - - List bssidList = statusDetails.getActiveBSSIDs(); - List toBeDeleted = new ArrayList<>(); - Equipment ce = equipmentServiceInterface.getOrNull(equipmentId); - List clientSessionsForCustomerAndEquipment = new ArrayList<>(); - if (ce != null) { - PaginationResponse clientSessions = clientServiceInterface.getSessionsForCustomer(customerId, - ImmutableSet.of(equipmentId), ImmutableSet.of(ce.getLocationId()), null, - new PaginationContext()); - clientSessionsForCustomerAndEquipment.addAll(clientSessions.getItems()); - } - for (OpensyncAPVIFState vifState : vifStateTables) { - - if (bssidList != null) { - for (ActiveBSSID activeBSSID : bssidList) { - if (activeBSSID.getBssid().equals(vifState.getMac()) - && activeBSSID.getSsid().equals(vifState.getSsid())) { - toBeDeleted.add(activeBSSID); - - } - } - } - - } - - bssidList.removeAll(toBeDeleted); - - statusDetails.setActiveBSSIDs(bssidList); - - activeBssidsStatus.setDetails(statusDetails); - - activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - - LOG.debug("wifiVIFStateDbTableDelete Updated activeBSSIDs {}", activeBssidsStatus); - - } - - @Override - public void wifiAssociatedClientsDbTableDelete(String deletedClientMac, String apId) { + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + Set macAddressSet = new HashSet<>(); + macAddressSet.add(new MacAddress(deletedClientMac)); + List clientSessionList = clientServiceInterface.getSessions(customerId, macAddressSet); - if (ovsdbSession == null) { - LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Session for AP {}", apId); - return; - } + for (ClientSession session : clientSessionList) { - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); + ClientSessionDetails clientSessionDetails = session.getDetails(); - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } + if ((clientSessionDetails.getAssociationState() != null) + && !clientSessionDetails.getAssociationState().equals(AssociationState.Disconnected)) { + clientSessionDetails.setDisconnectByClientTimestamp(System.currentTimeMillis()); + clientSessionDetails.setAssociationState(AssociationState.Disconnected); - Set macAddressSet = new HashSet<>(); - macAddressSet.add(new MacAddress(deletedClientMac)); - List clientSessionList = clientServiceInterface.getSessions(customerId, macAddressSet); + session.setDetails(clientSessionDetails); + session = clientServiceInterface.updateSession(session); - for (ClientSession session : clientSessionList) { + if (LOG.isTraceEnabled()) { + LOG.trace("wifiAssociatedClientsDbTableDelete Updated client session, set to disconnected {}", + session.toPrettyString()); + } + } - ClientSessionDetails clientSessionDetails = session.getDetails(); + } - if ((clientSessionDetails.getAssociationState() != null) - && !clientSessionDetails.getAssociationState().equals(AssociationState.Disconnected)) { - clientSessionDetails.setDisconnectByClientTimestamp(System.currentTimeMillis()); - clientSessionDetails.setAssociationState(AssociationState.Disconnected); + } - session.setDetails(clientSessionDetails); - session = clientServiceInterface.updateSession(session); + @Override + public void dhcpLeasedIpDbTableUpdate(List> dhcpAttributes, String apId, + RowUpdateOperation rowUpdateOperation) { - if (LOG.isTraceEnabled()) { - LOG.trace("wifiAssociatedClientsDbTableDelete Updated client session, set to disconnected {}", - session.toPrettyString()); - } - } + LOG.info("dhcpLeasedIpDbTableUpdate {} operations on AP {} ", rowUpdateOperation, apId); - } + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - } + if (ovsdbSession == null) { + LOG.debug("updateDhcpIpClientFingerprints::Cannot get Session for AP {}", apId); + return; + } - @Override - public void dhcpLeasedIpDbTableUpdate(List> dhcpAttributes, String apId, - RowUpdateOperation rowUpdateOperation) { + int customerId = ovsdbSession.getCustomerId(); + long equipmentId = ovsdbSession.getEquipmentId(); - LOG.info("dhcpLeasedIpDbTableUpdate {} operations on AP {} ", rowUpdateOperation, apId); + if ((customerId < 0) || (equipmentId < 0)) { + LOG.debug("updateDhcpIpClientFingerprints::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", + customerId, equipmentId, apId); + return; + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + Equipment ce = getCustomerEquipment(apId); - if (ovsdbSession == null) { - LOG.debug("updateDhcpIpClientFingerprints::Cannot get Session for AP {}", apId); - return; - } + if (ce == null) { + LOG.debug("updateDhcpIpClientFingerprints::Cannot get Equipment for AP {}", apId); + return; + } - int customerId = ovsdbSession.getCustomerId(); - long equipmentId = ovsdbSession.getEquipmentId(); + long locationId = ce.getLocationId(); - if ((customerId < 0) || (equipmentId < 0)) { - LOG.debug("updateDhcpIpClientFingerprints::Cannot get valid CustomerId {} or EquipmentId {} for AP {}", - customerId, equipmentId, apId); - return; - } + if (rowUpdateOperation.equals(RowUpdateOperation.INSERT)) { - Equipment ce = getCustomerEquipment(apId); + List clientSessionList = new ArrayList<>(); + for (Map dhcpLeasedIps : dhcpAttributes) { + if (!dhcpLeasedIps.containsKey("hwaddr")) { - if (ce == null) { - LOG.debug("updateDhcpIpClientFingerprints::Cannot get Equipment for AP {}", apId); - return; - } + LOG.info("Cannot insert a client {} that has no hwaddr.", dhcpLeasedIps); + continue; - long locationId = ce.getLocationId(); + } - //         "hwaddr": - //         "inet_addr": - //         "hostname": - //         "fingerprint": - //         "vendor_class": - //         "lease_time": - //         "subnet_mask": - //         "gateway": - //         "dhcp_server": - //         "primary_dns": - //         "secondary_dns": - //         "db_status": - //         "device_name": - //         "device_type": - //         "manuf_id": + MacAddress clientMacAddress = new MacAddress(dhcpLeasedIps.get("hwaddr")); + if (clientMacAddress.equals(equipmentServiceInterface.get(equipmentId).getBaseMacAddress())) { + LOG.info("Not a client device {} ", dhcpLeasedIps); + com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface + .getOrNull(customerId, clientMacAddress); + if (client != null) { - if (rowUpdateOperation.equals(RowUpdateOperation.INSERT)) { + // In case somehow this equipment has accidentally been + // tagged as a client, remove - List clientSessionList = new ArrayList<>(); - for (Map dhcpLeasedIps : dhcpAttributes) { - if (!dhcpLeasedIps.containsKey("hwaddr")) { + ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, + clientMacAddress); - LOG.info("Cannot insert a client {} that has no hwaddr.", dhcpLeasedIps); - continue; + if (clientSession != null) { + LOG.info("Deleting invalid client session {}", + clientServiceInterface.deleteSession(customerId, equipmentId, clientMacAddress)); + } - } + LOG.info("Deleting invalid client {}", + clientServiceInterface.delete(customerId, clientMacAddress)); - MacAddress clientMacAddress = new MacAddress(dhcpLeasedIps.get("hwaddr")); - if (clientMacAddress.equals(equipmentServiceInterface.get(equipmentId).getBaseMacAddress())) { - LOG.info("Not a client device {} ", dhcpLeasedIps); - com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, - clientMacAddress); - if (client != null) { + } + continue; + } + com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, + clientMacAddress); + if (client != null) { + LOG.info("Client {} already exists on the cloud, update client values", dhcpLeasedIps); - // In case somehow this equipment has accidentally been tagged as a client, remove - - ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, clientMacAddress); - - if (clientSession != null) { - LOG.info("Deleting invalid client session {}", clientServiceInterface.deleteSession(customerId, equipmentId, clientMacAddress)); - } - - LOG.info("Deleting invalid client {}", clientServiceInterface.delete(customerId, clientMacAddress)); + ClientInfoDetails clientDetails = (ClientInfoDetails) client.getDetails(); + if (dhcpLeasedIps.containsKey("hostname")) { - - } - continue; - } - com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, - clientMacAddress); - if (client != null) { - LOG.info("Client {} already exists on the cloud, update client values", dhcpLeasedIps); + clientDetails.setHostName(dhcpLeasedIps.get("hostname")); - ClientInfoDetails clientDetails = (ClientInfoDetails) client.getDetails(); - if (dhcpLeasedIps.containsKey("hostname")) { + } - clientDetails.setHostName(dhcpLeasedIps.get("hostname")); + if (dhcpLeasedIps.containsKey("fingerprint")) { - } + clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); + } - if (dhcpLeasedIps.containsKey("fingerprint")) { + if (dhcpLeasedIps.containsKey("device_type")) { - clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); - } + DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType + .getByName(dhcpLeasedIps.get("device_type")); + ClientType clientType = OvsdbToWlanCloudTypeMappingUtility + .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); - if (dhcpLeasedIps.containsKey("device_type")) { + LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); - DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType - .getByName(dhcpLeasedIps.get("device_type")); - ClientType clientType = OvsdbToWlanCloudTypeMappingUtility - .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); + clientDetails.setClientType(clientType.getId()); - LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); + } - clientDetails.setClientType(clientType.getId()); + client.setDetails(clientDetails); - } + client = clientServiceInterface.update(client); - client.setDetails(clientDetails); + LOG.info("Updated Client {}.", client); - client = clientServiceInterface.update(client); + // In this case, we might have a session, as the client + // already exists on the cloud, update if required + ClientSession session = updateClientSession(customerId, equipmentId, locationId, dhcpLeasedIps, + clientMacAddress); + if (session != null) { + clientSessionList.add(session); - LOG.info("Updated Client {}.", client); + } - // In this case, we might have a session, as the client - // already exists on the cloud, update if required - ClientSession session = updateClientSession(customerId, equipmentId, locationId, dhcpLeasedIps, - clientMacAddress); - if (session != null) { - clientSessionList.add(session); + } else { - } + client = new com.telecominfraproject.wlan.client.models.Client(); - } else { + client.setCustomerId(customerId); + client.setMacAddress(clientMacAddress); - client = new com.telecominfraproject.wlan.client.models.Client(); + ClientInfoDetails clientDetails = new ClientInfoDetails(); - client.setCustomerId(customerId); - client.setMacAddress(clientMacAddress); + if (dhcpLeasedIps.containsKey("hostname")) { - ClientInfoDetails clientDetails = new ClientInfoDetails(); + clientDetails.setHostName(dhcpLeasedIps.get("hostname")); - if (dhcpLeasedIps.containsKey("hostname")) { + } - clientDetails.setHostName(dhcpLeasedIps.get("hostname")); + if (dhcpLeasedIps.containsKey("fingerprint")) { - } + clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); + } - if (dhcpLeasedIps.containsKey("fingerprint")) { + if (dhcpLeasedIps.containsKey("device_type")) { - clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); - } + DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType + .getByName(dhcpLeasedIps.get("device_type")); + ClientType clientType = OvsdbToWlanCloudTypeMappingUtility + .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); - if (dhcpLeasedIps.containsKey("device_type")) { + LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); - DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType - .getByName(dhcpLeasedIps.get("device_type")); - ClientType clientType = OvsdbToWlanCloudTypeMappingUtility - .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); + clientDetails.setClientType(clientType.getId()); - LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); + } - clientDetails.setClientType(clientType.getId()); + client.setDetails(clientDetails); - } + client = clientServiceInterface.create(client); - client.setDetails(clientDetails); + LOG.info("Created Client {}.", client); + } - client = clientServiceInterface.create(client); + // we might have a session, update if required + ClientSession session = updateClientSession(customerId, equipmentId, locationId, dhcpLeasedIps, + clientMacAddress); + if (session != null) { + clientSessionList.add(session); + } - LOG.info("Created Client {}.", client); - } + } - } + if (!clientSessionList.isEmpty()) { + LOG.info("Updating client sessions {}", clientSessionList); + clientSessionList = clientServiceInterface.updateSessions(clientSessionList); + LOG.info("Updated client sessions {}", clientSessionList); + } - if (!clientSessionList.isEmpty()) { - LOG.info("Updating client sessions {}", clientSessionList); - clientSessionList = clientServiceInterface.updateSessions(clientSessionList); - LOG.info("Updated client sessions {}", clientSessionList); - } + } else if (rowUpdateOperation.equals(RowUpdateOperation.MODIFY) + || rowUpdateOperation.equals(RowUpdateOperation.INIT)) { - } else if (rowUpdateOperation.equals(RowUpdateOperation.MODIFY) - || rowUpdateOperation.equals(RowUpdateOperation.INIT)) { + List clientSessionList = new ArrayList<>(); - List clientSessionList = new ArrayList<>(); + for (Map dhcpLeasedIps : dhcpAttributes) { - for (Map dhcpLeasedIps : dhcpAttributes) { + if (!dhcpLeasedIps.containsKey("hwaddr")) { - if (!dhcpLeasedIps.containsKey("hwaddr")) { + LOG.info("Cannot update a client {} that has no hwaddr.", dhcpLeasedIps); + continue; - LOG.info("Cannot update a client {} that has no hwaddr.", dhcpLeasedIps); - continue; + } - } + MacAddress clientMacAddress = new MacAddress(dhcpLeasedIps.get("hwaddr")); - MacAddress clientMacAddress = new MacAddress(dhcpLeasedIps.get("hwaddr")); - - if (clientMacAddress.equals(equipmentServiceInterface.get(equipmentId).getBaseMacAddress())) { + if (clientMacAddress.equals(equipmentServiceInterface.get(equipmentId).getBaseMacAddress())) { - LOG.info("Not a client device {} ", dhcpLeasedIps); - com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, - clientMacAddress); - if (client != null) { + LOG.info("Not a client device {} ", dhcpLeasedIps); + com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface + .getOrNull(customerId, clientMacAddress); + if (client != null) { - // In case somehow this equipment has accidentally been tagged as a client, remove - - ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, clientMacAddress); - - if (clientSession != null) { - LOG.info("Deleting invalid client session {}", clientServiceInterface.deleteSession(customerId, equipmentId, clientMacAddress)); - } - - LOG.info("Deleting invalid client {}", clientServiceInterface.delete(customerId, clientMacAddress)); + // In case somehow this equipment has accidentally been + // tagged as a client, remove - - } - continue; - - } - - com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, - clientMacAddress); - if (client == null) { - LOG.info("Client {} does not exist on the cloud. Creating...", dhcpLeasedIps); - client = new com.telecominfraproject.wlan.client.models.Client(); - client.setCustomerId(customerId); - client.setMacAddress(clientMacAddress); - ClientInfoDetails clientDetails = new ClientInfoDetails(); + ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, + clientMacAddress); - client.setDetails(clientDetails); + if (clientSession != null) { + LOG.info("Deleting invalid client session {}", + clientServiceInterface.deleteSession(customerId, equipmentId, clientMacAddress)); + } - client = clientServiceInterface.create(client); + LOG.info("Deleting invalid client {}", + clientServiceInterface.delete(customerId, clientMacAddress)); - } + } + continue; - ClientInfoDetails clientDetails = (ClientInfoDetails) client.getDetails(); - if (dhcpLeasedIps.containsKey("hostname")) { + } - clientDetails.setHostName(dhcpLeasedIps.get("hostname")); + com.telecominfraproject.wlan.client.models.Client client = clientServiceInterface.getOrNull(customerId, + clientMacAddress); + if (client == null) { + LOG.info("Client {} does not exist on the cloud. Creating...", dhcpLeasedIps); + client = new com.telecominfraproject.wlan.client.models.Client(); + client.setCustomerId(customerId); + client.setMacAddress(clientMacAddress); + ClientInfoDetails clientDetails = new ClientInfoDetails(); - } + client.setDetails(clientDetails); - if (dhcpLeasedIps.containsKey("fingerprint")) { + client = clientServiceInterface.create(client); - clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); - } + } - if (dhcpLeasedIps.containsKey("device_type")) { + ClientInfoDetails clientDetails = (ClientInfoDetails) client.getDetails(); + if (dhcpLeasedIps.containsKey("hostname")) { - DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType.getByName(dhcpLeasedIps.get("device_type")); - ClientType clientType = OvsdbToWlanCloudTypeMappingUtility - .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); + clientDetails.setHostName(dhcpLeasedIps.get("hostname")); - LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); + } - clientDetails.setClientType(clientType.getId()); + if (dhcpLeasedIps.containsKey("fingerprint")) { - } + clientDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); + } - client.setDetails(clientDetails); + if (dhcpLeasedIps.containsKey("device_type")) { - client = clientServiceInterface.update(client); + DhcpFpDeviceType dhcpFpDeviceType = DhcpFpDeviceType.getByName(dhcpLeasedIps.get("device_type")); + ClientType clientType = OvsdbToWlanCloudTypeMappingUtility + .getClientTypeForDhcpFpDeviceType(dhcpFpDeviceType); - LOG.info("Updated Client {}.", client); + LOG.debug("Translate from ovsdb {} to cloud {}", dhcpFpDeviceType, clientType); - // check if there is a session for this client + clientDetails.setClientType(clientType.getId()); - ClientSession session = updateClientSession(customerId, equipmentId, locationId, dhcpLeasedIps, - clientMacAddress); - if (session != null) { - clientSessionList.add(session); + } - } + client.setDetails(clientDetails); - } + client = clientServiceInterface.update(client); - if (!clientSessionList.isEmpty()) { - LOG.info("Updating client sessions {}", clientSessionList); - clientSessionList = clientServiceInterface.updateSessions(clientSessionList); - LOG.info("Updated client sessions {}", clientSessionList); - } + LOG.info("Updated Client {}.", client); - } else if (rowUpdateOperation.equals(RowUpdateOperation.DELETE)) { - // Client should not be 'deleted' from Cloud - LOG.debug("Recieved deletions, not removing client(s) from cloud", dhcpAttributes); - } + // check if there is a session for this client - } - - protected ClientSession updateClientSession(int customerId, long equipmentId, long locationId, - Map dhcpLeasedIps, MacAddress clientMacAddress) { - ClientSession session = clientServiceInterface.getSessionOrNull(customerId, equipmentId, clientMacAddress); - - //         "hwaddr": -- - //         "inet_addr": -- - //         "hostname": -- - //         "fingerprint": -- - //         "vendor_class": -- - //         "lease_time": -- - //         "subnet_mask": -- - //         "gateway": -- - //         "dhcp_server": -- - //         "primary_dns": -- - //         "secondary_dns": -- - //         "db_status": - //         "device_name": - //         "device_type": - //         "manuf_id": - - if (session == null) { - session = new ClientSession(); - } - session.setCustomerId(customerId); - session.setEquipmentId(equipmentId); - session.setLocationId(locationId); - session.setMacAddress(clientMacAddress); - session.setDetails(new ClientSessionDetails()); - - ClientSessionDetails clientSessionDetails = new ClientSessionDetails(); - - if (dhcpLeasedIps.containsKey("fingerprint")) { - - clientSessionDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); - } - - if (dhcpLeasedIps.containsKey("inet_addr")) { - - try { - clientSessionDetails.setIpAddress(InetAddress.getByName(dhcpLeasedIps.get("inet_addr"))); - } catch (UnknownHostException e) { - LOG.error("Invalid Client IP", e); - } - - } - - if (dhcpLeasedIps.containsKey("hostname")) { - - clientSessionDetails.setHostname(dhcpLeasedIps.get("hostname")); - - } - - ClientDhcpDetails clientDhcpDetails = new ClientDhcpDetails(clientSessionDetails.getSessionId()); - - if (dhcpLeasedIps.containsKey("dhcp_server")) { - try { - clientDhcpDetails.setDhcpServerIp(InetAddress.getByName(dhcpLeasedIps.get("dhcp_server"))); - } catch (UnknownHostException e) { - LOG.error("Invalid DhcpServer", e); - } - } - - if (dhcpLeasedIps.containsKey("lease_time")) { - Integer leaseTime = Integer.valueOf(dhcpLeasedIps.get("lease_time")); - clientDhcpDetails.setLeaseTimeInSeconds(leaseTime); - } - - if (dhcpLeasedIps.containsKey("gateway")) { - try { - clientDhcpDetails.setGatewayIp(InetAddress.getByName(dhcpLeasedIps.get("gateway"))); - } catch (UnknownHostException e) { - LOG.error("Invalid Gateway IP", e); - - try { - clientDhcpDetails.setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("gateway").getBytes())); - } catch (UnknownHostException e1) { - // TODO Auto-generated catch block - LOG.error("Invalid Gateway Address", e); - } - - } - } - - if (dhcpLeasedIps.containsKey("subnet_mask")) { - try { - clientDhcpDetails.setSubnetMask(InetAddress.getByName(dhcpLeasedIps.get("subnet_mask"))); - } catch (UnknownHostException e) { - LOG.error("Invalid Subnet Mask", e); - try { - clientDhcpDetails - .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("subnet_mask").getBytes())); - } catch (UnknownHostException e1) { - // TODO Auto-generated catch block - LOG.error("Invalid Subnet Mask Address", e); - } - } - } - - if (dhcpLeasedIps.containsKey("primary_dns")) { - try { - clientDhcpDetails.setPrimaryDns(InetAddress.getByName(dhcpLeasedIps.get("primary_dns"))); - } catch (UnknownHostException e) { - LOG.error("Invalid Primary DNS", e); - try { - clientDhcpDetails - .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("primary_dns").getBytes())); - } catch (UnknownHostException e1) { - // TODO Auto-generated catch block - LOG.error("Invalid Primary DNS Address", e); - } - - } - } - - if (dhcpLeasedIps.containsKey("secondary_dns")) { - try { - clientDhcpDetails.setSecondaryDns(InetAddress.getByName(dhcpLeasedIps.get("secondary_dns"))); - } catch (UnknownHostException e) { - LOG.error("Invalid Secondary DNS", e); - try { - clientDhcpDetails - .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("secondary_dns").getBytes())); - } catch (UnknownHostException e1) { - // TODO Auto-generated catch block - LOG.error("Invalid Seconary DNS Address", e); - } - } - } - - if (dhcpLeasedIps.containsKey("device_name")) { - clientSessionDetails.setClassificationName(dhcpLeasedIps.get("device_name")); - } - - clientSessionDetails.setDhcpDetails(clientDhcpDetails); - - session.getDetails().mergeSession(clientSessionDetails); - - return session; - } - - @Override - public void commandStateDbTableUpdate(List> commandStateAttributes, String apId, - RowUpdateOperation rowUpdateOperation) { - LOG.info("Received Command_State row(s) {} rowUpdateOperation {} for ap {}", commandStateAttributes, - rowUpdateOperation, apId); - - // TODO: will handle changes from Command_State table - } + ClientSession session = updateClientSession(customerId, equipmentId, locationId, dhcpLeasedIps, + clientMacAddress); + if (session != null) { + clientSessionList.add(session); + + } + + } + + if (!clientSessionList.isEmpty()) { + LOG.info("Updating client sessions {}", clientSessionList); + clientSessionList = clientServiceInterface.updateSessions(clientSessionList); + LOG.info("Updated client sessions {}", clientSessionList); + } + + } else if (rowUpdateOperation.equals(RowUpdateOperation.DELETE)) { + // Client should not be 'deleted' from Cloud + LOG.debug("Recieved deletions, not removing client(s) from cloud", dhcpAttributes); + } + + } + + protected ClientSession updateClientSession(int customerId, long equipmentId, long locationId, + Map dhcpLeasedIps, MacAddress clientMacAddress) { + ClientSession session = clientServiceInterface.getSessionOrNull(customerId, equipmentId, clientMacAddress); + + //         "hwaddr": -- + //         "inet_addr": -- + //         "hostname": -- + //         "fingerprint": -- + //         "vendor_class": -- + //         "lease_time": -- + //         "subnet_mask": -- + //         "gateway": -- + //         "dhcp_server": -- + //         "primary_dns": -- + //         "secondary_dns": -- + //         "db_status": + //         "device_name": + //         "device_type": + //         "manuf_id": + + if (session == null) { + session = new ClientSession(); + } + session.setCustomerId(customerId); + session.setEquipmentId(equipmentId); + session.setLocationId(locationId); + session.setMacAddress(clientMacAddress); + session.setDetails(new ClientSessionDetails()); + + ClientSessionDetails clientSessionDetails = new ClientSessionDetails(); + + if (dhcpLeasedIps.containsKey("fingerprint")) { + + clientSessionDetails.setApFingerprint(dhcpLeasedIps.get("fingerprint")); + } + + if (dhcpLeasedIps.containsKey("inet_addr")) { + + try { + clientSessionDetails.setIpAddress(InetAddress.getByName(dhcpLeasedIps.get("inet_addr"))); + } catch (UnknownHostException e) { + LOG.error("Invalid Client IP", e); + } + + } + + if (dhcpLeasedIps.containsKey("hostname")) { + + clientSessionDetails.setHostname(dhcpLeasedIps.get("hostname")); + + } + + ClientDhcpDetails clientDhcpDetails = new ClientDhcpDetails(clientSessionDetails.getSessionId()); + + if (dhcpLeasedIps.containsKey("dhcp_server")) { + try { + clientDhcpDetails.setDhcpServerIp(InetAddress.getByName(dhcpLeasedIps.get("dhcp_server"))); + } catch (UnknownHostException e) { + LOG.error("Invalid DhcpServer", e); + } + } + + if (dhcpLeasedIps.containsKey("lease_time")) { + Integer leaseTime = Integer.valueOf(dhcpLeasedIps.get("lease_time")); + clientDhcpDetails.setLeaseTimeInSeconds(leaseTime); + } + + if (dhcpLeasedIps.containsKey("gateway")) { + try { + clientDhcpDetails.setGatewayIp(InetAddress.getByName(dhcpLeasedIps.get("gateway"))); + } catch (UnknownHostException e) { + LOG.error("Invalid Gateway IP", e); + + try { + clientDhcpDetails.setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("gateway").getBytes())); + } catch (UnknownHostException e1) { + // TODO Auto-generated catch block + LOG.error("Invalid Gateway Address", e); + } + + } + } + + if (dhcpLeasedIps.containsKey("subnet_mask")) { + try { + clientDhcpDetails.setSubnetMask(InetAddress.getByName(dhcpLeasedIps.get("subnet_mask"))); + } catch (UnknownHostException e) { + LOG.error("Invalid Subnet Mask", e); + try { + clientDhcpDetails + .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("subnet_mask").getBytes())); + } catch (UnknownHostException e1) { + // TODO Auto-generated catch block + LOG.error("Invalid Subnet Mask Address", e); + } + } + } + + if (dhcpLeasedIps.containsKey("primary_dns")) { + try { + clientDhcpDetails.setPrimaryDns(InetAddress.getByName(dhcpLeasedIps.get("primary_dns"))); + } catch (UnknownHostException e) { + LOG.error("Invalid Primary DNS", e); + try { + clientDhcpDetails + .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("primary_dns").getBytes())); + } catch (UnknownHostException e1) { + // TODO Auto-generated catch block + LOG.error("Invalid Primary DNS Address", e); + } + + } + } + + if (dhcpLeasedIps.containsKey("secondary_dns")) { + try { + clientDhcpDetails.setSecondaryDns(InetAddress.getByName(dhcpLeasedIps.get("secondary_dns"))); + } catch (UnknownHostException e) { + LOG.error("Invalid Secondary DNS", e); + try { + clientDhcpDetails + .setGatewayIp(InetAddress.getByAddress(dhcpLeasedIps.get("secondary_dns").getBytes())); + } catch (UnknownHostException e1) { + // TODO Auto-generated catch block + LOG.error("Invalid Seconary DNS Address", e); + } + } + } + + if (dhcpLeasedIps.containsKey("device_name")) { + clientSessionDetails.setClassificationName(dhcpLeasedIps.get("device_name")); + } + + clientSessionDetails.setDhcpDetails(clientDhcpDetails); + + session.getDetails().mergeSession(clientSessionDetails); + + return session; + } + + @Override + public void commandStateDbTableUpdate(List> commandStateAttributes, String apId, + RowUpdateOperation rowUpdateOperation) { + LOG.info("Received Command_State row(s) {} rowUpdateOperation {} for ap {}", commandStateAttributes, + rowUpdateOperation, apId); + + // TODO: will handle changes from Command_State table + } } diff --git a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/TipWlanOvsdbClient.java b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/TipWlanOvsdbClient.java index 9e3053e..433ce5a 100644 --- a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/TipWlanOvsdbClient.java +++ b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/TipWlanOvsdbClient.java @@ -104,7 +104,7 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { // successfully connected - register it in our // connectedClients table - + String key = alterClientCnIfRequired(clientCn, connectNodeInfo); ovsdbSessionMapInterface.newSession(key, ovsdbClient); @@ -132,7 +132,6 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { } - @Override public void disconnected(OvsdbClient ovsdbClient) { String remoteHost = ovsdbClient.getConnectionInfo().getRemoteAddress().getHostAddress(); @@ -192,22 +191,16 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { // connectedClients table String apId = alterClientCnIfRequired(clientCn, connectNodeInfo); - LOG.debug("Client connect for AP {}", apId); + LOG.debug("Client {} connect for AP {}", clientCn, apId); - OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); - -// try { -// ovsdbDao.provisionBridgePortInterface(ovsdbClient); -// } catch (Exception e) { -// LOG.warn("Could not provision Bridge->Port->Interface mapping.", e); -// } ovsdbDao.removeAllStatsConfigs(ovsdbClient); // always ovsdbDao.removeAllSsids(ovsdbClient); // always ovsdbDao.removeWifiRrm(ovsdbClient); + OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); + if (opensyncAPConfig != null) { ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); - ovsdbDao.configureInterfaces(ovsdbClient); ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); ovsdbDao.configureWifiRrm(ovsdbClient, opensyncAPConfig); if (opensyncAPConfig.getHotspotConfig() != null) { @@ -218,11 +211,14 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { ovsdbDao.enableNetworkProbeForSyntheticClient(ovsdbClient); } } - + + ovsdbDao.configureInterfaces(ovsdbClient); + if (ovsdbDao.getDeviceStatsReportingInterval(ovsdbClient) != collectionIntervalSecDeviceStats) { ovsdbDao.updateDeviceStatsReportingInterval(ovsdbClient, collectionIntervalSecDeviceStats); } + LOG.debug("Client connect Done"); return connectNodeInfo; } @@ -271,12 +267,13 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { ovsdbDao.removeAllStatsConfigs(ovsdbClient); // always ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); - ovsdbDao.configureInterfaces(ovsdbClient); ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); ovsdbDao.configureWifiRrm(ovsdbClient, opensyncAPConfig); if (opensyncAPConfig.getHotspotConfig() != null) { ovsdbDao.configureHotspots(ovsdbClient, opensyncAPConfig); } + ovsdbDao.configureInterfaces(ovsdbClient); + ovsdbDao.configureStatsFromProfile(ovsdbClient, opensyncAPConfig); if (ovsdbDao.getDeviceStatsReportingInterval(ovsdbClient) != collectionIntervalSecDeviceStats) { ovsdbDao.updateDeviceStatsReportingInterval(ovsdbClient, collectionIntervalSecDeviceStats); @@ -360,7 +357,8 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { CompletableFuture awCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, OvsdbDao.dhcpLeasedIpDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.dhcpLeasedIpDbTable, new MonitorRequest(new MonitorSelect(true, true, true, true)))), + new MonitorRequests(ImmutableMap.of(OvsdbDao.dhcpLeasedIpDbTable, + new MonitorRequest(new MonitorSelect(true, true, true, true)))), new MonitorCallback() { @Override @@ -425,15 +423,12 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { } - }); awCf.join(); - } - private void monitorCommandStateDbTable(OvsdbClient ovsdbClient, String key) throws OvsdbClientException { CompletableFuture csCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, @@ -450,7 +445,6 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { List> delete = new ArrayList<>(); List> update = new ArrayList<>(); - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { @@ -504,12 +498,10 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { } - }); csCf.join(); - } private void monitorAwlanNodeDbTable(OvsdbClient ovsdbClient, String key) throws OvsdbClientException { @@ -564,7 +556,6 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { } - // now address the update/add extIntegrationInterface.wifiAssociatedClientsDbTableUpdate(associatedClients, key); @@ -574,50 +565,48 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { acCf.join(); - } private void monitorWifiInetStateDbTable(OvsdbClient ovsdbClient, String key) throws OvsdbClientException { - CompletableFuture isCf = ovsdbClient - .monitor(OvsdbDao.ovsdbName, OvsdbDao.wifiInetStateDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiInetStateDbTable, - new MonitorRequest(new MonitorSelect(true, true, true, true)))), - new MonitorCallback() { + CompletableFuture isCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, + OvsdbDao.wifiInetStateDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiInetStateDbTable, + new MonitorRequest(new MonitorSelect(true, true, true, true)))), + new MonitorCallback() { - @Override - public void update(TableUpdates tableUpdates) { - LOG.info(OvsdbDao.ovsdbName, - OvsdbDao.wifiInetStateDbTable + "_" + key + " monitor callback received {}", - tableUpdates); + @Override + public void update(TableUpdates tableUpdates) { + LOG.info(OvsdbDao.ovsdbName, + OvsdbDao.wifiInetStateDbTable + "_" + key + " monitor callback received {}", + tableUpdates); - List inetStateInsertOrUpdate = new ArrayList<>(); - List inetStateDelete = new ArrayList<>(); + List inetStateInsertOrUpdate = new ArrayList<>(); + List inetStateDelete = new ArrayList<>(); - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - if (rowUpdate.getNew() == null) { - inetStateDelete.addAll(ovsdbDao - .getOpensyncApInetStateForRowUpdate(rowUpdate, key, ovsdbClient)); - } else { - inetStateInsertOrUpdate.addAll(ovsdbDao - .getOpensyncApInetStateForRowUpdate(rowUpdate, key, ovsdbClient)); - } - - } + if (rowUpdate.getNew() == null) { + inetStateDelete.addAll( + ovsdbDao.getOpensyncApInetStateForRowUpdate(rowUpdate, key, ovsdbClient)); + } else { + inetStateInsertOrUpdate.addAll( + ovsdbDao.getOpensyncApInetStateForRowUpdate(rowUpdate, key, ovsdbClient)); } - - // delete first - extIntegrationInterface.wifiInetStateDbTableUpdate(inetStateDelete, key); - - // now process updates and mutations - extIntegrationInterface.wifiInetStateDbTableUpdate(inetStateInsertOrUpdate, key); - } + } - }); + // delete first + extIntegrationInterface.wifiInetStateDbTableUpdate(inetStateDelete, key); + + // now process updates and mutations + extIntegrationInterface.wifiInetStateDbTableUpdate(inetStateInsertOrUpdate, key); + + } + + }); isCf.join(); } @@ -686,7 +675,6 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { } - } }); @@ -732,7 +720,7 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { try { ovsdbDao.configureFirmwareFlash(session.getOvsdbClient(), apId, firmwareVersion, username); } catch (Exception e) { - LOG.error("Failed to flash firmware for " + apId + " " + e.getLocalizedMessage()); + LOG.error("Failed to flash firmware for " + apId + " " + e.getLocalizedMessage()); return "Failed to flash firmware for " + apId + " " + e.getLocalizedMessage(); } @@ -841,7 +829,6 @@ public class TipWlanOvsdbClient implements OvsdbClientInterface { return "failed to trigger a factory reset of AP " + apId; } - } public String alterClientCnIfRequired(String clientCn, ConnectNodeInfo connectNodeInfo) { diff --git a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/dao/OvsdbDao.java b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/dao/OvsdbDao.java index 36304b5..417fb81 100644 --- a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/dao/OvsdbDao.java +++ b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/dao/OvsdbDao.java @@ -2049,41 +2049,44 @@ public class OvsdbDao { public void configureInterfaces(OvsdbClient ovsdbClient) { - configureWanInterfaces(ovsdbClient); - configureLanInterfaces(ovsdbClient); + configureWanInterfacesForDhcpSniffing(ovsdbClient); + configureLanInterfacesforDhcpSniffing(ovsdbClient); } - private void configureLanInterfaces(OvsdbClient ovsdbClient) { + private void configureLanInterfacesforDhcpSniffing(OvsdbClient ovsdbClient) { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); + conditions.add(new Condition("if_name", Function.NOT_EQUALS, new Atom<>(defaultWanInterfaceName))); + conditions.add(new Condition("parent_ifname", Function.NOT_EQUALS, new Atom<>(defaultWanInterfaceName))); + updateColumns.put("dhcp_sniff", new Atom<>(true)); + + Row row = new Row(updateColumns); + operations.add(new Update(wifiInetConfigDbTable, conditions, row)); + + try { + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } catch (OvsdbClientException | InterruptedException | ExecutionException | TimeoutException e) { + LOG.error("OvsdbDao::configureLanInterfaces failed.", e); + throw new RuntimeException(e); + + } + + } + + private void configureWanInterfacesForDhcpSniffing(OvsdbClient ovsdbClient) { List operations = new ArrayList<>(); Map updateColumns = new HashMap<>(); List conditions = new ArrayList<>(); - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(defaultLanInterfaceName))); - updateColumns.put("dhcp_sniff", new Atom<>(true)); + conditions.add(new Condition("if_name", Function.NOT_EQUALS, new Atom<>(defaultLanInterfaceName))); + conditions.add(new Condition("parent_ifname", Function.NOT_EQUALS, new Atom<>(defaultLanInterfaceName))); - Row row = new Row(updateColumns); - operations.add(new Update(wifiInetConfigDbTable, conditions, row)); - - try { - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } catch (OvsdbClientException | InterruptedException | ExecutionException | TimeoutException e) { - LOG.error("OvsdbDao::configureLanInterfaces failed.", e); - throw new RuntimeException(e); - - } - - } - - private void configureWanInterfaces(OvsdbClient ovsdbClient) { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(defaultWanInterfaceName))); updateColumns.put("dhcp_sniff", new Atom<>(true)); Row row = new Row(updateColumns); @@ -3359,6 +3362,7 @@ public class OvsdbDao { tableColumns.put("network", new Atom<>(true)); tableColumns.put("if_name", new Atom<>(ifName)); tableColumns.put("NAT", new Atom<>(isNat)); + tableColumns.put("dhcp_sniff", new Atom<>(true)); Row row = new Row(tableColumns); if (isUpdate) {