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 62f0a5c..50b1f7f 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 @@ -111,1572 +111,1566 @@ import wc.stats.IpDnsTelemetry.WCStatsReport; @Component public class OpensyncExternalIntegrationCloud implements OpensyncExternalIntegrationInterface { - private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); - - @Autowired - private AlarmServiceInterface alarmServiceInterface; - @Autowired - private CustomerServiceInterface customerServiceInterface; - @Autowired - private LocationServiceInterface locationServiceInterface; - @Autowired - private OvsdbSessionMapInterface ovsdbSessionMapInterface; - @Autowired - private CloudEventDispatcherInterface equipmentMetricsCollectorInterface; - @Autowired - private EquipmentServiceInterface equipmentServiceInterface; - @Autowired - private RoutingServiceInterface routingServiceInterface; - @Autowired - private ProfileServiceInterface profileServiceInterface; - @Autowired - private StatusServiceInterface statusServiceInterface; - @Autowired - private ClientServiceInterface clientServiceInterface; - - @Autowired - private OpensyncCloudGatewayController gatewayController; - - @Value("${connectus.ovsdb.autoProvisionedCustomerId:1970}") - private int autoProvisionedCustomerId; - @Value("${connectus.ovsdb.autoProvisionedLocationId:8}") - private int autoProvisionedLocationId; - @Value("${connectus.ovsdb.autoProvisionedProfileId:1}") - private int autoProvisionedProfileId; - @Value("${connectus.ovsdb.autoProvisionedSsid:autoProvisionedSsid}") - private String autoProvisionedSsid; - - @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, new Callable() { - @Override - public Equipment call() throws Exception { - return 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) { - ce = new Equipment(); - ce.setEquipmentType(EquipmentType.AP); - ce.setInventoryId(apId); - ce.setSerial(connectNodeInfo.serialNumber); - ce.setDetails(ApElementConfiguration.createWithDefaults()); - ce = equipmentServiceInterface.create(ce); - - ce.setCustomerId(autoProvisionedCustomerId); - ce.setName(apId); - ce.setLocationId(autoProvisionedLocationId); - ApElementConfiguration apElementConfig = (ApElementConfiguration) ce.getDetails(); - apElementConfig.setEquipmentModel(connectNodeInfo.model); - apElementConfig.getAdvancedRadioMap().get(RadioType.is2dot4GHz) - .setAutoChannelSelection(StateSetting.disabled); - apElementConfig.getAdvancedRadioMap().get(RadioType.is5GHzL) - .setAutoChannelSelection(StateSetting.disabled); - apElementConfig.getAdvancedRadioMap().get(RadioType.is5GHzU) - .setAutoChannelSelection(StateSetting.disabled); - - apElementConfig.getRadioMap().get(RadioType.is2dot4GHz).setAutoChannelSelection(false); - apElementConfig.getRadioMap().get(RadioType.is5GHzL).setAutoChannelSelection(false); - apElementConfig.getRadioMap().get(RadioType.is5GHzU).setAutoChannelSelection(false); - - ce.setDetails(apElementConfig); - ce = equipmentServiceInterface.update(ce); - - Profile apProfile = new Profile(); - apProfile.setCustomerId(ce.getCustomerId()); - apProfile.setName("DefaultApProfile"); - apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); - apProfile = profileServiceInterface.create(apProfile); - - Profile ssidProfile = new Profile(); - ssidProfile.setCustomerId(ce.getCustomerId()); - ssidProfile.setName("DefaultSsid-2g"); - SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); - ssidConfig.setSsid("DefaultSsid-2g"); - ssidConfig.setSecureMode(SecureMode.wpa2PSK); - ssidConfig.setKeyStr("12345678"); - - Set appliedRadios = new HashSet<>(); - appliedRadios.add(RadioType.is2dot4GHz); -// ssidConfig.getRadioBasedConfigs().get(RadioType.is2dot4GHz).setEnable80211r(true); - - ssidConfig.setAppliedRadios(appliedRadios); - ssidProfile.setDetails(ssidConfig); - ssidProfile = profileServiceInterface.create(ssidProfile); - - Profile ssidProfile5g = new Profile(); - ssidProfile5g.setCustomerId(ce.getCustomerId()); - ssidProfile5g.setName("DefaultSsid-5g"); - SsidConfiguration ssidConfig5g = SsidConfiguration.createWithDefaults(); - ssidConfig5g.setSecureMode(SecureMode.wpa2PSK); - ssidConfig5g.setSsid("DefaultSsid-5g"); - ssidConfig5g.setKeyStr("12345678"); - Set appliedRadios5g = new HashSet<>(); - appliedRadios5g.add(RadioType.is5GHzL); - appliedRadios5g.add(RadioType.is5GHzU); - ssidConfig5g.setAppliedRadios(appliedRadios5g); -// ssidConfig5g.getRadioBasedConfigs().get(RadioType.is5GHzL).setEnable80211r(true); -// ssidConfig5g.getRadioBasedConfigs().get(RadioType.is5GHzU).setEnable80211r(true); - - ssidProfile5g.setDetails(ssidConfig5g); - ssidProfile5g = profileServiceInterface.create(ssidProfile5g); - - Set childProfileIds = new HashSet<>(); - childProfileIds.add(ssidProfile.getId()); - childProfileIds.add(ssidProfile5g.getId()); - - apProfile.setChildProfileIds(childProfileIds); - - apProfile = profileServiceInterface.update(apProfile); - ce.setProfileId(apProfile.getId()); - - ce = equipmentServiceInterface.update(ce); - - Customer customer = customerServiceInterface.getOrNull(ce.getCustomerId()); - if (customer == null) { - customer = new Customer(); - customer.setId(autoProvisionedCustomerId); - customerServiceInterface.create(customer); - ce.setCustomerId(customer.getId()); - equipmentServiceInterface.update(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); - - } catch (Exception e) { - LOG.error("Could not process connection from AP {}", apId, e); - throw e; - } - - } - - 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); - protocolStatusData.setReportedSwVersion(connectNodeInfo.firmwareVersion); - protocolStatusData.setReportedSwAltVersion(connectNodeInfo.firmwareVersion); - 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(); - fwUpgradeStatusData.setActiveSwVersion(connectNodeInfo.firmwareVersion); - fwUpgradeStatusData.setAlternateSwVersion(connectNodeInfo.firmwareVersion); - fwUpgradeStatusData.setTargetSwVersion(connectNodeInfo.firmwareVersion); - fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.up_to_date); - statusRecord.setDetails(fwUpgradeStatusData); - statusServiceInterface.update(statusRecord); - - // TODO: - // equipmentStatusInterface.updateNetworkAdminStatus(networkAdminStatusRecord); - // dtop: this one populates traffic capacity and usage dial on the - // main dashboard - // from APDemoMetric properties getPeriodLengthSec, getRxBytes2G, - // getTxBytes2G, getRxBytes5G, getTxBytes5G - 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); - - statusServiceInterface.update(networkAdminStatusRec); - - Status networkAggStatusRec = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), - StatusDataType.NETWORK_AGGREGATE); - if (networkAggStatusRec == null) { - networkAggStatusRec = new Status(); - networkAggStatusRec.setCustomerId(ce.getCustomerId()); - networkAggStatusRec.setEquipmentId(ce.getId()); - NetworkAggregateStatusData naStatusData = new NetworkAggregateStatusData(); - networkAggStatusRec.setDetails(naStatusData); - } - - statusServiceInterface.update(networkAggStatusRec); - - } catch (Exception e) { - LOG.debug("Exception in updateApStatus", 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.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); - } - - 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); + private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); + + @Autowired + private AlarmServiceInterface alarmServiceInterface; + @Autowired + private CustomerServiceInterface customerServiceInterface; + @Autowired + private LocationServiceInterface locationServiceInterface; + @Autowired + private OvsdbSessionMapInterface ovsdbSessionMapInterface; + @Autowired + private CloudEventDispatcherInterface equipmentMetricsCollectorInterface; + @Autowired + private EquipmentServiceInterface equipmentServiceInterface; + @Autowired + private RoutingServiceInterface routingServiceInterface; + @Autowired + private ProfileServiceInterface profileServiceInterface; + @Autowired + private StatusServiceInterface statusServiceInterface; + @Autowired + private ClientServiceInterface clientServiceInterface; + + @Autowired + private OpensyncCloudGatewayController gatewayController; + + @Value("${connectus.ovsdb.autoProvisionedCustomerId:1970}") + private int autoProvisionedCustomerId; + @Value("${connectus.ovsdb.autoProvisionedLocationId:8}") + private int autoProvisionedLocationId; + @Value("${connectus.ovsdb.autoProvisionedProfileId:1}") + private int autoProvisionedProfileId; + @Value("${connectus.ovsdb.autoProvisionedSsid:autoProvisionedSsid}") + private String autoProvisionedSsid; + @Value("${connectus.ovsdb.isAutoconfigEnabled:true}") + private boolean isAutoconfigEnabled; + + @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, new Callable() { + @Override + public Equipment call() throws Exception { + return 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) { + if (isAutoconfigEnabled) { + Equipment ce = getCustomerEquipment(apId); + + try { + + if (ce == null) { + ce = new Equipment(); + ce.setEquipmentType(EquipmentType.AP); + ce.setInventoryId(apId); + ce.setSerial(connectNodeInfo.serialNumber); + ce.setDetails(ApElementConfiguration.createWithDefaults()); + ce = equipmentServiceInterface.create(ce); + + ce.setCustomerId(autoProvisionedCustomerId); + ce.setName(apId); + ce.setLocationId(autoProvisionedLocationId); + ApElementConfiguration apElementConfig = (ApElementConfiguration) ce.getDetails(); + apElementConfig.setEquipmentModel(connectNodeInfo.model); + apElementConfig.getAdvancedRadioMap().get(RadioType.is2dot4GHz) + .setAutoChannelSelection(StateSetting.disabled); + apElementConfig.getAdvancedRadioMap().get(RadioType.is5GHzL) + .setAutoChannelSelection(StateSetting.disabled); + apElementConfig.getAdvancedRadioMap().get(RadioType.is5GHzU) + .setAutoChannelSelection(StateSetting.disabled); + + apElementConfig.getRadioMap().get(RadioType.is2dot4GHz).setAutoChannelSelection(false); + apElementConfig.getRadioMap().get(RadioType.is5GHzL).setAutoChannelSelection(false); + apElementConfig.getRadioMap().get(RadioType.is5GHzU).setAutoChannelSelection(false); + + ce.setDetails(apElementConfig); + ce = equipmentServiceInterface.update(ce); + + Profile apProfile = new Profile(); + apProfile.setCustomerId(ce.getCustomerId()); + apProfile.setName("DefaultApProfile"); + apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); + apProfile = profileServiceInterface.create(apProfile); + + Profile ssidProfile = new Profile(); + ssidProfile.setCustomerId(ce.getCustomerId()); + ssidProfile.setName("DefaultSsid-2g"); + SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); + ssidConfig.setSsid("DefaultSsid-2g"); + ssidConfig.setSecureMode(SecureMode.wpa2PSK); + ssidConfig.setKeyStr("12345678"); + + Set appliedRadios = new HashSet<>(); + appliedRadios.add(RadioType.is2dot4GHz); + // ssidConfig.getRadioBasedConfigs().get(RadioType.is2dot4GHz).setEnable80211r(true); + + ssidConfig.setAppliedRadios(appliedRadios); + ssidProfile.setDetails(ssidConfig); + ssidProfile = profileServiceInterface.create(ssidProfile); + + Profile ssidProfile5g = new Profile(); + ssidProfile5g.setCustomerId(ce.getCustomerId()); + ssidProfile5g.setName("DefaultSsid-5g"); + SsidConfiguration ssidConfig5g = SsidConfiguration.createWithDefaults(); + ssidConfig5g.setSecureMode(SecureMode.wpa2PSK); + ssidConfig5g.setSsid("DefaultSsid-5g"); + ssidConfig5g.setKeyStr("12345678"); + Set appliedRadios5g = new HashSet<>(); + appliedRadios5g.add(RadioType.is5GHzL); + appliedRadios5g.add(RadioType.is5GHzU); + ssidConfig5g.setAppliedRadios(appliedRadios5g); + // ssidConfig5g.getRadioBasedConfigs().get(RadioType.is5GHzL).setEnable80211r(true); + // ssidConfig5g.getRadioBasedConfigs().get(RadioType.is5GHzU).setEnable80211r(true); + + ssidProfile5g.setDetails(ssidConfig5g); + ssidProfile5g = profileServiceInterface.create(ssidProfile5g); + + Set childProfileIds = new HashSet<>(); + childProfileIds.add(ssidProfile.getId()); + childProfileIds.add(ssidProfile5g.getId()); + + apProfile.setChildProfileIds(childProfileIds); + + apProfile = profileServiceInterface.update(apProfile); + ce.setProfileId(apProfile.getId()); + + ce = equipmentServiceInterface.update(ce); + + Customer customer = customerServiceInterface.getOrNull(ce.getCustomerId()); + if (customer == null) { + customer = new Customer(); + customer.setId(autoProvisionedCustomerId); + customerServiceInterface.create(customer); + ce.setCustomerId(customer.getId()); + equipmentServiceInterface.update(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); + + } catch (Exception e) { + LOG.error("Could not process connection from AP {}", apId, e); + throw e; + } + } else { + LOG.info("Autoconfig is not enabled for this AP {}", apId); + } + + } + + 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); + protocolStatusData.setReportedSwVersion(connectNodeInfo.firmwareVersion); + protocolStatusData.setReportedSwAltVersion(connectNodeInfo.firmwareVersion); + 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(); + fwUpgradeStatusData.setActiveSwVersion(connectNodeInfo.firmwareVersion); + fwUpgradeStatusData.setAlternateSwVersion(connectNodeInfo.firmwareVersion); + fwUpgradeStatusData.setTargetSwVersion(connectNodeInfo.firmwareVersion); + fwUpgradeStatusData.setUpgradeState(EquipmentUpgradeState.up_to_date); + statusRecord.setDetails(fwUpgradeStatusData); + statusServiceInterface.update(statusRecord); + + // TODO: + // equipmentStatusInterface.updateNetworkAdminStatus(networkAdminStatusRecord); + // dtop: this one populates traffic capacity and usage dial on the + // main dashboard + // from APDemoMetric properties getPeriodLengthSec, getRxBytes2G, + // getTxBytes2G, getRxBytes5G, getTxBytes5G + 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); + + statusServiceInterface.update(networkAdminStatusRec); + + Status networkAggStatusRec = statusServiceInterface.getOrNull(ce.getCustomerId(), ce.getId(), + StatusDataType.NETWORK_AGGREGATE); + if (networkAggStatusRec == null) { + networkAggStatusRec = new Status(); + networkAggStatusRec.setCustomerId(ce.getCustomerId()); + networkAggStatusRec.setEquipmentId(ce.getId()); + NetworkAggregateStatusData naStatusData = new NetworkAggregateStatusData(); + networkAggStatusRec.setDetails(naStatusData); + } + + statusServiceInterface.update(networkAggStatusRec); + + } catch (Exception e) { + LOG.debug("Exception in updateApStatus", 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.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 { + if (isAutoconfigEnabled) { + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + if (ovsdbSession == null) { + throw new IllegalStateException("AP is not connected " + apId); + } + + 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.setSsidProfile( + profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.ssid)); + + Set radiusSet = new HashSet<>(); + for (Profile ssidProfile : ret.getSsidProfile()) { + + radiusSet.addAll(profileContainer.getChildrenOfType(ssidProfile.getId(), ProfileType.radius)); + + } + ret.setRadiusProfiles(new ArrayList<>(radiusSet)); + + LOG.debug("ApConfig {}", ret.toString()); + } else { + LOG.info("Autoconfig is not enabled for this AP {}", apId); + } - ProfileContainer profileContainer = new ProfileContainer( - profileServiceInterface.getProfileWithChildren(equipmentConfig.getProfileId())); + } catch (Exception e) { + LOG.error("Cannot read config for AP {}", apId, e); + } - ret.setApProfile(profileContainer.getOrNull(equipmentConfig.getProfileId())); + return ret; + } - ret.setSsidProfile(profileContainer.getChildrenOfType(equipmentConfig.getProfileId(), ProfileType.ssid)); - - Set radiusSet = new HashSet(); - for (Profile ssidProfile : ret.getSsidProfile()) { + /** + * @param topic + * @return apId extracted from the topic name, or null if it cannot be + * extracted + */ + public static String extractApIdFromTopic(String topic) { + // Topic is formatted as + // "/ap/"+clientCn+"_"+ret.serialNumber+"/opensync" + if (topic == null) { + return null; + } - radiusSet.addAll(profileContainer.getChildrenOfType(ssidProfile.getId(), ProfileType.radius)); + String[] parts = topic.split("/"); + if (parts.length < 3) { + return null; + } - } - ret.setRadiusProfiles(new ArrayList(radiusSet)); + // apId is the third element in the topic + return parts[2]; + } - LOG.debug("ApConfig {}", ret.toString()); + /** + * @param topic + * @return customerId looked up from the topic name, or -1 if it cannot be + * extracted + */ + public int extractCustomerIdFromTopic(String topic) { - } catch (Exception e) { - LOG.error("Cannot read config for AP {}", apId, e); - } + String apId = extractApIdFromTopic(topic); + if (apId == null) { + return -1; + } - return ret; - } + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - /** - * @param topic - * @return apId extracted from the topic name, or null if it cannot be extracted - */ - public static String extractApIdFromTopic(String topic) { - // Topic is formatted as - // "/ap/"+clientCn+"_"+ret.serialNumber+"/opensync" - if (topic == null) { - return null; - } + if (ovsdbSession != null) { + return ovsdbSession.getCustomerId(); + } - String[] parts = topic.split("/"); - if (parts.length < 3) { - return null; - } + return -1; - // apId is the third element in the topic - return parts[2]; - } + } - /** - * @param topic - * @return customerId looked up from the topic name, or -1 if it cannot be - * extracted - */ - public int extractCustomerIdFromTopic(String topic) { + public long extractEquipmentIdFromTopic(String topic) { - String apId = extractApIdFromTopic(topic); - if (apId == null) { - return -1; - } + String apId = extractApIdFromTopic(topic); + if (apId == null) { + return -1; + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession != null) { - return ovsdbSession.getCustomerId(); - } + if (ovsdbSession != null) { + return ovsdbSession.getEquipmentId(); + } - return -1; + return -1; - } + } - public long extractEquipmentIdFromTopic(String topic) { + @Override + public void processMqttMessage(String topic, Report report) { + LOG.info("Received report on topic {} for ap {}", topic, report.getNodeID()); + int customerId = extractCustomerIdFromTopic(topic); - String apId = extractApIdFromTopic(topic); - if (apId == null) { - return -1; - } + long equipmentId = extractEquipmentIdFromTopic(topic); + if (equipmentId <= 0 || customerId <= 0) { + LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, + equipmentId); + return; + } + + gatewayController.updateActiveCustomer(customerId); + + List metricRecordList = new ArrayList<>(); + + populateApClientMetrics(metricRecordList, report, customerId, equipmentId); + populateApNodeMetrics(metricRecordList, report, customerId, equipmentId); + populateNeighbourScanReports(metricRecordList, report, customerId, equipmentId); + try { + // TODO: depends on survey + // populateChannelInfoReports(metricRecordList, report, customerId, + // equipmentId); + populateApSsidMetrics(metricRecordList, report, customerId, equipmentId, extractApIdFromTopic(topic)); + // handleRssiMetrics(metricRecordList, report, customerId, + // equipmentId); + + } catch (Exception e) { + LOG.error("Exception when processing populateApSsidMetrics", e); + } + + if (!metricRecordList.isEmpty()) { + equipmentMetricsCollectorInterface.publishMetrics(metricRecordList); + } + + } + + private void handleRssiMetrics(List metricRecordList, Report report, int customerId, + long equipmentId) { + LOG.debug("handleRssiMetrics for Customer {} Equipment {}", customerId, equipmentId); + + for (RssiReport rssiReport : report.getRssiReportList()) { + + for (RssiPeer peer : rssiReport.getPeerListList()) { + if (peer.getRssiSource().equals(RssiSource.CLIENT)) { + int rssi = 0; + + for (RssiSample sample : peer.getRssiListList()) { + rssi += getNegativeSignedIntFromUnsigned(sample.getRssi()); + LOG.debug("RSSI Sample: unsignedValue {} signedValue {}", sample.getRssi(), + getNegativeSignedIntFromUnsigned(sample.getRssi())); + } + + rssi = rssi / peer.getRssiListCount(); + + LOG.debug("RssiReport::RssiPeer::Band {} RssiPeer MAC {} RssiSamples Avg {} RxPpdus {} TxPpdus {}", + rssiReport.getBand(), peer.getMacAddress(), rssi, peer.getRxPpdus(), peer.getTxPpdus()); + } + } + + } + } + + private void populateApNodeMetrics(List metricRecordList, Report report, int customerId, + long equipmentId) { + { + LOG.debug("populateApNodeMetrics for Customer {} Equipment {}", customerId, equipmentId); + ApNodeMetrics apNodeMetrics = new ApNodeMetrics(); + ServiceMetric smr = new ServiceMetric(customerId, equipmentId); + metricRecordList.add(smr); + smr.setDetails(apNodeMetrics); + + for (Device deviceReport : report.getDeviceList()) { + + ApPerformance apPerformance = new ApPerformance(); + apNodeMetrics.setApPerformance(apPerformance); + + smr.setCreatedTimestamp(deviceReport.getTimestampMs()); + // data.setChannelUtilization2G(channelUtilization2G); + // data.setChannelUtilization5G(channelUtilization5G); + + if (deviceReport.getRadioTempCount() > 0) { + int cpuTemperature = 0; + int numSamples = 0; + for (RadioTemp r : deviceReport.getRadioTempList()) { + if (r.hasValue()) { + cpuTemperature += r.getValue(); + numSamples++; + } + } + + if (numSamples > 0) { + apPerformance.setCpuTemperature(cpuTemperature / numSamples); + } + } + + if (deviceReport.hasCpuUtil() && deviceReport.getCpuUtil().hasCpuUtil()) { + apPerformance + .setCpuUtilized(new byte[] { (byte) deviceReport.getCpuUtil().getCpuUtil(), (byte) 0 }); + } + + apPerformance.setEthLinkState(EthernetLinkState.UP1000_FULL_DUPLEX); + + if (deviceReport.hasMemUtil() && deviceReport.getMemUtil().hasMemTotal() + && deviceReport.getMemUtil().hasMemUsed()) { + apPerformance.setFreeMemory( + deviceReport.getMemUtil().getMemTotal() - deviceReport.getMemUtil().getMemUsed()); + } + apPerformance.setUpTime((long) deviceReport.getUptime()); + } + + // Main Network dashboard shows Traffic and Capacity values that + // are + // calculated + // from + // ApNodeMetric properties getPeriodLengthSec, getRxBytes2G, + // getTxBytes2G, + // getRxBytes5G, getTxBytes5G + + // go over all the clients to aggregate per-client tx/rx stats - + // we + // want to do + // this + // only once per batch of ApNodeMetrics - so we do not repeat + // values + // over and + // over again + + for (ClientReport clReport : report.getClientsList()) { + + long rxBytes = 0; + long txBytes = 0; + + for (Client cl : clReport.getClientListList()) { + if (cl.getStats().hasTxBytes()) { + txBytes += cl.getStats().getTxBytes(); + } + if (cl.getStats().hasRxBytes()) { + rxBytes += cl.getStats().getRxBytes(); + } + + } + + RadioType radioType = getRadioTypeFromOpensyncRadioBand(clReport.getBand()); + + apNodeMetrics.setRxBytes(radioType, rxBytes); + apNodeMetrics.setTxBytes(radioType, txBytes); + + // TODO: temporary solution as this was causing Noise Floor to + // disappear from Dashboard and Access Point rows + apNodeMetrics.setNoiseFloor(radioType, -98); + // TODO: Radio Utilization will be calculated when the survey is + // enabled + apNodeMetrics.setRadioUtilization(radioType, new ArrayList<>()); + + } + + // Status radioUtilizationStatus = + // statusServiceInterface.getOrNull(customerId, equipmentId, + // StatusDataType.RADIO_UTILIZATION); + // + // if (radioUtilizationStatus != null) { + // RadioUtilizationReport radioUtilizationReport = + // (RadioUtilizationReport) radioUtilizationStatus + // .getDetails(); + // } + + apNodeMetrics.setPeriodLengthSec(60); + + // Now try to populate metrics for calculation of radio capacity + // see + // com.telecominfraproject.wlan.metrics.streaming.spark.equipmentreport.CapacityDStreamsConfig.toAggregatedStats(int, + // long, ApNodeMetric data) + // result.stats2g = + // toAggregatedRadioStats(data.getNoiseFloor2G(),data.getRadioUtilization2G()); + // result.stats5g = + // toAggregatedRadioStats(data.getNoiseFloor5G(),data.getRadioUtilization5G()); + // RadioUtilization + // private Integer assocClientTx; + // private Integer unassocClientTx; + // private Integer assocClientRx; + // private Integer unassocClientRx; + // private Integer nonWifi; + // private Integer timestampSeconds; + + // populate it from report.survey + // for (Survey survey : report.getSurveyList()) { + /* + * LOG.debug("MJH Survey {}", survey); // int oBSS = 0; // int iBSS + * = 0; // int totalBusy = 0; // int durationMs = 0; for + * (SurveySample surveySample : survey.getSurveyListList()) { if + * (surveySample.getDurationMs() == 0) { continue; } + * + * // iBSS += surveySample.getBusySelf() + // + * surveySample.getBusyTx(); // oBSS += surveySample.getBusyRx(); // + * totalBusy += surveySample.getBusy(); // durationMs += + * surveySample.getDurationMs(); + * + * RadioUtilization radioUtil = new RadioUtilization(); radioUtil + * .setTimestampSeconds((int) ((survey.getTimestampMs() + + * surveySample.getOffsetMs()) / 1000)); + * radioUtil.setAssocClientTx(100 * surveySample.getBusyTx() / + * surveySample.getDurationMs()); radioUtil.setAssocClientRx(100 * + * surveySample.getBusyRx() / surveySample.getDurationMs()); + * radioUtil.setNonWifi( 100 * (surveySample.getBusy() - + * surveySample.getBusyTx() - surveySample.getBusyRx()) / + * surveySample.getDurationMs()); + * + * RadioType radioType = RadioType.UNSUPPORTED; switch + * (survey.getBand()) { case BAND2G: radioType = + * RadioType.is2dot4GHz; break; case BAND5G: radioType = + * RadioType.is5GHz; break; case BAND5GL: radioType = + * RadioType.is5GHzL; break; case BAND5GU: radioType = + * RadioType.is5GHzU; break; } + * + * apNodeMetrics.getRadioUtilization(radioType).add(radioUtil); + * + * } + * + * // Double totalUtilization = 100D * totalBusy / durationMs; // + * LOG.trace("Total Utilization {}", totalUtilization); // Double + * totalWifiUtilization = 100D * (iBSS + oBSS) / // durationMs; // + * LOG.trace("Total Wifi Utilization {}", // totalWifiUtilization); + * // LOG.trace("Total Non-Wifi Utilization {}", // totalUtilization + * - // totalWifiUtilization); // if (survey.getBand() == + * RadioBandType.BAND2G) { // + * data.setChannelUtilization2G(totalUtilization.intValue()); // } + * else { // + * data.setChannelUtilization5G(totalUtilization.intValue()); // } + */ + // } + + } + + } + + private void populateApClientMetrics(List metricRecordList, Report report, int customerId, + long equipmentId) { + LOG.debug("populateApClientMetrics for Customer {} Equipment {}", customerId, equipmentId); + + for (ClientReport clReport : report.getClientsList()) { + LOG.debug("Opensync Stats for ClientReport {}", clReport); + + for (Client cl : clReport.getClientListList()) { + + if (cl.getMacAddress() == null) { + LOG.debug( + "No mac address for Client {}, cannot set device mac address for client in ClientMetrics.", + cl); + continue; + } + + LOG.debug("Processing ClientReport from AP {}", clReport); + + ServiceMetric smr = new ServiceMetric(customerId, equipmentId, new MacAddress(cl.getMacAddress())); + metricRecordList.add(smr); + + smr.setCreatedTimestamp(clReport.getTimestampMs()); + + // clReport.getChannel(); + ClientMetrics cMetrics = new ClientMetrics(); + smr.setDetails(cMetrics); + + Integer periodLengthSec = 60; // matches what's configured by + // OvsdbDao.configureStats(OvsdbClient) + cMetrics.setPeriodLengthSec(periodLengthSec); + + cMetrics.setRadioType(getRadioTypeFromOpensyncRadioBand(clReport.getBand())); + + if (cl.hasStats()) { + if (cl.getStats().hasRssi()) { + int unsignedRssi = cl.getStats().getRssi(); + cMetrics.setRssi(getNegativeSignedIntFromUnsigned(unsignedRssi)); + } + + // we'll report each device as having a single (very long) + // session + cMetrics.setSessionId(smr.getClientMac()); + + // populate Rx stats + if (cl.getStats().hasRxBytes()) { + cMetrics.setRxBytes(cl.getStats().getRxBytes()); + } + + if (cl.getStats().hasRxRate()) { + cMetrics.setAverageRxRate(cl.getStats().getTxRate() / 1000); + } + + if (cl.getStats().hasRxErrors()) { + cMetrics.setNumRxNoFcsErr((int) cl.getStats().getRxErrors()); + } + + if (cl.getStats().hasRxFrames()) { + cMetrics.setNumRxFramesReceived(cl.getStats().getRxFrames()); + // cMetrics.setNumRxPackets(cl.getStats().getRxFrames()); + } + + if (cl.getStats().hasRxRetries()) { + cMetrics.setNumRxRetry((int) cl.getStats().getRxRetries()); + } + + // populate Tx stats + if (cl.getStats().hasTxBytes()) { + cMetrics.setNumTxBytes(cl.getStats().getTxBytes()); + } + + if (cl.getStats().hasTxRate()) { + cMetrics.setAverageTxRate(Double.valueOf(cl.getStats().getTxRate() / 1000)); + } + + if (cl.getStats().hasTxRate() && cl.getStats().hasRxRate()) { + cMetrics.setRates(new byte[] { Double.valueOf(cl.getStats().getTxRate() / 1000).byteValue(), + Double.valueOf(cl.getStats().getRxRate() / 1000).byteValue() }); + } + + if (cl.getStats().hasTxErrors()) { + cMetrics.setNumTxDropped((int) cl.getStats().getTxErrors()); + } + + if (cl.getStats().hasRxFrames()) { + cMetrics.setNumTxFramesTransmitted(cl.getStats().getTxFrames()); + } + + if (cl.getStats().hasTxRetries()) { + cMetrics.setNumTxDataRetries((int) cl.getStats().getTxRetries()); + } + + } + + LOG.debug("ApClientMetrics Report {}", cMetrics); + + } + + } + + } + + private void populateNeighbourScanReports(List metricRecordList, Report report, int customerId, + long equipmentId) { + LOG.debug("populateNeighbourScanReports for Customer {} Equipment {}", customerId, equipmentId); + + for (Neighbor neighbor : report.getNeighborsList()) { + + ServiceMetric smr = new ServiceMetric(customerId, equipmentId); + metricRecordList.add(smr); + NeighbourScanReports neighbourScanReports = new NeighbourScanReports(); + smr.setDetails(neighbourScanReports); + + smr.setCreatedTimestamp(neighbor.getTimestampMs()); + + List neighbourReports = new ArrayList<>(); + neighbourScanReports.setNeighbourReports(neighbourReports); + + for (NeighborBss nBss : neighbor.getBssListList()) { + NeighbourReport nr = new NeighbourReport(); + neighbourReports.add(nr); + + if (neighbor.getBand() == RadioBandType.BAND2G) { + nr.setAcMode(false); + nr.setbMode(false); + nr.setnMode(true); + nr.setRadioType(RadioType.is2dot4GHz); + } else if (neighbor.getBand() == RadioBandType.BAND5G) { + nr.setAcMode(true); + nr.setbMode(false); + nr.setnMode(false); + nr.setRadioType(RadioType.is5GHz); + } else if (neighbor.getBand() == RadioBandType.BAND5GL) { + nr.setAcMode(true); + nr.setbMode(false); + nr.setnMode(false); + nr.setRadioType(RadioType.is5GHzL); + } else if (neighbor.getBand() == RadioBandType.BAND5GU) { + nr.setAcMode(true); + nr.setbMode(false); + nr.setnMode(false); + nr.setRadioType(RadioType.is5GHzU); + } + + nr.setChannel(nBss.getChannel()); + nr.setMacAddress(new MacAddress(nBss.getBssid())); + nr.setNetworkType(NetworkType.AP); + nr.setPacketType(NeighborScanPacketType.BEACON); + nr.setPrivacy((nBss.getSsid() == null || nBss.getSsid().isEmpty()) ? true : false); + // nr.setRate(rate); + // we can only get Rssi as an unsigned int from opensync, so + // some shifting + nr.setRssi(getNegativeSignedIntFromUnsigned(nBss.getRssi())); + // nr.setScanTimeInSeconds(scanTimeInSeconds); + nr.setSecureMode(DetectedAuthMode.WPA); + // nr.setSignal(signal); + nr.setSsid(nBss.getSsid()); + } + + } + } + + private void handleClientSessionUpdate(int customerId, long equipmentId, String apId, long locationId, int channel, + RadioBandType band, long timestamp, sts.OpensyncStats.Client client, String nodeId, MacAddress macAddress, + String ssid) { + + LOG.debug("Client numConnected {} connectOffsetMs {} numDisconnected {} disconnectOffsetMs {} durationMs {}", + client.getConnectCount(), client.getConnectOffsetMs(), client.getDisconnectCount(), + client.getDisconnectOffsetMs(), client.getDurationMs()); + + com.telecominfraproject.wlan.client.models.Client clientInstance = clientServiceInterface.getOrNull(customerId, + new MacAddress(client.getMacAddress())); + if (clientInstance == null) { + clientInstance = new com.telecominfraproject.wlan.client.models.Client(); + clientInstance.setCustomerId(customerId); + clientInstance.setMacAddress(new MacAddress(client.getMacAddress())); + clientInstance.setDetails(new ClientInfoDetails()); + clientInstance = clientServiceInterface.create(clientInstance); + } + ClientInfoDetails clientDetails = (ClientInfoDetails) clientInstance.getDetails(); + clientDetails.setHostName(nodeId); + clientInstance.setDetails(clientDetails); + clientInstance = clientServiceInterface.update(clientInstance); + + try { + + ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, + clientInstance.getMacAddress()); + if (clientSession == null) { + LOG.debug("No session found for Client {}, creating new one.", client.getMacAddress()); + clientSession = new ClientSession(); + clientSession.setCustomerId(customerId); + clientSession.setEquipmentId(equipmentId); + clientSession.setLocationId(locationId); + clientSession.setMacAddress(new MacAddress(client.getMacAddress())); + clientSession.setDetails(new ClientSessionDetails()); + + clientSession = clientServiceInterface.updateSession(clientSession); + } + + ClientSessionDetails clientSessionDetails = clientSession.getDetails(); + clientSessionDetails.setRadioType(getRadioTypeFromOpensyncRadioBand(band)); + clientSessionDetails.setSessionId(clientSession.getMacAddress().getAddressAsLong()); + clientSessionDetails.setSsid(ssid); + clientSessionDetails.setAssociationStatus(0); + clientSessionDetails.setAssocTimestamp(timestamp - client.getConnectOffsetMs()); + clientSessionDetails.setAuthTimestamp(timestamp - client.getConnectOffsetMs()); + clientSessionDetails.setFirstDataRcvdTimestamp(timestamp); + clientSessionDetails.setFirstDataSentTimestamp(timestamp); + clientSessionDetails.setLastRxTimestamp(timestamp); + clientSessionDetails.setHostname(nodeId); + + ClientDhcpDetails dhcpDetails = new ClientDhcpDetails(clientSessionDetails.getSessionId()); + clientSessionDetails.setDhcpDetails(dhcpDetails); + + clientSessionDetails.setMetricDetails(calculateClientSessionMetricDetails(client)); + clientSession.setDetails(clientSessionDetails); + + clientSession = clientServiceInterface.updateSession(clientSession); + + LOG.debug("CreatedOrUpdated clientSession {}", clientSession); + + } catch (Exception e) { + LOG.error("Error while attempting to create ClientSession and Info", e); + } + } + + private RadioType getRadioTypeFromOpensyncRadioBand(RadioBandType band) { + RadioType radioType = null; + switch (band) { + case BAND2G: + radioType = RadioType.is2dot4GHz; + break; + case BAND5G: + radioType = RadioType.is5GHz; + break; + case BAND5GU: + radioType = RadioType.is5GHzU; + break; + case BAND5GL: + radioType = RadioType.is5GHzL; + break; + default: + radioType = RadioType.UNSUPPORTED; + } + return radioType; + } + + private ClientSessionMetricDetails calculateClientSessionMetricDetails(sts.OpensyncStats.Client client) { + ClientSessionMetricDetails metricDetails = new ClientSessionMetricDetails(); + metricDetails.setRssi(getNegativeSignedIntFromUnsigned(client.getStats().getRssi())); + metricDetails.setRxBytes(client.getStats().getRxBytes()); + metricDetails.setTxBytes(client.getStats().getTxBytes()); + metricDetails.setTotalTxPackets(client.getStats().getTxFrames()); + metricDetails.setTotalRxPackets(client.getStats().getRxFrames()); + metricDetails.setTxDataFrames((int) ((int) client.getStats().getTxFrames() - client.getStats().getTxRetries())); + metricDetails.setRxDataFrames((int) ((int) client.getStats().getRxFrames() - client.getStats().getRxRetries())); + // values reported in Kbps, convert to Mbps + metricDetails.setRxMbps(Float.valueOf((float) (client.getStats().getRxRate() / 1000))); + metricDetails.setTxMbps(Float.valueOf((float) (client.getStats().getTxRate() / 1000))); + metricDetails.setRxRateKbps((long) client.getStats().getRxRate()); + metricDetails.setTxRateKbps((long) client.getStats().getTxRate()); + return metricDetails; + } + + private void populateApSsidMetrics(List metricRecordList, Report report, int customerId, + long equipmentId, String apId) { + + LOG.debug("populateApSsidMetrics for Customer {} Equipment {}", customerId, equipmentId); + ServiceMetric smr = new ServiceMetric(customerId, equipmentId); + ApSsidMetrics apSsidMetrics = new ApSsidMetrics(); + + // we need to populate location Id on the client sessions, that's why + // we're + // getting equipment object in here (from the cache) + Equipment equipment = getCustomerEquipment(apId); + long locationId = (equipment != null) ? equipment.getLocationId() : 0; + + smr.setDetails(apSsidMetrics); + metricRecordList.add(smr); + for (ClientReport clientReport : report.getClientsList()) { + + LOG.debug("ClientReport for channel {} RadioBand {}", clientReport.getChannel(), clientReport.getBand()); + + if (smr.getCreatedTimestamp() < clientReport.getTimestampMs()) { + smr.setCreatedTimestamp(clientReport.getTimestampMs()); + } + + long txBytes = 0L; + long rxBytes = 0L; + long txFrames = 0L; + long rxFrames = 0L; + + int txErrors = 0; + int rxErrors = 0; + + int txRetries = 0; + int rxRetries = 0; + + int lastRssi = 0; + String ssid = null; + + Set clientMacs = new HashSet<>(); + + RadioType radioType = getRadioTypeFromOpensyncRadioBand(clientReport.getBand()); + + SsidStatistics ssidStatistics = new SsidStatistics(); + // GET the Radio IF MAC (BSSID) from the activeBSSIDs + + Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.ACTIVE_BSSIDS); + if (activeBssidsStatus != null) { + ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); + for (ActiveBSSID activeBSSID : statusDetails.getActiveBSSIDs()) { + if (activeBSSID.getRadioType().equals(radioType)) { + ssidStatistics.setBssid(new MacAddress(activeBSSID.getBssid())); + // ssid value, in case not in stats, else will take + // stats value after + ssid = activeBSSID.getSsid(); + } + } + } + + for (Client client : clientReport.getClientListList()) { + + if (client.hasSsid() && client.getSsid() != null && !client.getSsid().equals("")) { + ssid = client.getSsid(); + } + + LOG.debug("Client {} connected {} connectedCount {}", client.getMacAddress(), client.getConnected(), + client.getConnectCount()); + + if (client.hasStats()) { + clientMacs.add(client.getMacAddress()); + sts.OpensyncStats.Client.Stats clientStats = client.getStats(); + + rxBytes += clientStats.getRxBytes(); + txBytes += clientStats.getTxBytes(); + txFrames += clientStats.getRxFrames(); + rxFrames += clientStats.getTxFrames(); + rxRetries += clientStats.getRxRetries(); + txRetries += clientStats.getTxRetries(); + rxErrors += clientStats.getRxErrors(); + txErrors += clientStats.getTxErrors(); + + lastRssi = client.getStats().getRssi(); + + for (sts.OpensyncStats.Client.TxStats txStats : client.getTxStatsList()) { + + LOG.debug("txStats {}", txStats); + } + + for (sts.OpensyncStats.Client.RxStats rxStats : client.getRxStatsList()) { + + LOG.debug("rxStats {}", rxStats); + } + + for (sts.OpensyncStats.Client.TidStats tidStats : client.getTidStatsList()) { + + LOG.debug("tidStats {}", tidStats); + } + + try { + handleClientSessionUpdate(customerId, equipmentId, apId, locationId, clientReport.getChannel(), + clientReport.getBand(), clientReport.getTimestampMs(), client, report.getNodeID(), + ssidStatistics.getBssid(), ssidStatistics.getSsid()); + } catch (Exception e) { + LOG.debug("Unabled to update client {} session {}", client, e); + } + } + + } + + // we can only get Rssi as an unsigned int from opensync, so some + // shifting + ssidStatistics.setRxLastRssi(getNegativeSignedIntFromUnsigned(lastRssi)); + ssidStatistics.setNumRxData(Long.valueOf(rxFrames).intValue()); + ssidStatistics.setRxBytes(rxBytes - rxErrors - rxRetries); + ssidStatistics.setNumTxDataRetries(txRetries); + ssidStatistics.setNumRcvFrameForTx(txFrames); + ssidStatistics.setNumTxBytesSucc(txBytes - txErrors - txRetries); + ssidStatistics.setNumRxRetry(rxRetries); + ssidStatistics.setNumClient(clientMacs.size()); + ssidStatistics.setSsid(ssid); + + if (radioType != null) { + List ssidStatsList = apSsidMetrics.getSsidStats().get(radioType); + if (ssidStatsList == null) { + ssidStatsList = new ArrayList<>(); + } + ssidStatsList.add(ssidStatistics); + apSsidMetrics.getSsidStats().put(radioType, ssidStatsList); + } + + } + + LOG.debug("ApSsidMetrics {}", apSsidMetrics); + + // LOG.debug("Created ApSsidMetrics Report {}", apSsidMetrics); + + } + + int getNegativeSignedIntFromUnsigned(int unsignedValue) { + int negSignedValue = (unsignedValue << 1) >> 1; + return negSignedValue; + } + + private void populateChannelInfoReports(List metricRecordList, Report report, int customerId, + long equipmentId) { + + LOG.debug("populateChannelInfoReports for Customer {} Equipment {}", customerId, equipmentId); + ServiceMetric smr = new ServiceMetric(); + smr.setCustomerId(customerId); + smr.setEquipmentId(equipmentId); + + ChannelInfoReports channelInfoReports = new ChannelInfoReports(); + + smr.setDetails(channelInfoReports); + metricRecordList.add(smr); + + for (Survey survey : report.getSurveyList()) { + + smr.setCreatedTimestamp(survey.getTimestampMs()); + // message SurveySample { + // required uint32 channel = 1; + // optional uint32 duration_ms = 2; + // optional uint32 total_count = 3; + // optional uint32 sample_count = 4; + // optional uint32 busy = 5; /* Busy = Rx + Tx + Interference */ + // optional uint32 busy_tx = 6; /* Tx */ + // optional uint32 busy_rx = 7; /* Rx = Rx_obss + Rx_errr (self and + // obss errors) */ + // optional uint32 busy_self = 8; /* Rx_self (derived from succesful + // Rx frames)*/ + // optional uint32 offset_ms = 9; + // optional uint32 busy_ext = 10; /* 40MHz extention channel busy */ + // } + + RadioType radioType = null; + if (survey.getBand() == RadioBandType.BAND2G) { + radioType = RadioType.is2dot4GHz; + } else if (survey.getBand() == RadioBandType.BAND5G) { + radioType = RadioType.is5GHz; + } else if (survey.getBand() == RadioBandType.BAND5GL) { + radioType = RadioType.is5GHzL; + } else if (survey.getBand() == RadioBandType.BAND5GU) { + radioType = RadioType.is5GHzU; + } + + if (survey.getSurveyType().equals(SurveyType.OFF_CHANNEL) + || survey.getSurveyType().equals(SurveyType.FULL)) { + + // in this case, we have multiple channels (potentially) and + // will make + // ChannelInfo entries per surveyed channel + Map> sampleByChannelMap = new HashMap<>(); + + survey.getSurveyListList().stream().forEach(s -> { + List surveySampleList; + if (sampleByChannelMap.get(s.getChannel()) == null) { + surveySampleList = new ArrayList<>(); + } else { + surveySampleList = sampleByChannelMap.get(s.getChannel()); + } + surveySampleList.add(s); + sampleByChannelMap.put(s.getChannel(), surveySampleList); + }); + + for (List surveySampleList : sampleByChannelMap.values()) { + ChannelInfo channelInfo = createChannelInfo(equipmentId, radioType, surveySampleList); + + List channelInfoList = channelInfoReports.getRadioInfo(radioType); + if (channelInfoList == null) { + channelInfoList = new ArrayList<>(); + } + channelInfoList.add(channelInfo); + channelInfoReports.getChannelInformationReportsPerRadio().put(radioType, channelInfoList); + } + + } else { + + List surveySampleList = survey.getSurveyListList(); + + ChannelInfo channelInfo = createChannelInfo(equipmentId, radioType, surveySampleList); + + List channelInfoList = channelInfoReports.getRadioInfo(radioType); + if (channelInfoList == null) { + channelInfoList = new ArrayList<>(); + } + channelInfoList.add(channelInfo); + channelInfoReports.getChannelInformationReportsPerRadio().put(radioType, channelInfoList); + } + + } + + LOG.debug("ChannelInfoReports {}", channelInfoReports); + + } + + private ChannelInfo createChannelInfo(long equipmentId, RadioType radioType, List surveySampleList) { + int busyTx = 0; /* Tx */ + int busySelf = 0; /* Rx_self (derived from succesful Rx frames) */ + int busy = 0; /* Busy = Rx + Tx + Interference */ + ChannelInfo channelInfo = new ChannelInfo(); + + for (SurveySample sample : surveySampleList) { + + busyTx += sample.getBusyTx(); + busySelf += sample.getBusySelf(); + busy += sample.getBusy(); + channelInfo.setChanNumber(sample.getChannel()); + } + + int iBSS = busyTx + busySelf; + + int totalWifi = busy - iBSS; + + channelInfo.setTotalUtilization(busy); + channelInfo.setWifiUtilization(totalWifi); + channelInfo.setBandwidth(((ApElementConfiguration) equipmentServiceInterface.get(equipmentId).getDetails()) + .getRadioMap().get(radioType).getChannelBandwidth()); + channelInfo.setNoiseFloor(Integer.valueOf(-84)); // TODO: when this + // becomes available + // add + return channelInfo; + } + + @Override + public void processMqttMessage(String topic, FlowReport flowReport) { + + LOG.info("Received report on topic {}", topic); + int customerId = extractCustomerIdFromTopic(topic); + + long equipmentId = extractEquipmentIdFromTopic(topic); + if (equipmentId <= 0 || customerId <= 0) { + LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, + equipmentId); + return; + } + + String apId = extractApIdFromTopic(topic); + + if (apId == null) { + LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, + equipmentId, apId); + return; + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + } - if (ovsdbSession != null) { - return ovsdbSession.getEquipmentId(); - } + @Override + public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { + LOG.debug("Received WCStatsReport {}", wcStatsReport.toString()); - return -1; + LOG.info("Received report on topic {}", topic); + int customerId = extractCustomerIdFromTopic(topic); - } + long equipmentId = extractEquipmentIdFromTopic(topic); + if (equipmentId <= 0 || customerId <= 0) { + LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, + equipmentId); + return; + } - @Override - public void processMqttMessage(String topic, Report report) { - LOG.info("Received report on topic {} for ap {}", topic, report.getNodeID()); - int customerId = extractCustomerIdFromTopic(topic); + String apId = extractApIdFromTopic(topic); - long equipmentId = extractEquipmentIdFromTopic(topic); - if (equipmentId <= 0 || customerId <= 0) { - LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, - equipmentId); - return; - } + if (apId == null) { + LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, + equipmentId, apId); + return; + } - gatewayController.updateActiveCustomer(customerId); + } - List metricRecordList = new ArrayList<>(); - - populateApClientMetrics(metricRecordList, report, customerId, equipmentId); - populateApNodeMetrics(metricRecordList, report, customerId, equipmentId); - populateNeighbourScanReports(metricRecordList, report, customerId, equipmentId); - try { - // TODO: depends on survey -// populateChannelInfoReports(metricRecordList, report, customerId, equipmentId); - populateApSsidMetrics(metricRecordList, report, customerId, equipmentId, extractApIdFromTopic(topic)); -// handleRssiMetrics(metricRecordList, report, customerId, equipmentId); - - } catch (Exception e) { - LOG.error("Exception when processing populateApSsidMetrics", e); - } - - if (!metricRecordList.isEmpty()) { - equipmentMetricsCollectorInterface.publishMetrics(metricRecordList); - } - - } - - private void handleRssiMetrics(List metricRecordList, Report report, int customerId, - long equipmentId) { - LOG.debug("handleRssiMetrics for Customer {} Equipment {}", customerId, equipmentId); - - for (RssiReport rssiReport : report.getRssiReportList()) { - - for (RssiPeer peer : rssiReport.getPeerListList()) { - if (peer.getRssiSource().equals(RssiSource.CLIENT)) { - int rssi = 0; - - for (RssiSample sample : peer.getRssiListList()) { - rssi += (sample.getRssi() << 1) >> 1; - LOG.debug("RSSI Sample: unsignedValue {} signedValue {}", sample.getRssi(), - ((sample.getRssi() << 1) >> 1)); - } - - rssi = rssi / peer.getRssiListCount(); - - LOG.debug("RssiReport::RssiPeer::Band {} RssiPeer MAC {} RssiSamples Avg {} RxPpdus {} TxPpdus {}", - rssiReport.getBand(), peer.getMacAddress(), rssi, peer.getRxPpdus(), peer.getTxPpdus()); - } - } - - } - } - - private void populateApNodeMetrics(List metricRecordList, Report report, int customerId, - long equipmentId) { - { - LOG.debug("populateApNodeMetrics for Customer {} Equipment {}", customerId, equipmentId); - ApNodeMetrics apNodeMetrics = new ApNodeMetrics(); - ServiceMetric smr = new ServiceMetric(customerId, equipmentId); - metricRecordList.add(smr); - smr.setDetails(apNodeMetrics); - - for (Device deviceReport : report.getDeviceList()) { - - ApPerformance apPerformance = new ApPerformance(); - apNodeMetrics.setApPerformance(apPerformance); - - smr.setCreatedTimestamp(deviceReport.getTimestampMs()); - // data.setChannelUtilization2G(channelUtilization2G); - // data.setChannelUtilization5G(channelUtilization5G); - - if (deviceReport.getRadioTempCount() > 0) { - int cpuTemperature = 0; - int numSamples = 0; - for (RadioTemp r : deviceReport.getRadioTempList()) { - if (r.hasValue()) { - cpuTemperature += r.getValue(); - numSamples++; - } - } - - if (numSamples > 0) { - apPerformance.setCpuTemperature(cpuTemperature / numSamples); - } - } - - if (deviceReport.hasCpuUtil() && deviceReport.getCpuUtil().hasCpuUtil()) { - apPerformance - .setCpuUtilized(new byte[] { (byte) deviceReport.getCpuUtil().getCpuUtil(), (byte) 0 }); - } - - apPerformance.setEthLinkState(EthernetLinkState.UP1000_FULL_DUPLEX); - - if (deviceReport.hasMemUtil() && deviceReport.getMemUtil().hasMemTotal() - && deviceReport.getMemUtil().hasMemUsed()) { - apPerformance.setFreeMemory( - deviceReport.getMemUtil().getMemTotal() - deviceReport.getMemUtil().getMemUsed()); - } - apPerformance.setUpTime((long) deviceReport.getUptime()); - } - - // Main Network dashboard shows Traffic and Capacity values that - // are - // calculated - // from - // ApNodeMetric properties getPeriodLengthSec, getRxBytes2G, - // getTxBytes2G, - // getRxBytes5G, getTxBytes5G - - // go over all the clients to aggregate per-client tx/rx stats - - // we - // want to do - // this - // only once per batch of ApNodeMetrics - so we do not repeat - // values - // over and - // over again - - for (ClientReport clReport : report.getClientsList()) { - - long rxBytes = 0; - long txBytes = 0; - - for (Client cl : clReport.getClientListList()) { - if (cl.getStats().hasTxBytes()) { - txBytes += cl.getStats().getTxBytes(); - } - if (cl.getStats().hasRxBytes()) { - rxBytes += cl.getStats().getRxBytes(); - } - - } - - RadioType radioType = RadioType.UNSUPPORTED; - switch (clReport.getBand()) { - case BAND2G: - radioType = RadioType.is2dot4GHz; - break; - case BAND5G: - radioType = RadioType.is5GHz; - break; - case BAND5GL: - radioType = RadioType.is5GHzL; - break; - case BAND5GU: - radioType = RadioType.is5GHzU; - break; - } - - apNodeMetrics.setRxBytes(radioType, rxBytes); - apNodeMetrics.setTxBytes(radioType, txBytes); - - // TODO: temporary solution as this was causing Noise Floor to - // disappear from Dashboard and Access Point rows - apNodeMetrics.setNoiseFloor(radioType, -98); - // TODO: Radio Utilization will be calculated when the survey is enabled - apNodeMetrics.setRadioUtilization(radioType, new ArrayList<>()); - - } - -// Status radioUtilizationStatus = statusServiceInterface.getOrNull(customerId, equipmentId, -// StatusDataType.RADIO_UTILIZATION); -// -// if (radioUtilizationStatus != null) { -// RadioUtilizationReport radioUtilizationReport = (RadioUtilizationReport) radioUtilizationStatus -// .getDetails(); -// } - - apNodeMetrics.setPeriodLengthSec(60); - - // Now try to populate metrics for calculation of radio capacity - // see - // com.telecominfraproject.wlan.metrics.streaming.spark.equipmentreport.CapacityDStreamsConfig.toAggregatedStats(int, - // long, ApNodeMetric data) - // result.stats2g = - // toAggregatedRadioStats(data.getNoiseFloor2G(),data.getRadioUtilization2G()); - // result.stats5g = - // toAggregatedRadioStats(data.getNoiseFloor5G(),data.getRadioUtilization5G()); - // RadioUtilization - // private Integer assocClientTx; - // private Integer unassocClientTx; - // private Integer assocClientRx; - // private Integer unassocClientRx; - // private Integer nonWifi; - // private Integer timestampSeconds; - - // populate it from report.survey -// for (Survey survey : report.getSurveyList()) { - /* - * LOG.debug("MJH Survey {}", survey); // int oBSS = 0; // int iBSS = 0; // int - * totalBusy = 0; // int durationMs = 0; for (SurveySample surveySample : - * survey.getSurveyListList()) { if (surveySample.getDurationMs() == 0) { - * continue; } - * - * // iBSS += surveySample.getBusySelf() + // surveySample.getBusyTx(); // oBSS - * += surveySample.getBusyRx(); // totalBusy += surveySample.getBusy(); // - * durationMs += surveySample.getDurationMs(); - * - * RadioUtilization radioUtil = new RadioUtilization(); radioUtil - * .setTimestampSeconds((int) ((survey.getTimestampMs() + - * surveySample.getOffsetMs()) / 1000)); radioUtil.setAssocClientTx(100 * - * surveySample.getBusyTx() / surveySample.getDurationMs()); - * radioUtil.setAssocClientRx(100 * surveySample.getBusyRx() / - * surveySample.getDurationMs()); radioUtil.setNonWifi( 100 * - * (surveySample.getBusy() - surveySample.getBusyTx() - - * surveySample.getBusyRx()) / surveySample.getDurationMs()); - * - * RadioType radioType = RadioType.UNSUPPORTED; switch (survey.getBand()) { case - * BAND2G: radioType = RadioType.is2dot4GHz; break; case BAND5G: radioType = - * RadioType.is5GHz; break; case BAND5GL: radioType = RadioType.is5GHzL; break; - * case BAND5GU: radioType = RadioType.is5GHzU; break; } - * - * apNodeMetrics.getRadioUtilization(radioType).add(radioUtil); - * - * } - * - * // Double totalUtilization = 100D * totalBusy / durationMs; // - * LOG.trace("Total Utilization {}", totalUtilization); // Double - * totalWifiUtilization = 100D * (iBSS + oBSS) / // durationMs; // - * LOG.trace("Total Wifi Utilization {}", // totalWifiUtilization); // - * LOG.trace("Total Non-Wifi Utilization {}", // totalUtilization - // - * totalWifiUtilization); // if (survey.getBand() == RadioBandType.BAND2G) { // - * data.setChannelUtilization2G(totalUtilization.intValue()); // } else { // - * data.setChannelUtilization5G(totalUtilization.intValue()); // } - */ -// } - - - } - - } - - private void populateApClientMetrics(List metricRecordList, Report report, int customerId, - long equipmentId) { - LOG.debug("populateApClientMetrics for Customer {} Equipment {}", customerId, equipmentId); - - for (ClientReport clReport : report.getClientsList()) { - LOG.debug("Opensync Stats for ClientReport {}", clReport); - - for (Client cl : clReport.getClientListList()) { - - if (cl.getMacAddress() == null) { - LOG.debug( - "No mac address for Client {}, cannot set device mac address for client in ClientMetrics.", - cl); - continue; - } - - LOG.debug("Processing ClientReport from AP {}", clReport); - - ServiceMetric smr = new ServiceMetric(customerId, equipmentId, new MacAddress(cl.getMacAddress())); - metricRecordList.add(smr); - - smr.setCreatedTimestamp(clReport.getTimestampMs()); - - // clReport.getChannel(); - ClientMetrics cMetrics = new ClientMetrics(); - smr.setDetails(cMetrics); - - Integer periodLengthSec = 60; // matches what's configured by - // OvsdbDao.configureStats(OvsdbClient) - cMetrics.setPeriodLengthSec(periodLengthSec); - - RadioType radioType = RadioType.UNSUPPORTED; - switch (clReport.getBand()) { - case BAND2G: - radioType = RadioType.is2dot4GHz; - break; - case BAND5G: - radioType = RadioType.is5GHz; - break; - case BAND5GL: - radioType = RadioType.is5GHzL; - break; - case BAND5GU: - radioType = RadioType.is5GHzU; - break; - } - cMetrics.setRadioType(radioType); - - if (cl.hasStats()) { - if (cl.getStats().hasRssi()) { - int unsignedRssi = cl.getStats().getRssi(); - // we can only get Rssi as an unsigned int from opensync, so some shifting - int signedRssi = (unsignedRssi << 1) >> 1; - cMetrics.setRssi(signedRssi); - } - - // we'll report each device as having a single (very long) - // session - cMetrics.setSessionId(smr.getClientMac()); - - // populate Rx stats - if (cl.getStats().hasRxBytes()) { - cMetrics.setRxBytes(cl.getStats().getRxBytes()); - } - - if (cl.getStats().hasRxRate()) { - cMetrics.setAverageRxRate((double) (cl.getStats().getTxRate() / 1000)); - } - - if (cl.getStats().hasRxErrors()) { - cMetrics.setNumRxNoFcsErr((int) cl.getStats().getRxErrors()); - } - - if (cl.getStats().hasRxFrames()) { - cMetrics.setNumRxFramesReceived(cl.getStats().getRxFrames()); -// cMetrics.setNumRxPackets(cl.getStats().getRxFrames()); - } - - if (cl.getStats().hasRxRetries()) { - cMetrics.setNumRxRetry((int) cl.getStats().getRxRetries()); - } - - // populate Tx stats - if (cl.getStats().hasTxBytes()) { - cMetrics.setNumTxBytes(cl.getStats().getTxBytes()); - } - - if (cl.getStats().hasTxRate()) { - cMetrics.setAverageTxRate(Double.valueOf((double) (cl.getStats().getTxRate() / 1000))); - } - - if (cl.getStats().hasTxRate() && cl.getStats().hasRxRate()) { - cMetrics.setRates( - new byte[] { Double.valueOf((double) (cl.getStats().getTxRate() / 1000)).byteValue(), - Double.valueOf((double) (cl.getStats().getRxRate() / 1000)).byteValue() }); - } - - if (cl.getStats().hasTxErrors()) { - cMetrics.setNumTxDropped((int) cl.getStats().getTxErrors()); - } - - if (cl.getStats().hasRxFrames()) { - cMetrics.setNumTxFramesTransmitted(cl.getStats().getTxFrames()); - } - - if (cl.getStats().hasTxRetries()) { - cMetrics.setNumTxDataRetries((int) cl.getStats().getTxRetries()); - } - - } - - LOG.debug("ApClientMetrics Report {}", cMetrics); - - } - - } - - } - - private void populateNeighbourScanReports(List metricRecordList, Report report, int customerId, - long equipmentId) { - LOG.debug("populateNeighbourScanReports for Customer {} Equipment {}", customerId, equipmentId); - - for (Neighbor neighbor : report.getNeighborsList()) { - - ServiceMetric smr = new ServiceMetric(customerId, equipmentId); - metricRecordList.add(smr); - NeighbourScanReports neighbourScanReports = new NeighbourScanReports(); - smr.setDetails(neighbourScanReports); - - smr.setCreatedTimestamp(neighbor.getTimestampMs()); - - List neighbourReports = new ArrayList<>(); - neighbourScanReports.setNeighbourReports(neighbourReports); - - for (NeighborBss nBss : neighbor.getBssListList()) { - NeighbourReport nr = new NeighbourReport(); - neighbourReports.add(nr); - - if (neighbor.getBand() == RadioBandType.BAND2G) { - nr.setAcMode(false); - nr.setbMode(false); - nr.setnMode(true); - nr.setRadioType(RadioType.is2dot4GHz); - } else if (neighbor.getBand() == RadioBandType.BAND5G) { - nr.setAcMode(true); - nr.setbMode(false); - nr.setnMode(false); - nr.setRadioType(RadioType.is5GHz); - } else if (neighbor.getBand() == RadioBandType.BAND5GL) { - nr.setAcMode(true); - nr.setbMode(false); - nr.setnMode(false); - nr.setRadioType(RadioType.is5GHzL); - } else if (neighbor.getBand() == RadioBandType.BAND5GU) { - nr.setAcMode(true); - nr.setbMode(false); - nr.setnMode(false); - nr.setRadioType(RadioType.is5GHzU); - } - - nr.setChannel(nBss.getChannel()); - nr.setMacAddress(new MacAddress(nBss.getBssid())); - nr.setNetworkType(NetworkType.AP); - nr.setPacketType(NeighborScanPacketType.BEACON); - nr.setPrivacy((nBss.getSsid() == null || nBss.getSsid().isEmpty()) ? true : false); - // nr.setRate(rate); - // we can only get Rssi as an unsigned int from opensync, so some shifting - int signedRssi = (nBss.getRssi() << 1) >> 1; - nr.setRssi(signedRssi); - // nr.setScanTimeInSeconds(scanTimeInSeconds); - nr.setSecureMode(DetectedAuthMode.WPA); - // nr.setSignal(signal); - nr.setSsid(nBss.getSsid()); - } - - } - } - - private void handleClientSessionUpdate(int customerId, long equipmentId, String apId, long locationId, int channel, - RadioBandType band, long timestamp, sts.OpensyncStats.Client client, String nodeId, MacAddress macAddress, - String ssid) { - - com.telecominfraproject.wlan.client.models.Client clientInstance = clientServiceInterface.getOrNull(customerId, - new MacAddress(client.getMacAddress())); - if (clientInstance == null) { - clientInstance = new com.telecominfraproject.wlan.client.models.Client(); - clientInstance.setCustomerId(customerId); - clientInstance.setMacAddress(new MacAddress(client.getMacAddress())); - clientInstance.setDetails(new ClientInfoDetails()); - clientInstance = clientServiceInterface.create(clientInstance); - } - ClientInfoDetails clientDetails = (ClientInfoDetails) clientInstance.getDetails(); - clientDetails.setHostName(nodeId); - - try { - - ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, - clientInstance.getMacAddress()); - if (clientSession == null) { - LOG.debug("No session found for Client {}, creating new one.", client.getMacAddress()); - clientSession = new ClientSession(); - clientSession.setCustomerId(customerId); - clientSession.setEquipmentId(equipmentId); - clientSession.setLocationId(locationId); - clientSession.setMacAddress(new MacAddress(client.getMacAddress())); - clientSession.setDetails(new ClientSessionDetails()); - - clientSession = clientServiceInterface.updateSession(clientSession); - } - - RadioType radioType = null; - switch (band) { - case BAND2G: - radioType = RadioType.is2dot4GHz; - break; - case BAND5G: - radioType = RadioType.is5GHz; - break; - case BAND5GU: - radioType = RadioType.is5GHzU; - break; - case BAND5GL: - radioType = RadioType.is5GHzL; - break; - default: - LOG.debug("Band {} is not supported.", band); - } - clientSession.getDetails().setRadioType(radioType); - clientSession.getDetails().setSessionId(clientSession.getMacAddress().getAddressAsLong()); - clientSession.getDetails().setSsid(ssid); - clientSession.getDetails().setAssociationStatus(0); - clientSession.getDetails().setAssocTimestamp(timestamp - client.getConnectOffsetMs()); - clientSession.getDetails().setAuthTimestamp(timestamp - client.getConnectOffsetMs()); - clientSession.getDetails().setFirstDataRcvdTimestamp(timestamp); - clientSession.getDetails().setFirstDataSentTimestamp(timestamp); - clientSession.getDetails().setLastRxTimestamp(timestamp); - clientSession.getDetails().setHostname(nodeId); - ClientDhcpDetails dhcpDetails = new ClientDhcpDetails(clientSession.getDetails().getSessionId()); - clientSession.getDetails().setDhcpDetails(dhcpDetails); - ClientSessionMetricDetails metricDetails = new ClientSessionMetricDetails(); - int signedRssi = (client.getStats().getRssi() << 1) >> 1; - metricDetails.setRssi(signedRssi); - metricDetails.setRxBytes(client.getStats().getRxBytes()); - metricDetails.setTxBytes(client.getStats().getTxBytes()); - metricDetails.setTotalTxPackets(client.getStats().getTxFrames()); - metricDetails.setTotalRxPackets(client.getStats().getRxFrames()); - metricDetails - .setTxDataFrames((int) ((int) client.getStats().getTxFrames() - client.getStats().getTxRetries())); - metricDetails - .setRxDataFrames((int) ((int) client.getStats().getRxFrames() - client.getStats().getRxRetries())); - // values reported in Kbps, convert to Mbps - metricDetails.setRxMbps(Float.valueOf((float) (client.getStats().getRxRate() / 1000))); - metricDetails.setTxMbps(Float.valueOf((float) (client.getStats().getTxRate() / 1000))); - clientSession.getDetails().setMetricDetails(metricDetails); - - clientSession = clientServiceInterface.updateSession(clientSession); - LOG.debug("CreatedOrUpdated clientSession {}", clientSession); - - } catch (Exception e) { - LOG.error("Error while attempting to create ClientSession and Info", e); - } - } - - private void populateApSsidMetrics(List metricRecordList, Report report, int customerId, - long equipmentId, String apId) { - - LOG.debug("populateApSsidMetrics for Customer {} Equipment {}", customerId, equipmentId); - ServiceMetric smr = new ServiceMetric(customerId, equipmentId); - ApSsidMetrics apSsidMetrics = new ApSsidMetrics(); - - // we need to populate location Id on the client sessions, that's why we're - // getting equipment object in here (from the cache) - Equipment equipment = getCustomerEquipment(apId); - long locationId = (equipment != null) ? equipment.getLocationId() : 0; - - smr.setDetails(apSsidMetrics); - metricRecordList.add(smr); - for (ClientReport clientReport : report.getClientsList()) { - - LOG.debug("ClientReport for channel {} RadioBand {}", clientReport.getChannel(), clientReport.getBand()); - - if (smr.getCreatedTimestamp() < clientReport.getTimestampMs()) { - smr.setCreatedTimestamp(clientReport.getTimestampMs()); - } - - long txBytes = 0L; - long rxBytes = 0L; - long txFrames = 0L; - long rxFrames = 0L; - - int txErrors = 0; - int rxErrors = 0; - - int txRetries = 0; - int rxRetries = 0; - - int lastRssi = 0; - String ssid = null; - - Set clientMacs = new HashSet(); - - RadioType radioType = null; - switch (clientReport.getBand()) { - case BAND2G: - radioType = RadioType.is2dot4GHz; - break; - case BAND5G: - radioType = RadioType.is5GHz; - break; - case BAND5GU: - radioType = RadioType.is5GHzU; - break; - case BAND5GL: - radioType = RadioType.is5GHzL; - break; - default: - LOG.debug("Band {} is not supported.", clientReport.getBand()); - break; - } - SsidStatistics ssidStatistics = new SsidStatistics(); - // GET the Radio IF MAC (BSSID) from the activeBSSIDs - - Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); - if (activeBssidsStatus != null) { - ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); - for (ActiveBSSID activeBSSID : statusDetails.getActiveBSSIDs()) { - if (activeBSSID.getRadioType().equals(radioType)) { - ssidStatistics.setBssid(new MacAddress(activeBSSID.getBssid())); - // ssid value, in case not in stats, else will take stats value after - ssid = activeBSSID.getSsid(); - } - } - } - - for (Client client : clientReport.getClientListList()) { - - if (client.hasSsid() && client.getSsid() != null && !client.getSsid().equals("")) { - ssid = client.getSsid(); - } - - LOG.debug("Client {} connected {} connectedCount {}", client.getMacAddress(), client.getConnected(), - client.getConnectCount()); - - if (client.hasStats()) { - clientMacs.add(client.getMacAddress()); - sts.OpensyncStats.Client.Stats clientStats = client.getStats(); - - rxBytes += clientStats.getRxBytes(); - txBytes += clientStats.getTxBytes(); - txFrames += clientStats.getRxFrames(); - rxFrames += clientStats.getTxFrames(); - rxRetries += clientStats.getRxRetries(); - txRetries += clientStats.getTxRetries(); - rxErrors += clientStats.getRxErrors(); - txErrors += clientStats.getTxErrors(); - - lastRssi = client.getStats().getRssi(); - - for (sts.OpensyncStats.Client.TxStats txStats : client.getTxStatsList()) { - - LOG.debug("txStats {}", txStats); - } - - for (sts.OpensyncStats.Client.RxStats rxStats : client.getRxStatsList()) { - - LOG.debug("rxStats {}", rxStats); - } - - for (sts.OpensyncStats.Client.TidStats tidStats : client.getTidStatsList()) { - - LOG.debug("tidStats {}", tidStats); - } - - try { - handleClientSessionUpdate(customerId, equipmentId, apId, locationId, clientReport.getChannel(), - clientReport.getBand(), clientReport.getTimestampMs(), client, report.getNodeID(), - ssidStatistics.getBssid(), ssidStatistics.getSsid()); - } catch (Exception e) { - LOG.debug("Unabled to update client {} session {}", client, e); - } - } - - } - - LOG.debug("Number of clients connected to channel {} on Band {} during reporting time period is {}", - clientReport.getChannel(), clientReport.getBand(), clientMacs.size()); - LOG.debug("Mac Addresses of clients connected to channel {} on Band {} during reporting time period are {}", - clientReport.getChannel(), clientReport.getBand(), clientMacs); - - // we can only get Rssi as an unsigned int from opensync, so some shifting - int signedRssi = (lastRssi << 1) >> 1; - ssidStatistics.setRxLastRssi(signedRssi); - ssidStatistics.setNumRxData(Long.valueOf(rxFrames).intValue()); - ssidStatistics.setRxBytes(rxBytes - rxErrors - rxRetries); - ssidStatistics.setNumTxDataRetries(txRetries); - ssidStatistics.setNumRcvFrameForTx(txFrames); - ssidStatistics.setNumTxBytesSucc(txBytes - txErrors - txRetries); - ssidStatistics.setNumRxRetry(rxRetries); - ssidStatistics.setNumClient(clientMacs.size()); - ssidStatistics.setSsid(ssid); - - if (radioType != null) { - List ssidStatsList = apSsidMetrics.getSsidStats().get(radioType); - if (ssidStatsList == null) { - ssidStatsList = new ArrayList(); - } - ssidStatsList.add(ssidStatistics); - apSsidMetrics.getSsidStats().put(radioType, ssidStatsList); - } - - } - - LOG.debug("ApSsidMetrics {}", apSsidMetrics); - - // LOG.debug("Created ApSsidMetrics Report {}", apSsidMetrics); - - } - - private void populateChannelInfoReports(List metricRecordList, Report report, int customerId, - long equipmentId) { - - LOG.debug("populateChannelInfoReports for Customer {} Equipment {}", customerId, equipmentId); - ServiceMetric smr = new ServiceMetric(); - smr.setCustomerId(customerId); - smr.setEquipmentId(equipmentId); - - ChannelInfoReports channelInfoReports = new ChannelInfoReports(); - - smr.setDetails(channelInfoReports); - metricRecordList.add(smr); - - for (Survey survey : report.getSurveyList()) { - - smr.setCreatedTimestamp(survey.getTimestampMs()); - // message SurveySample { - // required uint32 channel = 1; - // optional uint32 duration_ms = 2; - // optional uint32 total_count = 3; - // optional uint32 sample_count = 4; - // optional uint32 busy = 5; /* Busy = Rx + Tx + Interference */ - // optional uint32 busy_tx = 6; /* Tx */ - // optional uint32 busy_rx = 7; /* Rx = Rx_obss + Rx_errr (self and - // obss errors) */ - // optional uint32 busy_self = 8; /* Rx_self (derived from succesful - // Rx frames)*/ - // optional uint32 offset_ms = 9; - // optional uint32 busy_ext = 10; /* 40MHz extention channel busy */ - // } - - RadioType radioType = null; - if (survey.getBand() == RadioBandType.BAND2G) { - radioType = RadioType.is2dot4GHz; - } else if (survey.getBand() == RadioBandType.BAND5G) { - radioType = RadioType.is5GHz; - } else if (survey.getBand() == RadioBandType.BAND5GL) { - radioType = RadioType.is5GHzL; - } else if (survey.getBand() == RadioBandType.BAND5GU) { - radioType = RadioType.is5GHzU; - } - - if (survey.getSurveyType().equals(SurveyType.OFF_CHANNEL) - || survey.getSurveyType().equals(SurveyType.FULL)) { - - // in this case, we have multiple channels (potentially) and will make - // ChannelInfo entries per surveyed channel - Map> sampleByChannelMap = new HashMap>(); - - survey.getSurveyListList().stream().forEach(s -> { - List surveySampleList; - if (sampleByChannelMap.get(s.getChannel()) == null) { - surveySampleList = new ArrayList(); - } else { - surveySampleList = sampleByChannelMap.get(s.getChannel()); - } - surveySampleList.add(s); - sampleByChannelMap.put(s.getChannel(), surveySampleList); - }); - - for (List surveySampleList : sampleByChannelMap.values()) { - ChannelInfo channelInfo = createChannelInfo(equipmentId, radioType, surveySampleList); - - List channelInfoList = channelInfoReports.getRadioInfo(radioType); - if (channelInfoList == null) { - channelInfoList = new ArrayList(); - } - channelInfoList.add(channelInfo); - channelInfoReports.getChannelInformationReportsPerRadio().put(radioType, channelInfoList); - } - - } else { - - List surveySampleList = survey.getSurveyListList(); - - ChannelInfo channelInfo = createChannelInfo(equipmentId, radioType, surveySampleList); - - List channelInfoList = channelInfoReports.getRadioInfo(radioType); - if (channelInfoList == null) { - channelInfoList = new ArrayList(); - } - channelInfoList.add(channelInfo); - channelInfoReports.getChannelInformationReportsPerRadio().put(radioType, channelInfoList); - } - - } - - LOG.debug("ChannelInfoReports {}", channelInfoReports); - - } - - private ChannelInfo createChannelInfo(long equipmentId, RadioType radioType, List surveySampleList) { - int busyTx = 0; /* Tx */ - int busySelf = 0; /* Rx_self (derived from succesful Rx frames) */ - int busy = 0; /* Busy = Rx + Tx + Interference */ - ChannelInfo channelInfo = new ChannelInfo(); - - for (SurveySample sample : surveySampleList) { - - busyTx += sample.getBusyTx(); - busySelf += sample.getBusySelf(); - busy += sample.getBusy(); - channelInfo.setChanNumber(sample.getChannel()); - } - - int iBSS = busyTx + busySelf; - - int totalWifi = busy - iBSS; - - channelInfo.setTotalUtilization(busy); - channelInfo.setWifiUtilization(totalWifi); - channelInfo.setBandwidth(((ApElementConfiguration) equipmentServiceInterface.get(equipmentId).getDetails()) - .getRadioMap().get(radioType).getChannelBandwidth()); - channelInfo.setNoiseFloor(Integer.valueOf(-84)); // TODO: when this becomes available add - return channelInfo; - } - - @Override - public void processMqttMessage(String topic, FlowReport flowReport) { - - LOG.info("Received report on topic {}", topic); - int customerId = extractCustomerIdFromTopic(topic); - - long equipmentId = extractEquipmentIdFromTopic(topic); - if (equipmentId <= 0 || customerId <= 0) { - LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, - equipmentId); - return; - } + @Override + public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { - String apId = extractApIdFromTopic(topic); + Equipment ce = getCustomerEquipment(apId); + if (ce == null) { + LOG.debug("wifiVIFStateDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - if (apId == null) { - LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, - equipmentId, apId); - return; - } + long equipmentId = ce.getId(); + int customerId = ce.getCustomerId(); - } + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } - @Override - public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { - LOG.debug("Received WCStatsReport {}", wcStatsReport.toString()); + if (vifStateTables == null || vifStateTables.isEmpty() || apId == null) { + return; + } - LOG.info("Received report on topic {}", topic); - int customerId = extractCustomerIdFromTopic(topic); + for (OpensyncAPVIFState vifState : vifStateTables) { - long equipmentId = extractEquipmentIdFromTopic(topic); - if (equipmentId <= 0 || customerId <= 0) { - LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, - equipmentId); - return; - } + if (vifState.getMac() != null && vifState.getSsid() != null && vifState.getChannel() > 0) { + String bssid = vifState.getMac(); + String ssid = vifState.getSsid(); - String apId = extractApIdFromTopic(topic); + int channel = vifState.getChannel(); - if (apId == null) { - LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, - equipmentId, apId); - return; - } + RadioType radioType = null; - } + Equipment apNode = equipmentServiceInterface.getOrNull(equipmentId); + if (apNode == null) { + continue; // we don't have the required info to get the + // radio type yet + } - @Override - public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { + ApElementConfiguration apElementConfig = (ApElementConfiguration) apNode.getDetails(); + for (RadioType key : apElementConfig.getRadioMap().keySet()) { + if (apElementConfig.getRadioMap().get(key).getChannelNumber() == channel) { + radioType = key; + break; + } + } - Equipment ce = getCustomerEquipment(apId); - if (ce == null) { - LOG.debug("wifiVIFStateDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + if (radioType == null) { + continue; // we cannot determine radioType for this BSSID + } - long equipmentId = ce.getId(); - int customerId = ce.getCustomerId(); + Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, + StatusDataType.ACTIVE_BSSIDS); - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } + if (activeBssidsStatus == null) { + activeBssidsStatus = new Status(); + activeBssidsStatus.setCustomerId(customerId); + activeBssidsStatus.setEquipmentId(equipmentId); + activeBssidsStatus.setStatusDataType(StatusDataType.ACTIVE_BSSIDS); - if (vifStateTables == null || vifStateTables.isEmpty() || apId == null) { - return; - } + ActiveBSSIDs statusDetails = new ActiveBSSIDs(); + statusDetails.setActiveBSSIDs(new ArrayList()); - for (OpensyncAPVIFState vifState : vifStateTables) { + activeBssidsStatus.setDetails(statusDetails); - if (vifState.getMac() != null && vifState.getSsid() != null && vifState.getChannel() > 0) { - String bssid = vifState.getMac(); - String ssid = vifState.getSsid(); + activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - int channel = vifState.getChannel(); + } - RadioType radioType = null; + ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); - Equipment apNode = equipmentServiceInterface.getOrNull(equipmentId); - if (apNode == null) { - continue; // we don't have the required info to get the radio type yet - } + List bssidList = statusDetails.getActiveBSSIDs(); + boolean bssidAlreadyPresent = false; + for (ActiveBSSID activeBssid : bssidList) { - ApElementConfiguration apElementConfig = (ApElementConfiguration) apNode.getDetails(); - for (RadioType key : apElementConfig.getRadioMap().keySet()) { - if (apElementConfig.getRadioMap().get(key).getChannelNumber() == channel) { - radioType = key; - break; - } - } + if (activeBssid.getBssid().equals(bssid) && activeBssid.getSsid().equals(ssid) + && activeBssid.getRadioType().equals(radioType)) { + activeBssid.setNumDevicesConnected(vifState.getAssociatedClients().size()); + bssidAlreadyPresent = true; + break; + } - if (radioType == null) { - continue; // we cannot determine radioType for this BSSID - } + } - Status activeBssidsStatus = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); + if (!bssidAlreadyPresent) { + ActiveBSSID newActiveBssid = new ActiveBSSID(); + newActiveBssid.setBssid(bssid); + newActiveBssid.setSsid(ssid); + newActiveBssid.setRadioType(radioType); + newActiveBssid.setNumDevicesConnected(vifState.getAssociatedClients().size()); + bssidList.add(newActiveBssid); + } - if (activeBssidsStatus == null) { - activeBssidsStatus = new Status(); - activeBssidsStatus.setCustomerId(customerId); - activeBssidsStatus.setEquipmentId(equipmentId); - activeBssidsStatus.setStatusDataType(StatusDataType.ACTIVE_BSSIDS); + statusDetails.setActiveBSSIDs(bssidList); + activeBssidsStatus.setDetails(statusDetails); + activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); - ActiveBSSIDs statusDetails = new ActiveBSSIDs(); - statusDetails.setActiveBSSIDs(new ArrayList()); + } - activeBssidsStatus.setDetails(statusDetails); + } - activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); + } - } + @Override + public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { - ActiveBSSIDs statusDetails = (ActiveBSSIDs) activeBssidsStatus.getDetails(); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - List bssidList = statusDetails.getActiveBSSIDs(); - boolean bssidAlreadyPresent = false; - for (ActiveBSSID activeBssid : bssidList) { + if (ovsdbSession == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - if (activeBssid.getBssid().equals(bssid) && activeBssid.getSsid().equals(ssid) - && activeBssid.getRadioType().equals(radioType)) { - activeBssid.setNumDevicesConnected(vifState.getAssociatedClients().size()); - bssidAlreadyPresent = true; - break; - } + for (OpensyncAPRadioState radioState : radioStateTables) { + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - } + gatewayController.updateActiveCustomer(ce.getCustomerId()); - if (!bssidAlreadyPresent) { - ActiveBSSID newActiveBssid = new ActiveBSSID(); - newActiveBssid.setBssid(bssid); - newActiveBssid.setSsid(ssid); - newActiveBssid.setRadioType(radioType); - newActiveBssid.setNumDevicesConnected(vifState.getAssociatedClients().size()); - bssidList.add(newActiveBssid); - } + ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); - statusDetails.setActiveBSSIDs(bssidList); - activeBssidsStatus.setDetails(statusDetails); - activeBssidsStatus = statusServiceInterface.update(activeBssidsStatus); + if (radioState.getFreqBand().equals(RadioType.UNSUPPORTED)) { + LOG.debug("Could not get radio configuration for AP {}", apId); + continue; + } - } + if (radioState.getAllowedChannels() != null) { + apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setAllowedChannels(new ArrayList<>(radioState.getAllowedChannels())); - } + LOG.debug("Updated AllowedChannels from Wifi_Radio_State table change for AP {}", apId); - } + } - @Override - public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { + if (radioState.getTxPower() > 0) { + apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setEirpTxPower(AutoOrManualValue.createManualInstance(radioState.getTxPower())); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + LOG.debug("Updated TxPower from Wifi_Radio_State table change for AP {}", apId); + } - if (ovsdbSession == null) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + StateSetting state = StateSetting.disabled; + if (radioState.isEnabled()) { + state = StateSetting.enabled; + } - for (OpensyncAPRadioState radioState : radioStateTables) { - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + if (!apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).getRadioAdminState() + .equals(state)) { + // only update if changed + apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).setRadioAdminState(state); - gatewayController.updateActiveCustomer(ce.getCustomerId()); + LOG.debug("Updated RadioAdminState from Wifi_Radio_State table change for AP {}", apId); - ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + } - if (radioState.getFreqBand().equals(RadioType.UNSUPPORTED)) { - LOG.debug("Could not get radio configuration for AP {}", apId); - continue; - } + ce.setDetails(apElementConfiguration); + try { + 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); + } - if (radioState.getAllowedChannels() != null) { - apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setAllowedChannels(new ArrayList<>(radioState.getAllowedChannels())); + } - LOG.debug("Updated AllowedChannels from Wifi_Radio_State table change for AP {}", apId); + } - } + @Override + public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (radioState.getTxPower() > 0) { - apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); - apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) - .setEirpTxPower(AutoOrManualValue.createManualInstance(radioState.getTxPower())); + if (ovsdbSession == null) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - LOG.debug("Updated TxPower from Wifi_Radio_State table change for AP {}", apId); - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - StateSetting state = StateSetting.disabled; - if (radioState.isEnabled()) { - state = StateSetting.enabled; - } + if (inetStateTables == null || inetStateTables.isEmpty() || apId == null) { + return; + } - if (!apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).getRadioAdminState() - .equals(state)) { - // only update if changed - apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).setRadioAdminState(state); + for (OpensyncAPInetState inetState : inetStateTables) { + // TODO: implement me + } - LOG.debug("Updated RadioAdminState from Wifi_Radio_State table change for AP {}", apId); + } - } + @Override + public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, + String apId) { - ce.setDetails(apElementConfiguration); - try { - 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); - } + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - } + if (ovsdbSession == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - @Override - public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + long equipmentId = ce.getId(); - if (ovsdbSession == null) { - LOG.debug("wifiInetStateDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiInetStateDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + if (wifiAssociatedClients == null || wifiAssociatedClients.isEmpty() || apId == null) { + return; + } - if (inetStateTables == null || inetStateTables.isEmpty() || apId == null) { - return; - } + } - for (OpensyncAPInetState inetState : inetStateTables) { - // TODO: implement me - } + @Override + public void awlanNodeDbTableUpdate(OpensyncAWLANNode opensyncAPState, String apId) { - } + Equipment ce = getCustomerEquipment(apId); + if (ce == null) { + LOG.debug("awlanNodeDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - @Override - public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, - String apId) { + long equipmentId = ce.getId(); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + if (equipmentId < 0L) { + LOG.debug("awlanNodeDbTableUpdate::Cannot get equipmentId {} for session {}", equipmentId); + return; + } - if (ovsdbSession == null) { - LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Session for AP {}", apId); - return; - } + // TODO: update config where applicable + } - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + @Override + public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { - long equipmentId = ce.getId(); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } + if (ovsdbSession == null) { + LOG.debug("wifiVIFStateDbTableDelete::Cannot get Session for AP {}", apId); + return; + } - if (wifiAssociatedClients == null || wifiAssociatedClients.isEmpty() || apId == null) { - return; - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiVIFStateDbTableDelete::Cannot get Equipment for AP {}", apId); + return; + } - // TODO: update activeBSSDs, etc based on associated clients + long equipmentId = ce.getId(); - } + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } - @Override - public void awlanNodeDbTableUpdate(OpensyncAWLANNode opensyncAPState, String apId) { + // TODO: if applicable, remove SsidProfiles related to deleted VIF rows + // for this AP + } - Equipment ce = getCustomerEquipment(apId); - if (ce == null) { - LOG.debug("awlanNodeDbTableUpdate::Cannot get Equipment for AP {}", apId); - return; - } + @Override + public void wifiAssociatedClientsDbTableDelete(String deletedClientMac, String apId) { - long equipmentId = ce.getId(); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (equipmentId < 0L) { - LOG.debug("awlanNodeDbTableUpdate::Cannot get equipmentId {} for session {}", equipmentId); - return; - } + if (ovsdbSession == null) { + LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Session for AP {}", apId); + return; + } - // TODO: update config where applicable - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Equipment for AP {}", apId); + return; + } + long equipmentId = ce.getId(); - @Override - public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + // TODO: update activeBSSDs, etc based on associated clients, client + // information, etc - if (ovsdbSession == null) { - LOG.debug("wifiVIFStateDbTableDelete::Cannot get Session for AP {}", apId); - return; - } - - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiVIFStateDbTableDelete::Cannot get Equipment for AP {}", apId); - return; - } - - long equipmentId = ce.getId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - // TODO: if applicable, remove SsidProfiles related to deleted VIF rows - // for this AP - } - - @Override - public void wifiAssociatedClientsDbTableDelete(String deletedClientMac, String apId) { - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession == null) { - LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Session for AP {}", apId); - return; - } - - Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); - if (ce == null) { - LOG.debug("wifiAssociatedClientsDbTableDelete::Cannot get Equipment for AP {}", apId); - return; - } - long equipmentId = ce.getId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - // TODO: update activeBSSDs, etc based on associated clients, client - // information, etc - - } + } } diff --git a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/ConnectusOvsdbClient.java b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/ConnectusOvsdbClient.java index f2ca137..4cfd1f3 100644 --- a/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/ConnectusOvsdbClient.java +++ b/opensync-gateway/src/main/java/com/telecominfraproject/wlan/opensync/ovsdb/ConnectusOvsdbClient.java @@ -108,8 +108,7 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { LOG.info("ovsdbClient connectedClients = {}", ConnectusOvsdbClient.this.ovsdbSessionMapInterface.getNumSessions()); - } - catch (Exception e) { + } catch (Exception e) { LOG.error("ovsdbClient error", e); // something is wrong with the SSL ovsdbClient.shutdown(); @@ -126,8 +125,7 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { try { subjectDn = ((X509Certificate) ovsdbClient.getConnectionInfo().getRemoteCertificate()) .getSubjectDN().getName(); - } - catch (Exception e) { + } catch (Exception e) { // do nothing } @@ -153,8 +151,7 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { ovsdbClient.cancelMonitor(OvsdbDao.wifiAssociatedClientsDbTable + "_" + key); ovsdbClient.cancelMonitor(OvsdbDao.awlanNodeDbTable + "_" + key); - } - catch (OvsdbClientException e) { + } catch (OvsdbClientException e) { LOG.warn("Could not cancel Monitor {}", e.getMessage()); } @@ -185,29 +182,27 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { String apId = clientCn + "_" + connectNodeInfo.serialNumber; OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); - - try { - ovsdbDao.provisionBridgePortInterface(ovsdbClient); - } - catch (Exception e) { - // TODO: for some AP configurations this 'may' not be necessary. - LOG.warn("Could not provision Bridge->Port->Interface mapping.", e); - } - - ovsdbDao.removeAllSsids(ovsdbClient); - if (opensyncAPConfig != null) { + try { + ovsdbDao.provisionBridgePortInterface(ovsdbClient); + } catch (Exception e) { + // TODO: for some AP configurations this 'may' not be necessary. + LOG.warn("Could not provision Bridge->Port->Interface mapping.", e); + } + + ovsdbDao.removeAllSsids(ovsdbClient); + ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); - } - - ovsdbDao.configureStats(ovsdbClient); + ovsdbDao.configureStats(ovsdbClient); + + // Check if device stats is configured in Wifi_Stats_Config table, + // provision it + // if needed + if (ovsdbDao.getDeviceStatsReportingInterval(ovsdbClient) != collectionIntervalSecDeviceStats) { + ovsdbDao.updateDeviceStatsReportingInterval(ovsdbClient, collectionIntervalSecDeviceStats); + } - // Check if device stats is configured in Wifi_Stats_Config table, - // provision it - // if needed - if (ovsdbDao.getDeviceStatsReportingInterval(ovsdbClient) != collectionIntervalSecDeviceStats) { - ovsdbDao.updateDeviceStatsReportingInterval(ovsdbClient, collectionIntervalSecDeviceStats); } // ovsdbDao.configureWifiInet(ovsdbClient); @@ -260,19 +255,19 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { } private void monitorOvsdbStateTables(OvsdbClient ovsdbClient, String key) throws OvsdbClientException { - CompletableFuture rsCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, - OvsdbDao.wifiRadioStateDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiRadioStateDbTable, - new MonitorRequest(new MonitorSelect(true, false, false, true)))), - new MonitorCallback() { + CompletableFuture rsCf = ovsdbClient + .monitor(OvsdbDao.ovsdbName, OvsdbDao.wifiRadioStateDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiRadioStateDbTable, + new MonitorRequest(new MonitorSelect(true, false, false, true)))), + new MonitorCallback() { - @Override - public void update(TableUpdates tableUpdates) { - extIntegrationInterface.wifiRadioStatusDbTableUpdate( - ovsdbDao.getOpensyncAPRadioState(tableUpdates, key, ovsdbClient), key); - } + @Override + public void update(TableUpdates tableUpdates) { + extIntegrationInterface.wifiRadioStatusDbTableUpdate( + ovsdbDao.getOpensyncAPRadioState(tableUpdates, key, ovsdbClient), key); + } - }); + }); extIntegrationInterface .wifiRadioStatusDbTableUpdate(ovsdbDao.getOpensyncAPRadioState(rsCf.join(), key, ovsdbClient), key); @@ -355,51 +350,54 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { extIntegrationInterface.wifiVIFStateDbTableUpdate(ovsdbDao.getOpensyncAPVIFState(vsCf.join(), key, ovsdbClient), key); - CompletableFuture acCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, - OvsdbDao.wifiAssociatedClientsDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiAssociatedClientsDbTable, - new MonitorRequest(new MonitorSelect(false, true, true, true)))), - new MonitorCallback() { + CompletableFuture acCf = ovsdbClient + .monitor(OvsdbDao.ovsdbName, OvsdbDao.wifiAssociatedClientsDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiAssociatedClientsDbTable, + new MonitorRequest(new MonitorSelect(false, true, true, true)))), + new MonitorCallback() { - @Override - public void update(TableUpdates tableUpdates) { + @Override + public void update(TableUpdates tableUpdates) { - boolean insertOrModify = false; - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + boolean insertOrModify = false; + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - if (rowUpdate.getOld() != null && rowUpdate.getNew() == null) { - insertOrModify = false; - Row row = rowUpdate.getOld(); - String deletedClientMac = row.getStringColumn("mac"); - extIntegrationInterface.wifiAssociatedClientsDbTableDelete(deletedClientMac, key); + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + if (rowUpdate.getOld() != null && rowUpdate.getNew() == null) { + insertOrModify = false; + Row row = rowUpdate.getOld(); + String deletedClientMac = row.getStringColumn("mac"); + extIntegrationInterface.wifiAssociatedClientsDbTableDelete(deletedClientMac, + key); + } + } + + } + + if (insertOrModify) { + extIntegrationInterface.wifiAssociatedClientsDbTableUpdate( + ovsdbDao.getOpensyncWifiAssociatedClients(tableUpdates, key, ovsdbClient), + key); } } - } - - if (insertOrModify) { - extIntegrationInterface.wifiAssociatedClientsDbTableUpdate( - ovsdbDao.getOpensyncWifiAssociatedClients(tableUpdates, key, ovsdbClient), key); - } - } - - }); + }); extIntegrationInterface.wifiAssociatedClientsDbTableUpdate( ovsdbDao.getOpensyncWifiAssociatedClients(acCf.join(), key, ovsdbClient), key); - CompletableFuture awCf = ovsdbClient.monitor( - OvsdbDao.ovsdbName, OvsdbDao.awlanNodeDbTable + "_" + key, new MonitorRequests(ImmutableMap - .of(OvsdbDao.awlanNodeDbTable, new MonitorRequest(new MonitorSelect(true, false, false, true)))), - new MonitorCallback() { + CompletableFuture awCf = ovsdbClient + .monitor(OvsdbDao.ovsdbName, OvsdbDao.awlanNodeDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.awlanNodeDbTable, + new MonitorRequest(new MonitorSelect(true, false, false, true)))), + new MonitorCallback() { - @Override - public void update(TableUpdates tableUpdates) { - extIntegrationInterface.awlanNodeDbTableUpdate( - ovsdbDao.getOpensyncAWLANNode(tableUpdates, key, ovsdbClient), key); - } + @Override + public void update(TableUpdates tableUpdates) { + extIntegrationInterface.awlanNodeDbTableUpdate( + ovsdbDao.getOpensyncAWLANNode(tableUpdates, key, ovsdbClient), key); + } - }); + }); extIntegrationInterface.awlanNodeDbTableUpdate(ovsdbDao.getOpensyncAWLANNode(awCf.join(), key, ovsdbClient), key); @@ -410,8 +408,7 @@ public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); try { session.getOvsdbClient().shutdown(); - } - catch (Exception e) { + } catch (Exception e) { LOG.error("Failed to close session to " + apId + " " + e.getLocalizedMessage()); return "Failed to close session to " + apId + " " + e.getLocalizedMessage(); 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 5a42c12..7f13a28 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 @@ -69,2654 +69,2656 @@ import com.vmware.ovsdb.service.OvsdbClient; @Component public class OvsdbDao { - private static final Logger LOG = LoggerFactory.getLogger(OvsdbDao.class); + private static final Logger LOG = LoggerFactory.getLogger(OvsdbDao.class); - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.managerAddr:3.88.149.10}") - private String managerIpAddr; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.managerAddr:3.88.149.10}") + private String managerIpAddr; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.region:Ottawa}") - public String region; - - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.listenPort:6640}") - private int ovsdbListenPort; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.region:Ottawa}") + public String region; + + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.listenPort:6640}") + private int ovsdbListenPort; - @org.springframework.beans.factory.annotation.Value("${connectus.mqttBroker.address:testportal.123wlan.com}") - private String mqttBrokerAddress; - - @org.springframework.beans.factory.annotation.Value("${connectus.mqttBroker.listenPort:1883}") - private int mqttBrokerListenPort; - - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.timeoutSec:30}") - private int ovsdbTimeoutSec; - - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_bridge:br-home}") - public String bridgeNameVifInterfaces; - - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio1:home-ap-24}") - public String ifName2pt4GHz; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio2:home-ap-l50}") - public String ifName5GHzL; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio0:home-ap-u50}") - public String ifName5GHzU; + @org.springframework.beans.factory.annotation.Value("${connectus.mqttBroker.address:testportal.123wlan.com}") + private String mqttBrokerAddress; + + @org.springframework.beans.factory.annotation.Value("${connectus.mqttBroker.listenPort:1883}") + private int mqttBrokerListenPort; + + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.timeoutSec:30}") + private int ovsdbTimeoutSec; + + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_bridge:br-home}") + public String bridgeNameVifInterfaces; + + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio1:home-ap-24}") + public String ifName2pt4GHz; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio2:home-ap-l50}") + public String ifName5GHzL; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-iface.default_radio0:home-ap-u50}") + public String ifName5GHzU; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio0:wifi2}") - public String radioName5GHzU; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio2:wifi1}") - public String radioName5GHzL; - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio1:wifi0}") - public String radioName2pt4GHz; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio0:wifi2}") + public String radioName5GHzU; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio2:wifi1}") + public String radioName5GHzL; + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.wifi-device.radio1:wifi0}") + public String radioName2pt4GHz; - public static final String ovsdbName = "Open_vSwitch"; - public static final String awlanNodeDbTable = "AWLAN_Node"; - public static final String wifiStatsConfigDbTable = "Wifi_Stats_Config"; - - public static final String interfaceDbTable = "Interface"; - public static final String portDbTable = "Port"; - public static final String bridgeDbTable = "Bridge"; - - public static final String wifiRadioConfigDbTable = "Wifi_Radio_Config"; - public static final String wifiRadioStateDbTable = "Wifi_Radio_State"; - - public static final String wifiVifConfigDbTable = "Wifi_VIF_Config"; - public static final String wifiVifStateDbTable = "Wifi_VIF_State"; - - public static final String wifiInetConfigDbTable = "Wifi_Inet_Config"; - public static final String wifiInetStateDbTable = "Wifi_Inet_State"; - - public static final String wifiAssociatedClientsDbTable = "Wifi_Associated_Clients"; - - public ConnectNodeInfo getConnectNodeInfo(OvsdbClient ovsdbClient) { - ConnectNodeInfo ret = new ConnectNodeInfo(); + public static final String ovsdbName = "Open_vSwitch"; + public static final String awlanNodeDbTable = "AWLAN_Node"; + public static final String wifiStatsConfigDbTable = "Wifi_Stats_Config"; + + public static final String interfaceDbTable = "Interface"; + public static final String portDbTable = "Port"; + public static final String bridgeDbTable = "Bridge"; + + public static final String wifiRadioConfigDbTable = "Wifi_Radio_Config"; + public static final String wifiRadioStateDbTable = "Wifi_Radio_State"; + + public static final String wifiVifConfigDbTable = "Wifi_VIF_Config"; + public static final String wifiVifStateDbTable = "Wifi_VIF_State"; + + public static final String wifiInetConfigDbTable = "Wifi_Inet_Config"; + public static final String wifiInetStateDbTable = "Wifi_Inet_State"; + + public static final String wifiAssociatedClientsDbTable = "Wifi_Associated_Clients"; + + public ConnectNodeInfo getConnectNodeInfo(OvsdbClient ovsdbClient) { + ConnectNodeInfo ret = new ConnectNodeInfo(); - try { - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("mqtt_settings"); - columns.add("redirector_addr"); - columns.add("manager_addr"); - columns.add("sku_number"); - columns.add("serial_number"); - columns.add("model"); - columns.add("firmware_version"); - columns.add("platform_version"); - columns.add("revision"); - - operations.add(new Select(awlanNodeDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Select from {}:", awlanNodeDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - Row row = null; - if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { - row = ((SelectResult) result[0]).getRows().iterator().next(); - } - - ret.mqttSettings = row != null ? row.getMapColumn("mqtt_settings") : null; - ret.redirectorAddr = row != null ? row.getStringColumn("redirector_addr") : null; - ret.managerAddr = row != null ? row.getStringColumn("manager_addr") : null; - - ret.platformVersion = row != null ? row.getStringColumn("platform_version") : null; - ret.firmwareVersion = row != null ? row.getStringColumn("firmware_version") : null; - - ret.revision = row != null ? row.getStringColumn("revision") : null; - - ret.skuNumber = getSingleValueFromSet(row, "sku_number"); - ret.serialNumber = getSingleValueFromSet(row, "serial_number"); - ret.model = getSingleValueFromSet(row, "model"); - - // now populate macAddress, ipV4Address from Wifi_Inet_State - // first look them up for if_name = br-wan - fillInIpAddressAndMac(ovsdbClient, ret, "br-wan"); - if (ret.ipV4Address == null || ret.macAddress == null) { - // when not found - look them up for if_name = br-lan - fillInIpAddressAndMac(ovsdbClient, ret, "br-lan"); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - return ret; - } - - public void fillInIpAddressAndMac(OvsdbClient ovsdbClient, ConnectNodeInfo connectNodeInfo, String ifName) { - try { - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - // populate macAddress, ipV4Address from Wifi_Inet_State - - columns.add("inet_addr"); - columns.add("hwaddr"); - - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); - - operations.add(new Select(wifiInetStateDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Select from {}:", wifiInetStateDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - Row row = null; - if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { - row = ((SelectResult) result[0]).getRows().iterator().next(); - connectNodeInfo.ipV4Address = getSingleValueFromSet(row, "inet_addr"); - connectNodeInfo.macAddress = row.getStringColumn("hwaddr"); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - } - - public ConnectNodeInfo updateConnectNodeInfoOnConnect(OvsdbClient ovsdbClient, String clientCn, - ConnectNodeInfo incomingConnectNodeInfo) { - ConnectNodeInfo ret = incomingConnectNodeInfo.clone(); - - try { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - // set device_mode = cloud - plume's APs do not use it - // updateColumns.put("device_mode", new Atom("cloud") ); - - // update sku_number if it was empty - if (ret.skuNumber == null || ret.skuNumber.isEmpty()) { - ret.skuNumber = "connectus.ai_" + ret.serialNumber; - updateColumns.put("sku_number", new Atom<>(ret.skuNumber)); - } - - // Configure the MQTT connection - // ovsh u AWLAN_Node - // mqtt_settings:ins:'["map",[["broker","testportal.123wlan.com"],["topics","/ap/dev-ap-0300/opensync"],["qos","0"],["port","1883"],["remote_log","1"]]]' - Map newMqttSettings = new HashMap<>(); - newMqttSettings.put("broker", mqttBrokerAddress); - newMqttSettings.put("topics", "/ap/" + clientCn + "_" + ret.serialNumber + "/opensync"); - newMqttSettings.put("port", "" + mqttBrokerListenPort); - newMqttSettings.put("compress", "zlib"); - newMqttSettings.put("qos", "0"); - newMqttSettings.put("remote_log", "1"); - - if (ret.mqttSettings == null || !ret.mqttSettings.equals(newMqttSettings)) { - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map mgttSettings = com.vmware.ovsdb.protocol.operation.notation.Map - .of(newMqttSettings); - ret.mqttSettings = newMqttSettings; - updateColumns.put("mqtt_settings", mgttSettings); - } - - if (!updateColumns.isEmpty()) { - Row row = new Row(updateColumns); - operations.add(new Update(awlanNodeDbTable, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Updated {}:", awlanNodeDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - return ret; - } - - /** - * @param ovsdbClient - * @return value of reporting_interval column for the stats_type=device from the - * Wifi_Stats_Config table. If value is not provisioned then return -1. - */ - public long getDeviceStatsReportingInterval(OvsdbClient ovsdbClient) { - long ret = -1; - try { - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - - columns.add("reporting_interval"); - columns.add("stats_type"); - columns.add("radio_type"); - - conditions.add(new Condition("stats_type", Function.EQUALS, new Atom<>("device"))); - - operations.add(new Select(wifiStatsConfigDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Select from {}:", wifiStatsConfigDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - Row row = null; - if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { - row = ((SelectResult) result[0]).getRows().iterator().next(); - ret = row.getIntegerColumn("reporting_interval"); - LOG.info("Stats collection for stats_type=device is already configured with reporting_interval = {}", - ret); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - return ret; - } - - /** - * @param ovsdbClient - * @param value of reporting_interval column for the stats_type=device - * from the Wifi_Stats_Config table. If value is not - * provisioned then return -1. - */ - public void updateDeviceStatsReportingInterval(OvsdbClient ovsdbClient, long newValue) { - try { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - // turn on stats collection over MQTT: (reporting_interval is in - // seconds?) - // $ ovsh i Wifi_Stats_Config reporting_interval:=10 - // radio_type:="2.4G" stats_type:="device" - - updateColumns.put("reporting_interval", new Atom<>(newValue)); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("stats_type", new Atom<>("device")); - - Row row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); + try { + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("mqtt_settings"); + columns.add("redirector_addr"); + columns.add("manager_addr"); + columns.add("sku_number"); + columns.add("serial_number"); + columns.add("model"); + columns.add("firmware_version"); + columns.add("platform_version"); + columns.add("revision"); + + operations.add(new Select(awlanNodeDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Select from {}:", awlanNodeDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + Row row = null; + if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { + row = ((SelectResult) result[0]).getRows().iterator().next(); + } + + ret.mqttSettings = row != null ? row.getMapColumn("mqtt_settings") : null; + ret.redirectorAddr = row != null ? row.getStringColumn("redirector_addr") : null; + ret.managerAddr = row != null ? row.getStringColumn("manager_addr") : null; + + ret.platformVersion = row != null ? row.getStringColumn("platform_version") : null; + ret.firmwareVersion = row != null ? row.getStringColumn("firmware_version") : null; + + ret.revision = row != null ? row.getStringColumn("revision") : null; + + ret.skuNumber = getSingleValueFromSet(row, "sku_number"); + ret.serialNumber = getSingleValueFromSet(row, "serial_number"); + ret.model = getSingleValueFromSet(row, "model"); + + // now populate macAddress, ipV4Address from Wifi_Inet_State + // first look them up for if_name = br-wan + fillInIpAddressAndMac(ovsdbClient, ret, "br-wan"); + if (ret.ipV4Address == null || ret.macAddress == null) { + // when not found - look them up for if_name = br-lan + fillInIpAddressAndMac(ovsdbClient, ret, "br-lan"); + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + return ret; + } + + public void fillInIpAddressAndMac(OvsdbClient ovsdbClient, ConnectNodeInfo connectNodeInfo, String ifName) { + try { + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + // populate macAddress, ipV4Address from Wifi_Inet_State + + columns.add("inet_addr"); + columns.add("hwaddr"); + + conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); + + operations.add(new Select(wifiInetStateDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Select from {}:", wifiInetStateDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + Row row = null; + if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { + row = ((SelectResult) result[0]).getRows().iterator().next(); + connectNodeInfo.ipV4Address = getSingleValueFromSet(row, "inet_addr"); + connectNodeInfo.macAddress = row.getStringColumn("hwaddr"); + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + } + + public ConnectNodeInfo updateConnectNodeInfoOnConnect(OvsdbClient ovsdbClient, String clientCn, + ConnectNodeInfo incomingConnectNodeInfo) { + ConnectNodeInfo ret = incomingConnectNodeInfo.clone(); + + try { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + // set device_mode = cloud - plume's APs do not use it + // updateColumns.put("device_mode", new Atom("cloud") ); + + // update sku_number if it was empty + if (ret.skuNumber == null || ret.skuNumber.isEmpty()) { + ret.skuNumber = "connectus.ai_" + ret.serialNumber; + updateColumns.put("sku_number", new Atom<>(ret.skuNumber)); + } + + // Configure the MQTT connection + // ovsh u AWLAN_Node + // mqtt_settings:ins:'["map",[["broker","testportal.123wlan.com"],["topics","/ap/dev-ap-0300/opensync"],["qos","0"],["port","1883"],["remote_log","1"]]]' + Map newMqttSettings = new HashMap<>(); + newMqttSettings.put("broker", mqttBrokerAddress); + newMqttSettings.put("topics", "/ap/" + clientCn + "_" + ret.serialNumber + "/opensync"); + newMqttSettings.put("port", "" + mqttBrokerListenPort); + newMqttSettings.put("compress", "zlib"); + newMqttSettings.put("qos", "0"); + newMqttSettings.put("remote_log", "1"); + + if (ret.mqttSettings == null || !ret.mqttSettings.equals(newMqttSettings)) { + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map mgttSettings = com.vmware.ovsdb.protocol.operation.notation.Map + .of(newMqttSettings); + ret.mqttSettings = newMqttSettings; + updateColumns.put("mqtt_settings", mgttSettings); + } + + if (!updateColumns.isEmpty()) { + Row row = new Row(updateColumns); + operations.add(new Update(awlanNodeDbTable, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Updated {}:", awlanNodeDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + return ret; + } + + /** + * @param ovsdbClient + * @return value of reporting_interval column for the stats_type=device from + * the Wifi_Stats_Config table. If value is not provisioned then + * return -1. + */ + public long getDeviceStatsReportingInterval(OvsdbClient ovsdbClient) { + long ret = -1; + try { + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + + columns.add("reporting_interval"); + columns.add("stats_type"); + columns.add("radio_type"); + + conditions.add(new Condition("stats_type", Function.EQUALS, new Atom<>("device"))); + + operations.add(new Select(wifiStatsConfigDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Select from {}:", wifiStatsConfigDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + Row row = null; + if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { + row = ((SelectResult) result[0]).getRows().iterator().next(); + ret = row.getIntegerColumn("reporting_interval"); + LOG.info("Stats collection for stats_type=device is already configured with reporting_interval = {}", + ret); + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + return ret; + } + + /** + * @param ovsdbClient + * @param value + * of reporting_interval column for the stats_type=device from + * the Wifi_Stats_Config table. If value is not provisioned then + * return -1. + */ + public void updateDeviceStatsReportingInterval(OvsdbClient ovsdbClient, long newValue) { + try { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + // turn on stats collection over MQTT: (reporting_interval is in + // seconds?) + // $ ovsh i Wifi_Stats_Config reporting_interval:=10 + // radio_type:="2.4G" stats_type:="device" + + updateColumns.put("reporting_interval", new Atom<>(newValue)); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("stats_type", new Atom<>("device")); + + Row row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + if (LOG.isDebugEnabled()) { + LOG.debug("Updated {}:", wifiStatsConfigDbTable); - if (LOG.isDebugEnabled()) { - LOG.debug("Updated {}:", wifiStatsConfigDbTable); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + } + + public void performRedirect(OvsdbClient ovsdbClient, String clientCn) { + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("manager_addr"); + columns.add("sku_number"); + columns.add("serial_number"); + columns.add("model"); + columns.add("firmware_version"); + + try { + LOG.debug("Starting Redirect"); + + operations.add(new Select(awlanNodeDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - } - - public void performRedirect(OvsdbClient ovsdbClient, String clientCn) { - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("manager_addr"); - columns.add("sku_number"); - columns.add("serial_number"); - columns.add("model"); - columns.add("firmware_version"); + LOG.debug("Select from AWLAN_Node:"); - try { - LOG.debug("Starting Redirect"); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - operations.add(new Select(awlanNodeDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + String skuNumber = null; + String serialNumber = null; + String model = null; + String firmwareVersion = null; - LOG.debug("Select from AWLAN_Node:"); + Row row = null; + if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { + row = ((SelectResult) result[0]).getRows().iterator().next(); + } - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + firmwareVersion = row != null ? row.getStringColumn("firmware_version") : null; - String skuNumber = null; - String serialNumber = null; - String model = null; - String firmwareVersion = null; + skuNumber = getSingleValueFromSet(row, "sku_number"); + serialNumber = getSingleValueFromSet(row, "serial_number"); + model = getSingleValueFromSet(row, "model"); - Row row = null; - if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { - row = ((SelectResult) result[0]).getRows().iterator().next(); - } + LOG.info("Redirecting AP Node: clientCn {} serialNumber {} model {} firmwareVersion {} skuNumber {}", + clientCn, serialNumber, model, firmwareVersion, skuNumber); - firmwareVersion = row != null ? row.getStringColumn("firmware_version") : null; + // Update table AWLAN_Node - set manager_addr + operations.clear(); + Map updateColumns = new HashMap<>(); - skuNumber = getSingleValueFromSet(row, "sku_number"); - serialNumber = getSingleValueFromSet(row, "serial_number"); - model = getSingleValueFromSet(row, "model"); + updateColumns.put("manager_addr", new Atom<>("ssl:" + managerIpAddr + ":" + ovsdbListenPort)); - LOG.info("Redirecting AP Node: clientCn {} serialNumber {} model {} firmwareVersion {} skuNumber {}", - clientCn, serialNumber, model, firmwareVersion, skuNumber); + row = new Row(updateColumns); + operations.add(new Update(awlanNodeDbTable, row)); - // Update table AWLAN_Node - set manager_addr - operations.clear(); - Map updateColumns = new HashMap<>(); + fResult = ovsdbClient.transact(ovsdbName, operations); + result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - updateColumns.put("manager_addr", new Atom<>("ssl:" + managerIpAddr + ":" + ovsdbListenPort)); + LOG.debug("Updated AWLAN_Node:"); - row = new Row(updateColumns); - operations.add(new Update(awlanNodeDbTable, row)); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - fResult = ovsdbClient.transact(ovsdbName, operations); - result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + LOG.debug("Redirect Done"); + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error when redirecting AP Node", e); + throw new RuntimeException(e); + } - LOG.debug("Updated AWLAN_Node:"); + } - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + public Set getSet(Row row, String columnName) { - LOG.debug("Redirect Done"); - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error when redirecting AP Node", e); - throw new RuntimeException(e); - } + Set set = row != null ? row.getSetColumn(columnName) : null; - } + return set; + } - public Set getSet(Row row, String columnName) { + public T getSingleValueFromSet(Row row, String columnName) { - Set set = row != null ? row.getSetColumn(columnName) : null; + Set set = row != null ? row.getSetColumn(columnName) : null; + T ret = set != null && !set.isEmpty() ? set.iterator().next() : null; - return set; - } + return ret; + } - public T getSingleValueFromSet(Row row, String columnName) { + public Map getProvisionedInterfaces(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); - Set set = row != null ? row.getSetColumn(columnName) : null; - T ret = set != null && !set.isEmpty() ? set.iterator().next() : null; + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("name"); + columns.add("type"); + columns.add("options"); + columns.add("_uuid"); + columns.add("ofport"); + columns.add("mtu"); + columns.add("ifindex"); + columns.add("link_state"); + columns.add("admin_state"); - return ret; - } + try { + LOG.debug("Retrieving Interfaces:"); - public Map getProvisionedInterfaces(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); + operations.add(new Select(interfaceDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("name"); - columns.add("type"); - columns.add("options"); - columns.add("_uuid"); - columns.add("ofport"); - columns.add("mtu"); - columns.add("ifindex"); - columns.add("link_state"); - columns.add("admin_state"); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - try { - LOG.debug("Retrieving Interfaces:"); + for (Row row : ((SelectResult) result[0]).getRows()) { - operations.add(new Select(interfaceDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + InterfaceInfo interfaceInfo = new InterfaceInfo(); + interfaceInfo.name = row.getStringColumn("name"); + interfaceInfo.type = row.getStringColumn("type"); + interfaceInfo.uuid = row.getUuidColumn("_uuid"); - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + Long tmp = getSingleValueFromSet(row, "ofport"); + interfaceInfo.ofport = tmp != null ? tmp.intValue() : 0; - for (Row row : ((SelectResult) result[0]).getRows()) { + tmp = getSingleValueFromSet(row, "mtu"); + interfaceInfo.mtu = tmp != null ? tmp.intValue() : 0; - InterfaceInfo interfaceInfo = new InterfaceInfo(); - interfaceInfo.name = row.getStringColumn("name"); - interfaceInfo.type = row.getStringColumn("type"); - interfaceInfo.uuid = row.getUuidColumn("_uuid"); + tmp = getSingleValueFromSet(row, "ifindex"); + interfaceInfo.ifIndex = tmp != null ? tmp.intValue() : 0; - Long tmp = getSingleValueFromSet(row, "ofport"); - interfaceInfo.ofport = tmp != null ? tmp.intValue() : 0; + String tmpStr = getSingleValueFromSet(row, "link_state"); + interfaceInfo.linkState = tmpStr != null ? tmpStr : ""; - tmp = getSingleValueFromSet(row, "mtu"); - interfaceInfo.mtu = tmp != null ? tmp.intValue() : 0; + tmpStr = getSingleValueFromSet(row, "admin_state"); + interfaceInfo.adminState = tmpStr != null ? tmpStr : ""; - tmp = getSingleValueFromSet(row, "ifindex"); - interfaceInfo.ifIndex = tmp != null ? tmp.intValue() : 0; + interfaceInfo.options = row.getMapColumn("options"); - String tmpStr = getSingleValueFromSet(row, "link_state"); - interfaceInfo.linkState = tmpStr != null ? tmpStr : ""; + ret.put(interfaceInfo.name, interfaceInfo); + } - tmpStr = getSingleValueFromSet(row, "admin_state"); - interfaceInfo.adminState = tmpStr != null ? tmpStr : ""; + LOG.debug("Retrieved Interfaces: {}", ret); - interfaceInfo.options = row.getMapColumn("options"); + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedInterfaces", e); - ret.put(interfaceInfo.name, interfaceInfo); - } + throw new RuntimeException(e); + } - LOG.debug("Retrieved Interfaces: {}", ret); + return ret; + } - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedInterfaces", e); + public Map getProvisionedPorts(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); - throw new RuntimeException(e); - } + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("name"); + columns.add("_uuid"); + columns.add("interfaces"); - return ret; - } + try { + LOG.debug("Retrieving Ports:"); - public Map getProvisionedPorts(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); + operations.add(new Select(portDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("name"); - columns.add("_uuid"); - columns.add("interfaces"); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - try { - LOG.debug("Retrieving Ports:"); + for (Row row : ((SelectResult) result[0]).getRows()) { - operations.add(new Select(portDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + PortInfo portInfo = new PortInfo(); + portInfo.name = row.getStringColumn("name"); + portInfo.uuid = row.getUuidColumn("_uuid"); + portInfo.interfaceUuids = row.getSetColumn("interfaces"); - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + ret.put(portInfo.name, portInfo); + } + + LOG.debug("Retrieved Ports: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedPorts", e); + throw new RuntimeException(e); + } + + return ret; + } + + public Map getProvisionedBridges(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("name"); + columns.add("_uuid"); + columns.add("ports"); + + try { + LOG.debug("Retrieving Bridges:"); + + operations.add(new Select(bridgeDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + for (Row row : ((SelectResult) result[0]).getRows()) { + + BridgeInfo bridgeInfo = new BridgeInfo(); + bridgeInfo.name = row.getStringColumn("name"); + bridgeInfo.uuid = row.getUuidColumn("_uuid"); + bridgeInfo.portUuids = row.getSetColumn("ports"); + + ret.put(bridgeInfo.name, bridgeInfo); + } + + LOG.debug("Retrieved Bridges: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedBridges", e); + throw new RuntimeException(e); + } + + return ret; + } + + public Map getProvisionedWifiRadioConfigs(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + + columns.add("_uuid"); + columns.add("if_name"); + columns.add("bcn_int"); + columns.add("channel"); + columns.add("channel_mode"); + columns.add("country"); + columns.add("enabled"); + columns.add("ht_mode"); + columns.add("tx_power"); + columns.add("vif_configs"); + columns.add("freq_band"); + columns.add("hw_config"); + columns.add("hw_type"); + + try { + LOG.debug("Retrieving WifiRadioConfig:"); + + operations.add(new Select(wifiRadioConfigDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + for (Row row : ((SelectResult) result[0]).getRows()) { + + WifiRadioConfigInfo wifiRadioConfigInfo = new WifiRadioConfigInfo(); + wifiRadioConfigInfo.uuid = row.getUuidColumn("_uuid"); + wifiRadioConfigInfo.ifName = row.getStringColumn("if_name"); + Long beaconTmp = getSingleValueFromSet(row, "bcn_int"); + if (beaconTmp == null) { + beaconTmp = 0L; + } + wifiRadioConfigInfo.beaconInterval = beaconTmp.intValue(); + Long channelTmp = getSingleValueFromSet(row, "channel"); + if (channelTmp == null) { + channelTmp = -1L; + } + wifiRadioConfigInfo.channel = channelTmp.intValue(); + wifiRadioConfigInfo.channelMode = getSingleValueFromSet(row, "channel_mode"); + wifiRadioConfigInfo.country = getSingleValueFromSet(row, "country"); + Boolean tmp = getSingleValueFromSet(row, "enabled"); + wifiRadioConfigInfo.enabled = tmp != null ? tmp : false; + wifiRadioConfigInfo.htMode = getSingleValueFromSet(row, "ht_mode"); + wifiRadioConfigInfo.txPower = getSingleValueFromSet(row, "txPower"); + wifiRadioConfigInfo.vifConfigUuids = row.getSetColumn("vif_configs"); + wifiRadioConfigInfo.freqBand = row.getStringColumn("freq_band"); + wifiRadioConfigInfo.hwConfig = row.getMapColumn("hw_config"); + wifiRadioConfigInfo.hwType = row.getStringColumn("hw_type"); + ret.put(wifiRadioConfigInfo.ifName, wifiRadioConfigInfo); + } + + LOG.debug("Retrieved WifiRadioConfig: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedWifiRadioConfigs", e); + throw new RuntimeException(e); + } + + return ret; + } + + public Map getProvisionedWifiVifConfigs(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("bridge"); + columns.add("ap_bridge"); + columns.add("_uuid"); + columns.add("btm"); + columns.add("enabled"); + columns.add("ft_psk"); + columns.add("group_rekey"); + columns.add("if_name"); + columns.add("min_hw_mode"); + columns.add("mode"); + columns.add("rrm"); + columns.add("ssid"); + columns.add("ssid_broadcast"); + columns.add("uapsd_enable"); + columns.add("vif_radio_idx"); + columns.add("security"); + columns.add("vlan_id"); + + try { + LOG.debug("Retrieving WifiVifConfig:"); + + operations.add(new Select(wifiVifConfigDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + for (Row row : ((SelectResult) result[0]).getRows()) { + + WifiVifConfigInfo wifiVifConfigInfo = new WifiVifConfigInfo(); + wifiVifConfigInfo.bridge = row.getStringColumn("bridge"); + wifiVifConfigInfo.apBridge = row.getBooleanColumn("ap_bridge"); + wifiVifConfigInfo.uuid = row.getUuidColumn("_uuid"); + wifiVifConfigInfo.btm = row.getIntegerColumn("btm").intValue(); + wifiVifConfigInfo.enabled = row.getBooleanColumn("enabled"); + wifiVifConfigInfo.ftPsk = row.getIntegerColumn("ft_psk").intValue(); + wifiVifConfigInfo.groupRekey = row.getIntegerColumn("group_rekey").intValue(); + wifiVifConfigInfo.minHwMode = row.getStringColumn("min_hw_mode"); + wifiVifConfigInfo.ifName = row.getStringColumn("if_name"); + wifiVifConfigInfo.mode = row.getStringColumn("mode"); + wifiVifConfigInfo.rrm = row.getIntegerColumn("rrm").intValue(); + wifiVifConfigInfo.ssid = row.getStringColumn("ssid"); + wifiVifConfigInfo.ssidBroadcast = row.getStringColumn("ssid_broadcast"); + wifiVifConfigInfo.uapsdEnable = row.getBooleanColumn("uapsd_enable"); + Long radioIdxTmp = getSingleValueFromSet(row, "vif_radio_idx"); + if (radioIdxTmp == null) { + radioIdxTmp = 0L; + } + wifiVifConfigInfo.vifRadioIdx = radioIdxTmp.intValue(); + wifiVifConfigInfo.security = row.getMapColumn("security"); + + if (row.getColumns().get("vlan_id") != null && row.getColumns().get("vlan_id").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiVifConfigInfo.vlanId = row.getIntegerColumn("vlan_id").intValue(); + } + ret.put(wifiVifConfigInfo.ifName + '_' + wifiVifConfigInfo.ssid, wifiVifConfigInfo); + } + + LOG.debug("Retrieved WifiVifConfigs: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedWifiVifConfigs", e); + throw new RuntimeException(e); + } + + return ret; + } + + public Map getProvisionedWifiInetConfigs(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("NAT"); + columns.add("_uuid"); + columns.add("broadcast"); + columns.add("enabled"); + columns.add("if_name"); + columns.add("if_type"); + columns.add("ip_assign_scheme"); + columns.add("network"); + columns.add("inet_addr"); + columns.add("mtu"); + columns.add("netmask"); + columns.add("vlan_id"); + + try { + LOG.debug("Retrieving WifiInetConfig:"); + + operations.add(new Select(wifiInetConfigDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + for (Row row : ((SelectResult) result[0]).getRows()) { + + WifiInetConfigInfo wifiInetConfigInfo = new WifiInetConfigInfo(); + Boolean natTmp = getSingleValueFromSet(row, "NAT"); + wifiInetConfigInfo.nat = natTmp != null ? natTmp : false; + + wifiInetConfigInfo.uuid = row.getUuidColumn("_uuid"); + if (row.getColumns().get("broadcast") != null && row.getColumns().get("broadcast").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiInetConfigInfo.broadcast = row.getStringColumn("broadcast"); + } + wifiInetConfigInfo.enabled = row.getBooleanColumn("enabled"); + wifiInetConfigInfo.ifName = row.getStringColumn("if_name"); + wifiInetConfigInfo.ifType = row.getStringColumn("if_type"); + wifiInetConfigInfo.ipAssignScheme = row.getStringColumn("ip_assign_scheme"); + wifiInetConfigInfo.network = row.getBooleanColumn("network"); + if (row.getColumns().get("inet_addr") != null && row.getColumns().get("inet_addr").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiInetConfigInfo.inetAddr = row.getStringColumn("inet_addr"); + } + if (row.getColumns().get("mtu") != null && row.getColumns().get("mtu").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiInetConfigInfo.mtu = row.getIntegerColumn("mtu").intValue(); + } + if (row.getColumns().get("netmask") != null && row.getColumns().get("netmask").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiInetConfigInfo.netmask = row.getStringColumn("netmask"); + } + if (row.getColumns().get("vlan_id") != null && row.getColumns().get("vlan_id").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + wifiInetConfigInfo.vlanId = row.getIntegerColumn("vlan_id").intValue(); + } + ret.put(wifiInetConfigInfo.ifName, wifiInetConfigInfo); + } + + LOG.debug("Retrieved WifiInetConfigs: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedWifiInetConfigs", e); + throw new RuntimeException(e); + } + + return ret; + } + + public Map getProvisionedWifiStatsConfigs(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); + + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("channel_list"); + columns.add("radio_type"); + columns.add("reporting_interval"); + columns.add("sampling_interval"); + columns.add("stats_type"); + columns.add("survey_interval_ms"); + columns.add("survey_type"); + columns.add("threshold"); + columns.add("_uuid"); + + try { + LOG.debug("Retrieving WifiStatsConfigs:"); + + operations.add(new Select(wifiStatsConfigDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + for (Row row : ((SelectResult) result[0]).getRows()) { + + WifiStatsConfigInfo wifiStatsConfigInfo = new WifiStatsConfigInfo(); + + wifiStatsConfigInfo.channelList = row.getSetColumn("channel_list"); + wifiStatsConfigInfo.radioType = row.getStringColumn("radio_type"); + wifiStatsConfigInfo.reportingInterval = row.getIntegerColumn("reporting_interval").intValue(); + wifiStatsConfigInfo.samplingInterval = row.getIntegerColumn("sampling_interval").intValue(); + wifiStatsConfigInfo.statsType = row.getStringColumn("stats_type"); + wifiStatsConfigInfo.surveyType = getSingleValueFromSet(row, "survey_type"); + Long tmp = getSingleValueFromSet(row, "survey_interval_ms"); + wifiStatsConfigInfo.surveyIntervalMs = tmp != null ? tmp.intValue() : 0; + wifiStatsConfigInfo.threshold = row.getMapColumn("threshold"); + wifiStatsConfigInfo.uuid = row.getUuidColumn("_uuid"); + + if (wifiStatsConfigInfo.surveyType == null) { + ret.put(wifiStatsConfigInfo.radioType + "_" + wifiStatsConfigInfo.statsType, wifiStatsConfigInfo); + } else { + ret.put(wifiStatsConfigInfo.radioType + "_" + wifiStatsConfigInfo.statsType + "_" + + wifiStatsConfigInfo.surveyType, wifiStatsConfigInfo); + + } + } + + LOG.debug("Retrieved WifiStatsConfigs: {}", ret); + + } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedWifiStatsConfigs", e); + + throw new RuntimeException(e); + } + + return ret; + } + + public void provisionSingleBridgePortInterface(OvsdbClient ovsdbClient, String interfaceName, String bridgeName, + String interfaceType, Map interfaceOptions, + Map provisionedInterfaces, Map provisionedPorts, + Map provisionedBridges) + throws OvsdbClientException, TimeoutException, ExecutionException, InterruptedException { + + LOG.debug("InterfaceName {} BridgeName {} InterfaceType {}", interfaceName, bridgeName, interfaceType); + if (!provisionedInterfaces.containsKey(interfaceName)) { + // Create this interface and link it to the port and the bridge + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); + + updateColumns.put("name", new Atom<>(interfaceName)); + if (interfaceType != null) { + updateColumns.put("type", new Atom<>(interfaceType)); + } + // updateColumns.put("admin_state", new Atom("up") ); + // updateColumns.put("link_state", new Atom("up") ); + // updateColumns.put("ifindex", new Atom(ifIndex) ); + // updateColumns.put("mtu", new Atom(1500) ); + // updateColumns.put("ofport", new Atom(ofport) ); + + if (interfaceOptions != null) { + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map ifOptions = com.vmware.ovsdb.protocol.operation.notation.Map + .of(interfaceOptions); + updateColumns.put("options", ifOptions); + } + + Uuid interfaceUuid = null; + + Row row = new Row(updateColumns); + operations.add(new Insert(interfaceDbTable, row)); + + { + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned Interface for {}", interfaceName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + if (res instanceof InsertResult) { + interfaceUuid = ((InsertResult) res).getUuid(); + } + } + } + + if (interfaceUuid == null) { + throw new IllegalStateException("Interface entry was not created successfully"); + } + + Uuid portUuid = null; + operations = new ArrayList<>(); + // link the interface to the port, create port if necessary + if (!provisionedPorts.containsKey(interfaceName)) { + // need to create port + updateColumns = new HashMap<>(); + + // portUuid = new Uuid(new UUID(System.currentTimeMillis(), + // System.nanoTime())) ; + updateColumns.put("name", new Atom<>(interfaceName)); + // updateColumns.put("_uuid", new Atom(portUuid)); + + Set portInterfacesSet = new HashSet<>(); + portInterfacesSet.add(interfaceUuid); + com.vmware.ovsdb.protocol.operation.notation.Set portInterfaces = com.vmware.ovsdb.protocol.operation.notation.Set + .of(portInterfacesSet); + updateColumns.put("interfaces", portInterfaces); + + row = new Row(updateColumns); + operations.add(new Insert(portDbTable, row)); + + { + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned Port for {}", interfaceName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + if (res instanceof InsertResult) { + portUuid = ((InsertResult) res).getUuid(); + } + } + } + + } else { + // need to update port + PortInfo existingPort = provisionedPorts.get(interfaceName); + portUuid = existingPort.uuid; + + conditions = new ArrayList<>(); + updateColumns = new HashMap<>(); + + conditions.add(new Condition("name", Function.EQUALS, new Atom<>(interfaceName))); + + Set portInterfacesSet = new HashSet<>(); + if (existingPort.interfaceUuids != null) { + portInterfacesSet.addAll(existingPort.interfaceUuids); + } + portInterfacesSet.add(interfaceUuid); + com.vmware.ovsdb.protocol.operation.notation.Set portInterfaces = com.vmware.ovsdb.protocol.operation.notation.Set + .of(portInterfacesSet); + updateColumns.put("interfaces", portInterfaces); + + row = new Row(updateColumns); + operations.add(new Update(portDbTable, row)); + + { + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Updated Port for {}", interfaceName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + } - for (Row row : ((SelectResult) result[0]).getRows()) { + if (portUuid == null) { + throw new IllegalStateException("Port entry was not created successfully"); + } - PortInfo portInfo = new PortInfo(); - portInfo.name = row.getStringColumn("name"); - portInfo.uuid = row.getUuidColumn("_uuid"); - portInfo.interfaceUuids = row.getSetColumn("interfaces"); + operations = new ArrayList<>(); - ret.put(portInfo.name, portInfo); - } - - LOG.debug("Retrieved Ports: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedPorts", e); - throw new RuntimeException(e); - } - - return ret; - } - - public Map getProvisionedBridges(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("name"); - columns.add("_uuid"); - columns.add("ports"); - - try { - LOG.debug("Retrieving Bridges:"); - - operations.add(new Select(bridgeDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - for (Row row : ((SelectResult) result[0]).getRows()) { - - BridgeInfo bridgeInfo = new BridgeInfo(); - bridgeInfo.name = row.getStringColumn("name"); - bridgeInfo.uuid = row.getUuidColumn("_uuid"); - bridgeInfo.portUuids = row.getSetColumn("ports"); - - ret.put(bridgeInfo.name, bridgeInfo); - } - - LOG.debug("Retrieved Bridges: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedBridges", e); - throw new RuntimeException(e); - } - - return ret; - } - - public Map getProvisionedWifiRadioConfigs(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - - columns.add("_uuid"); - columns.add("if_name"); - columns.add("bcn_int"); - columns.add("channel"); - columns.add("channel_mode"); - columns.add("country"); - columns.add("enabled"); - columns.add("ht_mode"); - columns.add("tx_power"); - columns.add("vif_configs"); - columns.add("freq_band"); - columns.add("hw_config"); - columns.add("hw_type"); - - try { - LOG.debug("Retrieving WifiRadioConfig:"); - - operations.add(new Select(wifiRadioConfigDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - for (Row row : ((SelectResult) result[0]).getRows()) { - - WifiRadioConfigInfo wifiRadioConfigInfo = new WifiRadioConfigInfo(); - wifiRadioConfigInfo.uuid = row.getUuidColumn("_uuid"); - wifiRadioConfigInfo.ifName = row.getStringColumn("if_name"); - Long beaconTmp = getSingleValueFromSet(row, "bcn_int"); - if (beaconTmp == null) { - beaconTmp = 0L; - } - wifiRadioConfigInfo.beaconInterval = beaconTmp.intValue(); - Long channelTmp = getSingleValueFromSet(row, "channel"); - if (channelTmp == null) { - channelTmp = -1L; - } - wifiRadioConfigInfo.channel = channelTmp.intValue(); - wifiRadioConfigInfo.channelMode = getSingleValueFromSet(row, "channel_mode"); - wifiRadioConfigInfo.country = getSingleValueFromSet(row, "country"); - Boolean tmp = getSingleValueFromSet(row, "enabled"); - wifiRadioConfigInfo.enabled = tmp != null ? tmp : false; - wifiRadioConfigInfo.htMode = getSingleValueFromSet(row, "ht_mode"); - wifiRadioConfigInfo.txPower = getSingleValueFromSet(row, "txPower"); - wifiRadioConfigInfo.vifConfigUuids = row.getSetColumn("vif_configs"); - wifiRadioConfigInfo.freqBand = row.getStringColumn("freq_band"); - wifiRadioConfigInfo.hwConfig = row.getMapColumn("hw_config"); - wifiRadioConfigInfo.hwType = row.getStringColumn("hw_type"); - ret.put(wifiRadioConfigInfo.ifName, wifiRadioConfigInfo); - } - - LOG.debug("Retrieved WifiRadioConfig: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedWifiRadioConfigs", e); - throw new RuntimeException(e); - } - - return ret; - } - - public Map getProvisionedWifiVifConfigs(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("bridge"); - columns.add("ap_bridge"); - columns.add("_uuid"); - columns.add("btm"); - columns.add("enabled"); - columns.add("ft_psk"); - columns.add("group_rekey"); - columns.add("if_name"); - columns.add("min_hw_mode"); - columns.add("mode"); - columns.add("rrm"); - columns.add("ssid"); - columns.add("ssid_broadcast"); - columns.add("uapsd_enable"); - columns.add("vif_radio_idx"); - columns.add("security"); - columns.add("vlan_id"); - - try { - LOG.debug("Retrieving WifiVifConfig:"); - - operations.add(new Select(wifiVifConfigDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - for (Row row : ((SelectResult) result[0]).getRows()) { - - WifiVifConfigInfo wifiVifConfigInfo = new WifiVifConfigInfo(); - wifiVifConfigInfo.bridge = row.getStringColumn("bridge"); - wifiVifConfigInfo.apBridge = row.getBooleanColumn("ap_bridge"); - wifiVifConfigInfo.uuid = row.getUuidColumn("_uuid"); - wifiVifConfigInfo.btm = row.getIntegerColumn("btm").intValue(); - wifiVifConfigInfo.enabled = row.getBooleanColumn("enabled"); - wifiVifConfigInfo.ftPsk = row.getIntegerColumn("ft_psk").intValue(); - wifiVifConfigInfo.groupRekey = row.getIntegerColumn("group_rekey").intValue(); - wifiVifConfigInfo.minHwMode = row.getStringColumn("min_hw_mode"); - wifiVifConfigInfo.ifName = row.getStringColumn("if_name"); - wifiVifConfigInfo.mode = row.getStringColumn("mode"); - wifiVifConfigInfo.rrm = row.getIntegerColumn("rrm").intValue(); - wifiVifConfigInfo.ssid = row.getStringColumn("ssid"); - wifiVifConfigInfo.ssidBroadcast = row.getStringColumn("ssid_broadcast"); - wifiVifConfigInfo.uapsdEnable = row.getBooleanColumn("uapsd_enable"); - Long radioIdxTmp = getSingleValueFromSet(row, "vif_radio_idx"); - if (radioIdxTmp == null) { - radioIdxTmp = 0L; - } - wifiVifConfigInfo.vifRadioIdx = radioIdxTmp.intValue(); - wifiVifConfigInfo.security = row.getMapColumn("security"); - - if (row.getColumns().get("vlan_id") != null && row.getColumns().get("vlan_id").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiVifConfigInfo.vlanId = row.getIntegerColumn("vlan_id").intValue(); - } - ret.put(wifiVifConfigInfo.ifName + '_' + wifiVifConfigInfo.ssid, wifiVifConfigInfo); - } - - LOG.debug("Retrieved WifiVifConfigs: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedWifiVifConfigs", e); - throw new RuntimeException(e); - } - - return ret; - } - - public Map getProvisionedWifiInetConfigs(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("NAT"); - columns.add("_uuid"); - columns.add("broadcast"); - columns.add("enabled"); - columns.add("if_name"); - columns.add("if_type"); - columns.add("ip_assign_scheme"); - columns.add("network"); - columns.add("inet_addr"); - columns.add("mtu"); - columns.add("netmask"); - columns.add("vlan_id"); - - try { - LOG.debug("Retrieving WifiInetConfig:"); - - operations.add(new Select(wifiInetConfigDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - for (Row row : ((SelectResult) result[0]).getRows()) { - - WifiInetConfigInfo wifiInetConfigInfo = new WifiInetConfigInfo(); - Boolean natTmp = getSingleValueFromSet(row, "NAT"); - wifiInetConfigInfo.nat = natTmp != null ? natTmp : false; - - wifiInetConfigInfo.uuid = row.getUuidColumn("_uuid"); - if (row.getColumns().get("broadcast") != null && row.getColumns().get("broadcast").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiInetConfigInfo.broadcast = row.getStringColumn("broadcast"); - } - wifiInetConfigInfo.enabled = row.getBooleanColumn("enabled"); - wifiInetConfigInfo.ifName = row.getStringColumn("if_name"); - wifiInetConfigInfo.ifType = row.getStringColumn("if_type"); - wifiInetConfigInfo.ipAssignScheme = row.getStringColumn("ip_assign_scheme"); - wifiInetConfigInfo.network = row.getBooleanColumn("network"); - if (row.getColumns().get("inet_addr") != null && row.getColumns().get("inet_addr").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiInetConfigInfo.inetAddr = row.getStringColumn("inet_addr"); - } - if (row.getColumns().get("mtu") != null && row.getColumns().get("mtu").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiInetConfigInfo.mtu = row.getIntegerColumn("mtu").intValue(); - } - if (row.getColumns().get("netmask") != null && row.getColumns().get("netmask").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiInetConfigInfo.netmask = row.getStringColumn("netmask"); - } - if (row.getColumns().get("vlan_id") != null && row.getColumns().get("vlan_id").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - wifiInetConfigInfo.vlanId = row.getIntegerColumn("vlan_id").intValue(); - } - ret.put(wifiInetConfigInfo.ifName, wifiInetConfigInfo); - } - - LOG.debug("Retrieved WifiInetConfigs: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedWifiInetConfigs", e); - throw new RuntimeException(e); - } - - return ret; - } - - public Map getProvisionedWifiStatsConfigs(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); - - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("channel_list"); - columns.add("radio_type"); - columns.add("reporting_interval"); - columns.add("sampling_interval"); - columns.add("stats_type"); - columns.add("survey_interval_ms"); - columns.add("survey_type"); - columns.add("threshold"); - columns.add("_uuid"); - - try { - LOG.debug("Retrieving WifiStatsConfigs:"); - - operations.add(new Select(wifiStatsConfigDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - for (Row row : ((SelectResult) result[0]).getRows()) { - - WifiStatsConfigInfo wifiStatsConfigInfo = new WifiStatsConfigInfo(); - - wifiStatsConfigInfo.channelList = row.getSetColumn("channel_list"); - wifiStatsConfigInfo.radioType = row.getStringColumn("radio_type"); - wifiStatsConfigInfo.reportingInterval = row.getIntegerColumn("reporting_interval").intValue(); - wifiStatsConfigInfo.samplingInterval = row.getIntegerColumn("sampling_interval").intValue(); - wifiStatsConfigInfo.statsType = row.getStringColumn("stats_type"); - wifiStatsConfigInfo.surveyType = getSingleValueFromSet(row, "survey_type"); - Long tmp = getSingleValueFromSet(row, "survey_interval_ms"); - wifiStatsConfigInfo.surveyIntervalMs = tmp != null ? tmp.intValue() : 0; - wifiStatsConfigInfo.threshold = row.getMapColumn("threshold"); - wifiStatsConfigInfo.uuid = row.getUuidColumn("_uuid"); - - if (wifiStatsConfigInfo.surveyType == null) { - ret.put(wifiStatsConfigInfo.radioType + "_" + wifiStatsConfigInfo.statsType, wifiStatsConfigInfo); - } else { - ret.put(wifiStatsConfigInfo.radioType + "_" + wifiStatsConfigInfo.statsType + "_" - + wifiStatsConfigInfo.surveyType, wifiStatsConfigInfo); - - } - } - - LOG.debug("Retrieved WifiStatsConfigs: {}", ret); - - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedWifiStatsConfigs", e); - - throw new RuntimeException(e); - } - - return ret; - } - - public void provisionSingleBridgePortInterface(OvsdbClient ovsdbClient, String interfaceName, String bridgeName, - String interfaceType, Map interfaceOptions, - Map provisionedInterfaces, Map provisionedPorts, - Map provisionedBridges) - throws OvsdbClientException, TimeoutException, ExecutionException, InterruptedException { - - LOG.debug("InterfaceName {} BridgeName {} InterfaceType {}", interfaceName, bridgeName, interfaceType); - if (!provisionedInterfaces.containsKey(interfaceName)) { - // Create this interface and link it to the port and the bridge - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); - - updateColumns.put("name", new Atom<>(interfaceName)); - if (interfaceType != null) { - updateColumns.put("type", new Atom<>(interfaceType)); - } - // updateColumns.put("admin_state", new Atom("up") ); - // updateColumns.put("link_state", new Atom("up") ); - // updateColumns.put("ifindex", new Atom(ifIndex) ); - // updateColumns.put("mtu", new Atom(1500) ); - // updateColumns.put("ofport", new Atom(ofport) ); - - if (interfaceOptions != null) { - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map ifOptions = com.vmware.ovsdb.protocol.operation.notation.Map - .of(interfaceOptions); - updateColumns.put("options", ifOptions); - } - - Uuid interfaceUuid = null; - - Row row = new Row(updateColumns); - operations.add(new Insert(interfaceDbTable, row)); - - { - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned Interface for {}", interfaceName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - if (res instanceof InsertResult) { - interfaceUuid = ((InsertResult) res).getUuid(); - } - } - } - - if (interfaceUuid == null) { - throw new IllegalStateException("Interface entry was not created successfully"); - } - - Uuid portUuid = null; - operations = new ArrayList<>(); - // link the interface to the port, create port if necessary - if (!provisionedPorts.containsKey(interfaceName)) { - // need to create port - updateColumns = new HashMap<>(); - - // portUuid = new Uuid(new UUID(System.currentTimeMillis(), - // System.nanoTime())) ; - updateColumns.put("name", new Atom<>(interfaceName)); - // updateColumns.put("_uuid", new Atom(portUuid)); - - Set portInterfacesSet = new HashSet<>(); - portInterfacesSet.add(interfaceUuid); - com.vmware.ovsdb.protocol.operation.notation.Set portInterfaces = com.vmware.ovsdb.protocol.operation.notation.Set - .of(portInterfacesSet); - updateColumns.put("interfaces", portInterfaces); - - row = new Row(updateColumns); - operations.add(new Insert(portDbTable, row)); - - { - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned Port for {}", interfaceName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - if (res instanceof InsertResult) { - portUuid = ((InsertResult) res).getUuid(); - } - } - } - - } else { - // need to update port - PortInfo existingPort = provisionedPorts.get(interfaceName); - portUuid = existingPort.uuid; - - conditions = new ArrayList<>(); - updateColumns = new HashMap<>(); - - conditions.add(new Condition("name", Function.EQUALS, new Atom<>(interfaceName))); - - Set portInterfacesSet = new HashSet<>(); - if (existingPort.interfaceUuids != null) { - portInterfacesSet.addAll(existingPort.interfaceUuids); - } - portInterfacesSet.add(interfaceUuid); - com.vmware.ovsdb.protocol.operation.notation.Set portInterfaces = com.vmware.ovsdb.protocol.operation.notation.Set - .of(portInterfacesSet); - updateColumns.put("interfaces", portInterfaces); - - row = new Row(updateColumns); - operations.add(new Update(portDbTable, row)); - - { - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Updated Port for {}", interfaceName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - } + // link the port to the bridge + if (provisionedBridges.containsKey(bridgeName)) { + BridgeInfo existingBridge = provisionedBridges.get(bridgeName); - if (portUuid == null) { - throw new IllegalStateException("Port entry was not created successfully"); - } + conditions = new ArrayList<>(); + updateColumns = new HashMap<>(); - operations = new ArrayList<>(); + conditions.add(new Condition("name", Function.EQUALS, new Atom<>(bridgeName))); - // link the port to the bridge - if (provisionedBridges.containsKey(bridgeName)) { - BridgeInfo existingBridge = provisionedBridges.get(bridgeName); + Set bridgePortsSet = new HashSet<>(); + if (existingBridge.portUuids != null) { + bridgePortsSet.addAll(existingBridge.portUuids); + } - conditions = new ArrayList<>(); - updateColumns = new HashMap<>(); + bridgePortsSet.add(portUuid); + com.vmware.ovsdb.protocol.operation.notation.Set bridgePorts = com.vmware.ovsdb.protocol.operation.notation.Set + .of(bridgePortsSet); + updateColumns.put("ports", bridgePorts); - conditions.add(new Condition("name", Function.EQUALS, new Atom<>(bridgeName))); + row = new Row(updateColumns); + operations.add(new Update(bridgeDbTable, row)); - Set bridgePortsSet = new HashSet<>(); - if (existingBridge.portUuids != null) { - bridgePortsSet.addAll(existingBridge.portUuids); - } + } else { + LOG.warn("provisionedBridges does not have bridge {} - {} - port will be dangling", bridgeName, + provisionedBridges.keySet()); + } - bridgePortsSet.add(portUuid); - com.vmware.ovsdb.protocol.operation.notation.Set bridgePorts = com.vmware.ovsdb.protocol.operation.notation.Set - .of(bridgePortsSet); - updateColumns.put("ports", bridgePorts); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - row = new Row(updateColumns); - operations.add(new Update(bridgeDbTable, row)); + if (LOG.isDebugEnabled()) { + LOG.debug("Finished provisioning Interface/port/bridge for {} / {}", interfaceName, bridgeName); - } else { - LOG.warn("provisionedBridges does not have bridge {} - {} - port will be dangling", bridgeName, - provisionedBridges.keySet()); - } + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + } + } - if (LOG.isDebugEnabled()) { - LOG.debug("Finished provisioning Interface/port/bridge for {} / {}", interfaceName, bridgeName); + // public static final String homeAp24 = "home-ap-24"; + // public static final String homeApL50 = "home-ap-l50"; + // public static final String homeApU50 = "home-ap-u50"; - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } + public static final String brWan = "br-wan"; + public static final String brLan = "br-lan"; - } - } + public static final String patchW2h = "patch-w2h"; + public static final String patchH2w = "patch-h2w"; - // public static final String homeAp24 = "home-ap-24"; - // public static final String homeApL50 = "home-ap-l50"; - // public static final String homeApU50 = "home-ap-u50"; + public void provisionBridgePortInterface(OvsdbClient ovsdbClient) { + try { + Map provisionedInterfaces = getProvisionedInterfaces(ovsdbClient); + LOG.debug("Existing Interfaces: {}", provisionedInterfaces.keySet()); - public static final String brWan = "br-wan"; - public static final String brLan = "br-lan"; + Map provisionedPorts = getProvisionedPorts(ovsdbClient); + LOG.debug("Existing Ports: {}", provisionedPorts.keySet()); - public static final String patchW2h = "patch-w2h"; - public static final String patchH2w = "patch-h2w"; + Map provisionedBridges = getProvisionedBridges(ovsdbClient); + LOG.debug("Existing Bridges: {}", provisionedBridges.keySet()); - public void provisionBridgePortInterface(OvsdbClient ovsdbClient) { - try { - Map provisionedInterfaces = getProvisionedInterfaces(ovsdbClient); - LOG.debug("Existing Interfaces: {}", provisionedInterfaces.keySet()); + Map patchH2wOptions = new HashMap<>(); + patchH2wOptions.put("peer", "patch-w2h"); - Map provisionedPorts = getProvisionedPorts(ovsdbClient); - LOG.debug("Existing Ports: {}", provisionedPorts.keySet()); + Map patchW2hOptions = new HashMap<>(); + patchH2wOptions.put("peer", "patch-h2w"); - Map provisionedBridges = getProvisionedBridges(ovsdbClient); - LOG.debug("Existing Bridges: {}", provisionedBridges.keySet()); + provisionSingleBridgePortInterface(ovsdbClient, patchH2w, bridgeNameVifInterfaces, "patch", patchH2wOptions, + provisionedInterfaces, provisionedPorts, provisionedBridges); + provisionSingleBridgePortInterface(ovsdbClient, patchW2h, brWan, "patch", patchW2hOptions, + provisionedInterfaces, provisionedPorts, provisionedBridges); - Map patchH2wOptions = new HashMap<>(); - patchH2wOptions.put("peer", "patch-w2h"); + provisionSingleBridgePortInterface(ovsdbClient, ifName5GHzU, bridgeNameVifInterfaces, "vif", null, + provisionedInterfaces, provisionedPorts, provisionedBridges); + provisionSingleBridgePortInterface(ovsdbClient, ifName5GHzL, bridgeNameVifInterfaces, "vif", null, + provisionedInterfaces, provisionedPorts, provisionedBridges); + provisionSingleBridgePortInterface(ovsdbClient, ifName2pt4GHz, bridgeNameVifInterfaces, "vif", null, + provisionedInterfaces, provisionedPorts, provisionedBridges); - Map patchW2hOptions = new HashMap<>(); - patchH2wOptions.put("peer", "patch-h2w"); + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in provisionBridgePortInterface", e); + throw new RuntimeException(e); + } - provisionSingleBridgePortInterface(ovsdbClient, patchH2w, bridgeNameVifInterfaces, "patch", patchH2wOptions, - provisionedInterfaces, provisionedPorts, provisionedBridges); - provisionSingleBridgePortInterface(ovsdbClient, patchW2h, brWan, "patch", patchW2hOptions, - provisionedInterfaces, provisionedPorts, provisionedBridges); + } - provisionSingleBridgePortInterface(ovsdbClient, ifName5GHzU, bridgeNameVifInterfaces, "vif", null, - provisionedInterfaces, provisionedPorts, provisionedBridges); - provisionSingleBridgePortInterface(ovsdbClient, ifName5GHzL, bridgeNameVifInterfaces, "vif", null, - provisionedInterfaces, provisionedPorts, provisionedBridges); - provisionSingleBridgePortInterface(ovsdbClient, ifName2pt4GHz, bridgeNameVifInterfaces, "vif", null, - provisionedInterfaces, provisionedPorts, provisionedBridges); + public void removeOnboardingSsids(OvsdbClient ovsdbClient) { + try { + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + conditions.add(new Condition("ssid", Function.EQUALS, new Atom<>("opensync.onboard"))); - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in provisionBridgePortInterface", e); - throw new RuntimeException(e); - } + operations.add(new Delete(wifiVifConfigDbTable, conditions)); - } + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - public void removeOnboardingSsids(OvsdbClient ovsdbClient) { - try { - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - conditions.add(new Condition("ssid", Function.EQUALS, new Atom<>("opensync.onboard"))); + if (LOG.isDebugEnabled()) { + LOG.debug("Removed onboarding SSIDs from {}:", wifiVifConfigDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in removeOnboardingSsids", e); + throw new RuntimeException(e); + } + + } + + public void removeAllSsids(OvsdbClient ovsdbClient) { + try { + List operations = new ArrayList<>(); + + operations.add(new Delete(wifiVifConfigDbTable)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Removed all existing SSIDs from {}:", wifiVifConfigDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + // Now clean up references in the vif_configs columns + operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + Set vifConfigsSet = new HashSet<>(); + com.vmware.ovsdb.protocol.operation.notation.Set vifConfigs = com.vmware.ovsdb.protocol.operation.notation.Set + .of(vifConfigsSet); + updateColumns.put("vif_configs", vifConfigs); + + Row row = new Row(updateColumns); + operations.add(new Update(wifiRadioConfigDbTable, row)); + + fResult = ovsdbClient.transact(ovsdbName, operations); + result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Updated WifiRadioConfig "); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + LOG.info("Removed all ssids"); + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in removeAllSsids", e); + throw new RuntimeException(e); + } + + } + + public void configureWifiRadios(OvsdbClient ovsdbClient, OpensyncAPConfig opensyncAPConfig) { + + Map provisionedWifiRadios = getProvisionedWifiRadioConfigs(ovsdbClient); + LOG.debug("Existing WifiRadioConfigs: {}", provisionedWifiRadios.keySet()); + + String country = opensyncAPConfig.getCountryCode(); // should be the + // same for all + // radios on this AP + // ;-) + + ApElementConfiguration apElementConfiguration = (ApElementConfiguration) opensyncAPConfig.getCustomerEquipment() + .getDetails(); + + for (RadioType radioType : apElementConfiguration.getRadioMap().keySet()) { + Map hwConfig = new HashMap<>(); + + ElementRadioConfiguration elementRadioConfig = apElementConfiguration.getRadioMap().get(radioType); + int channel = elementRadioConfig.getChannelNumber(); + ChannelBandwidth bandwidth = elementRadioConfig.getChannelBandwidth(); + String ht_mode = null; + switch (bandwidth) { + case is20MHz: + ht_mode = "HT20"; + break; + case is40MHz: + ht_mode = "HT40"; + break; + case is80MHz: + ht_mode = "HT80"; + break; + case is160MHz: + ht_mode = "HT160"; + break; + case auto: + ht_mode = "0"; + break; + default: + ht_mode = null; + } + elementRadioConfig.getAutoChannelSelection(); + + RadioConfiguration radioConfig = apElementConfiguration.getAdvancedRadioMap().get(radioType); + int beaconInterval = radioConfig.getBeaconInterval(); + boolean enabled = radioConfig.getRadioAdminState().equals(StateSetting.enabled); + + int txPower = 0; + if (!elementRadioConfig.getEirpTxPower().isAuto()) { + txPower = elementRadioConfig.getEirpTxPower().getValue(); + } + String configName = null; + switch (radioType) { + case is2dot4GHz: + configName = radioName2pt4GHz; + break; + case is5GHz: + // 802.11h dfs (Dynamic Frequency Selection) aka military and + // weather radar + // avoidance protocol + // Must not be disabled (by law) + // NA for 2.4GHz + hwConfig.put("dfs_enable", "1"); + hwConfig.put("dfs_ignorecac", "0"); + hwConfig.put("dfs_usenol", "1"); + configName = radioName5GHzU; + break; + case is5GHzL: + // 802.11h dfs (Dynamic Frequency Selection) aka military and + // weather radar + // avoidance protocol + // Must not be disabled (by law) + // NA for 2.4GHz + hwConfig.put("dfs_enable", "1"); + hwConfig.put("dfs_ignorecac", "0"); + hwConfig.put("dfs_usenol", "1"); + configName = radioName5GHzL; + break; + case is5GHzU: + // 802.11h dfs (Dynamic Frequency Selection) aka military and + // weather radar + // avoidance protocol + // Must not be disabled (by law) + // NA for 2.4GHz + hwConfig.put("dfs_enable", "1"); + hwConfig.put("dfs_ignorecac", "0"); + hwConfig.put("dfs_usenol", "1"); + configName = radioName5GHzU; + break; + default: // don't know this interface + continue; + + } + + if (configName != null) { + try { + configureWifiRadios(ovsdbClient, configName, provisionedWifiRadios, channel, hwConfig, country, + beaconInterval, enabled, ht_mode, txPower); + } catch (OvsdbClientException e) { + LOG.error("ConfigureWifiRadios failed with OvsdbClient exception.", e); + } catch (TimeoutException e) { + LOG.error("ConfigureWifiRadios failed with Timeout.", e); + + } catch (ExecutionException e) { + LOG.error("ConfigureWifiRadios excecution failed.", e); + + } catch (InterruptedException e) { + LOG.error("ConfigureWifiRadios interrupted.", e); + } + + } + + } + + } + + public List getOpensyncAPRadioState(TableUpdates tableUpdates, String apId, + OvsdbClient ovsdbClient) { + + List ret = new ArrayList<>(); + + try { + + for (Entry tableUpdate : tableUpdates.getTableUpdates().entrySet()) { + + for (Entry rowUpdate : tableUpdate.getValue().getRowUpdates().entrySet()) { + + Row row = rowUpdate.getValue().getNew(); + // Row old = rowUpdate.getOld(); + + if (row != null) { + + OpensyncAPRadioState tableState = new OpensyncAPRadioState(); + + Map map = row.getColumns(); + + if (map.get("mac") != null && map.get("mac").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMac(row.getStringColumn("mac")); + } + if (map.get("channel") != null && map.get("channel").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setChannel(row.getIntegerColumn("channel").intValue()); + } + if (map.get("freq_band") != null && map.get("freq_band").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + String frequencyBand = row.getStringColumn("freq_band"); + switch (frequencyBand) { + case "2.4G": + tableState.setFreqBand(RadioType.is2dot4GHz); + break; + case "5G": + tableState.setFreqBand(RadioType.is5GHz); + break; + case "5GL": + tableState.setFreqBand(RadioType.is5GHzL); + break; + case "5GU": + tableState.setFreqBand(RadioType.is5GHzU); + break; + default: + tableState.setFreqBand(RadioType.UNSUPPORTED); + } + } + if (map.get("if_name") != null && map.get("if_name").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setIfName(row.getStringColumn("if_name")); + } + if (map.get("channel_mode") != null && map.get("channel_mode").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setChannelMode(row.getStringColumn("channel_mode")); + } + if (map.get("country") != null && map.get("country").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setCountry(row.getStringColumn("country")); + } + if (map.get("enabled") != null && map.get("enabled").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setEnabled(row.getBooleanColumn("enabled")); + } + if (map.get("ht_mode") != null && map.get("ht_mode").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setHtMode(row.getStringColumn("ht_mode")); + } + if (map.get("tx_power") != null && map.get("tx_power").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setTxPower(row.getIntegerColumn("tx_power").intValue()); + } + if (map.get("hw_config") != null && map.get("hw_config").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Map.class)) { + tableState.setHwConfig(row.getMapColumn("hw_config")); + } + if (map.get("_version") != null && map.get("_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_version")); + } + if (map.get("_uuid") != null && map.get("_uuid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_uuid")); + } + if (map.get("allowed_channels") != null) { + + Set allowedChannels = getSet(row, "allowed_channels"); + + Set allowed = new HashSet<>(); + for (Long channel : allowedChannels) { + allowed.add(channel.intValue()); + } + tableState.setAllowedChannels(allowed); + } + + ret.add(tableState); + } + } + } + + ret.stream().forEach(wrs -> { + LOG.debug("Wifi_Radio_State row {}", wrs); + }); + + } catch (Exception e) { + LOG.error("Could not parse update for Wifi_Radio_State", e); + } + + return ret; + } + + public List getOpensyncAPInetState(TableUpdates tableUpdates, String apId, + OvsdbClient ovsdbClient) { + List ret = new ArrayList<>(); + + try { + + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + + Row row = rowUpdate.getNew(); + // Row old = rowUpdate.getOld(); + + if (row != null) { + + OpensyncAPInetState tableState = new OpensyncAPInetState(); + Map map = row.getColumns(); + + if (map.get("NAT") != null && map.get("NAT").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setNat(row.getBooleanColumn("NAT")); + } + if (map.get("enabled") != null && map.get("enabled").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setEnabled(row.getBooleanColumn("enabled")); + } + if (map.get("if_name") != null && map.get("if_name").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setIfName(row.getStringColumn("if_name")); + } + if (map.get("if_type") != null && map.get("if_type").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setIfType(row.getStringColumn("if_type")); + } + if (map.get("ip_assign_scheme") != null && map.get("ip_assign_scheme").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setIpAssignScheme(row.getStringColumn("ip_assign_scheme")); + } + if (map.get("network") != null && map.get("network").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setNetwork(row.getBooleanColumn("network")); + } + if (map.get("hwaddr") != null && map.get("hwaddr").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setHwAddr(row.getStringColumn("hwaddr")); + } + if (map.get("_version") != null && map.get("_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_version")); + } + if (map.get("_uuid") != null && map.get("_uuid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_uuid")); + } + ret.add(tableState); + } + + } + } + + ret.stream().forEach(wrs -> { + LOG.debug("Wifi_Inet_State row {}", wrs); + }); + + } catch (Exception e) { + LOG.error("Could not parse update for Wifi_Inet_State", e); + } + return ret; + } + + public List getOpensyncAPVIFState(TableUpdates tableUpdates, String apId, + OvsdbClient ovsdbClient) { + List ret = new ArrayList<>(); + try { + + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + + Row row = rowUpdate.getNew(); + // Row old = rowUpdate.getOld(); + + if (row != null) { + + OpensyncAPVIFState tableState = new OpensyncAPVIFState(); + + Map map = row.getColumns(); + + if (map.get("mac") != null && map.get("mac").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMac(row.getStringColumn("mac")); + } + if (map.get("bridge") != null && map.get("bridge").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setBridge(row.getStringColumn("bridge")); + } + if (map.get("btm") != null && map.get("btm").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setBtm(row.getIntegerColumn("btm").intValue()); + } + + if (map.get("channel") != null && map.get("channel").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setChannel(row.getIntegerColumn("channel").intValue()); + } + + if (map.get("enabled") != null && map.get("enabled").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setEnabled(row.getBooleanColumn("enabled")); + } + + if (map.get("group_rekey") != null && map.get("group_rekey").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setGroupRekey(row.getIntegerColumn("group_rekey").intValue()); + } + if (map.get("if_name") != null && map.get("if_name").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setIfName(row.getStringColumn("if_name")); + } + + if (map.get("mode") != null && map.get("mode").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMode(row.getStringColumn("mode")); + } + + if (map.get("rrm") != null && map.get("rrm").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setRrm(row.getIntegerColumn("rrm").intValue()); + } + if (map.get("ssid") != null && map.get("ssid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setSsid(row.getStringColumn("ssid")); + } + + if (map.get("ssid_broadcast") != null && map.get("ssid_broadcast").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setSsidBroadcast(row.getStringColumn("ssid_broadcast")); + } + if (map.get("uapsd_enable") != null && map.get("uapsd_enable").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setUapsdEnable(row.getBooleanColumn("uapsd_enable")); + } + if (map.get("vif_radio_idx") != null && map.get("vif_radio_idx").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVifRadioIdx(row.getIntegerColumn("vif_radio_idx").intValue()); + } + + if (map.get("associated_clients") != null) { + tableState.setAssociatedClients(row.getSetColumn("associated_clients")); + } + + if (map.get("security") != null) { + tableState.setSecurity(row.getMapColumn("security")); + } + + if (map.get("_version") != null && map.get("_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_version")); + } + if (map.get("_uuid") != null && map.get("_uuid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_uuid")); + } + + ret.add(tableState); + + } + + } + } + + ret.stream().forEach(wrs -> { + LOG.debug("Wifi_VIF_State row {}", wrs); + }); + + } catch (Exception e) { + LOG.error("Could not parse update for Wifi_VIF_State", e); + + } + return ret; + } + + public List getOpensyncWifiAssociatedClients(TableUpdates tableUpdates, String apId, + OvsdbClient ovsdbClient) { + List ret = new ArrayList<>(); + + try { + + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + + Row row = rowUpdate.getNew(); + + if (row != null) { + + OpensyncWifiAssociatedClients tableState = new OpensyncWifiAssociatedClients(); + Map map = row.getColumns(); + + if (map.get("mac") != null && map.get("mac").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMac(row.getStringColumn("mac")); + } + if (row.getSetColumn("capabilities") != null) { + tableState.setCapabilities(row.getSetColumn("capabilities")); + } + if (map.get("state") != null && map.get("state").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setState(row.getStringColumn("state")); + } + if (map.get("_version") != null && map.get("_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_version")); + } + if (map.get("_uuid") != null && map.get("_uuid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_uuid")); + } + + ret.add(tableState); + + } + } + } + ret.stream().forEach(wrs -> { + LOG.debug("Wifi_Associated_Clients row {}", wrs); + }); + } catch (Exception e) { + LOG.error("Could not get Wifi_Associated_Clients list from table update", e); + } + + return ret; + } + + public OpensyncAWLANNode getOpensyncAWLANNode(TableUpdates tableUpdates, String apId, OvsdbClient ovsdbClient) { + OpensyncAWLANNode tableState = new OpensyncAWLANNode(); + + try { + + for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { + + for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { + + Row row = rowUpdate.getNew(); + + if (row != null) { + + Map map = row.getColumns(); + + if (map.get("mqtt_settings") != null) { + tableState.setMqttSettings(row.getMapColumn("mqtt_settings")); + } + if (map.get("mqtt_headers") != null) { + tableState.setMqttHeaders(row.getMapColumn("mqtt_headers")); + } + if (map.get("mqtt_topics") != null) { + tableState.setMqttHeaders(row.getMapColumn("mqtt_topics")); + } + + if (map.get("model") != null && map.get("model").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setModel(row.getStringColumn("model")); + } + if (map.get("sku_number") != null && map.get("sku_number").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setSkuNumber(row.getStringColumn("sku_number")); + } + if (map.get("id") != null && map.get("id").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setId(row.getStringColumn("id")); + } + + if (map.get("version_matrix") != null) { + tableState.setVersionMatrix(row.getMapColumn("version_matrix")); + } + if (map.get("firmware_version") != null && map.get("firmware_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setFirmwareVersion(row.getStringColumn("firmware_version")); + } + if (map.get("firmware_url") != null && map.get("firmware_url").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setFirmwareUrl(row.getStringColumn("firmware_url")); + } + + if (map.get("_uuid") != null && map.get("_uuid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_uuid")); + } + if (map.get("upgrade_dl_timer") != null && map.get("upgrade_dl_timer").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setUpgradeDlTimer(row.getIntegerColumn("upgrade_dl_timer").intValue()); + } + if (map.get("platform_version") != null && map.get("platform_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setPlatformVersion(row.getStringColumn("platform_version")); + } + if (map.get("firmware_pass") != null && map.get("firmware_pass").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setFirmwarePass(row.getStringColumn("firmware_pass")); + } + if (map.get("upgrade_timer") != null && map.get("upgrade_timer").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setUpgradeTimer(row.getIntegerColumn("upgrade_timer").intValue()); + } + if (map.get("max_backoff") != null && map.get("max_backoff").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMaxBackoff(row.getIntegerColumn("max_backoff").intValue()); + } + if (map.get("led_config") != null) { + tableState.setLedConfig(row.getMapColumn("led_config")); + } + if (map.get("redirector_addr") != null && map.get("redirector_addr").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setRedirectorAddr(row.getStringColumn("redirector_addr")); + } + if (map.get("serial_number") != null && map.get("serial_number").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setSerialNumber(row.getStringColumn("serial_number")); + } + if (map.get("_version") != null && map.get("_version").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setVersion(row.getUuidColumn("_version")); + } + if (map.get("upgrade_status") != null && map.get("upgrade_status").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setUpgradeTimer(row.getIntegerColumn("upgrade_status").intValue()); + } + if (map.get("device_mode") != null && map.get("device_mode").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setDeviceMode(row.getStringColumn("device_mode")); + } + if (map.get("min_backoff") != null && map.get("min_backoff").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setMinBackoff(row.getIntegerColumn("min_backoff").intValue()); + } + + if (map.get("revision") != null && map.get("revision").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setRevision(row.getStringColumn("revision")); + } + if (map.get("manager_addr") != null && map.get("manager_addr").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setManagerAddr(row.getStringColumn("manager_addr")); + } + if (map.get("factory_reset") != null && map.get("factory_reset").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + tableState.setFactoryReset(row.getBooleanColumn("factory_reset")); + } + } + + } + + } + } catch (Exception e) { + LOG.error("Failed to handle AWLAN_Node update", e); + } + + return tableState; + + } + + public void configureWifiRadios(OvsdbClient ovsdbClient, String configName, + Map provisionedWifiRadios, int channel, Map hwConfig, + String country, int beaconInterval, boolean enabled, String ht_mode, int txPower) + throws OvsdbClientException, TimeoutException, ExecutionException, InterruptedException { + + WifiRadioConfigInfo existingConfig = provisionedWifiRadios.get(configName); + + if (existingConfig == null) { + LOG.warn("There is no WifiRadioConfig {}", configName); + return; + } + + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); + conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(configName))); + + updateColumns.put("channel", new Atom<>(channel)); + updateColumns.put("country", new Atom<>(country)); + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map hwConfigMap = com.vmware.ovsdb.protocol.operation.notation.Map + .of(hwConfig); + updateColumns.put("hw_config", hwConfigMap); + updateColumns.put("bcn_int", new Atom<>(beaconInterval)); + updateColumns.put("enabled", new Atom<>(enabled)); + if (ht_mode != null && !ht_mode.equals("0")) { + updateColumns.put("ht_mode", new Atom<>(ht_mode)); + } else { + updateColumns.put("ht_mode", new com.vmware.ovsdb.protocol.operation.notation.Set()); + } + if (txPower > 0) { + updateColumns.put("tx_power", new Atom<>(txPower)); + } else { + updateColumns.put("tx_power", new com.vmware.ovsdb.protocol.operation.notation.Set()); + } + + Row row = new Row(updateColumns); + operations.add(new Update(wifiRadioConfigDbTable, conditions, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned channel {} for {}", channel, configName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + public void configureSingleSsid(OvsdbClient ovsdbClient, String bridge, String ifName, String ssid, + boolean ssidBroadcast, Map security, + Map provisionedWifiRadioConfigs, String radioIfName, int vlanId, + boolean rrmEnabled, boolean enable80211r, String minHwMode, boolean enabled, int keyRefresh, + boolean uapsdEnabled, boolean apBridge, NetworkForwardMode networkForwardMode, String gateway, String inet, + Map dns, String ipAssignScheme) { + + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + try { + updateColumns.put("bridge", new Atom<>(bridge)); + updateColumns.put("btm", new Atom<>(1)); + updateColumns.put("enabled", new Atom<>(enabled)); + if (enable80211r) { + updateColumns.put("ft_psk", new Atom<>(1)); + updateColumns.put("ft_mobility_domain", new Atom<>(17911)); + } else { + updateColumns.put("ft_psk", new Atom<>(0)); + updateColumns.put("ft_mobility_domain", new com.vmware.ovsdb.protocol.operation.notation.Set()); + } + updateColumns.put("if_name", new Atom<>(ifName)); + updateColumns.put("mode", new Atom<>("ap")); + updateColumns.put("rrm", new Atom<>(rrmEnabled ? 1 : 0)); + updateColumns.put("ssid", new Atom<>(ssid)); + updateColumns.put("ssid_broadcast", new Atom<>(ssidBroadcast ? "enabled" : "disabled")); + updateColumns.put("uapsd_enable", new Atom<>(true)); + // updateColumns.put("vif_radio_idx", new + // Atom(vifRadioIdx)); + updateColumns.put("min_hw_mode", new Atom<>(minHwMode)); + updateColumns.put("vlan_id", new Atom<>(vlanId)); + updateColumns.put("group_rekey", new Atom<>(keyRefresh)); + updateColumns.put("uapsd_enable", new Atom<>(uapsdEnabled)); + updateColumns.put("ap_bridge", new Atom<>(apBridge)); + + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map securityMap = com.vmware.ovsdb.protocol.operation.notation.Map + .of(security); + updateColumns.put("security", securityMap); + + Row row = new Row(updateColumns); + operations.add(new Insert(wifiVifConfigDbTable, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned SSID {} on {}", ssid, ifName); + + Uuid vifConfigUuid = null; + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + if (res instanceof InsertResult) { + vifConfigUuid = ((InsertResult) res).getUuid(); + } + } + + if (vifConfigUuid == null) { + throw new IllegalStateException("Wifi_VIF_Config entry was not created successfully"); + } + + // update Wifi_Radio_Config here - add vifConfigUuid + /// usr/plume/tools/ovsh u Wifi_Radio_Config + // vif_configs:='["set",[["uuid","98e42897-b567-4186-84a6-4a4e38a51e9d"],["uuid","4314920e-c4e6-42a6-93e3-261142ed9adf"]]]' + // --where if_name==wifi0 + updateColumns.clear(); + operations.clear(); + + WifiRadioConfigInfo wifiRadioConfigInfo = provisionedWifiRadioConfigs.get(radioIfName); + if (wifiRadioConfigInfo == null) { + throw new IllegalStateException("missing Wifi_Radio_Config entry " + radioIfName); + } + + Set vifConfigsSet = new HashSet<>(wifiRadioConfigInfo.vifConfigUuids); + vifConfigsSet.add(vifConfigUuid); + com.vmware.ovsdb.protocol.operation.notation.Set vifConfigs = com.vmware.ovsdb.protocol.operation.notation.Set + .of(vifConfigsSet); + updateColumns.put("vif_configs", vifConfigs); + + List conditions = new ArrayList<>(); + conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(radioIfName))); + + row = new Row(updateColumns); + operations.add(new Update(wifiRadioConfigDbTable, conditions, row)); + + fResult = ovsdbClient.transact(ovsdbName, operations); + result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Updated WifiRadioConfig {} for SSID {}:", radioIfName, ssid); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + Map inetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); + if (inetConfigs.containsKey(ifName)) { + updateWifiInetConfig(ovsdbClient, vlanId, ifName, enabled, networkForwardMode == NetworkForwardMode.NAT, + "vif", gateway, inet, dns, ipAssignScheme, vifConfigUuid); + } else { + LOG.debug("No corresponding WifiInetConfig for this Interface"); + insertWifiInetConfigForVif(ovsdbClient, vlanId, ifName, enabled, + networkForwardMode == NetworkForwardMode.NAT, "vif", gateway, inet, dns, ipAssignScheme, + vifConfigUuid); + } + + LOG.info("Provisioned SSID {} on interface {} / {}", ssid, ifName, radioIfName); + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureSingleSsid", e); + throw new RuntimeException(e); + } + } + + public void configureSsids(OvsdbClient ovsdbClient, OpensyncAPConfig opensyncApConfig) { + + boolean rrmEnabled = false; + if (opensyncApConfig.getEquipmentLocation() != null + && opensyncApConfig.getEquipmentLocation().getDetails() != null) { + rrmEnabled = opensyncApConfig.getEquipmentLocation().getDetails().isRrmEnabled(); + } + + for (Profile ssidProfile : opensyncApConfig.getSsidProfile()) { + + Map provisionedWifiVifConfigs = getProvisionedWifiVifConfigs(ovsdbClient); + LOG.debug("Existing WifiVifConfigs: {}", provisionedWifiVifConfigs.keySet()); + + SsidConfiguration ssidConfig = (SsidConfiguration) ssidProfile.getDetails(); + ApElementConfiguration apElementConfig = (ApElementConfiguration) opensyncApConfig.getCustomerEquipment() + .getDetails(); + for (RadioType radioType : ssidConfig.getAppliedRadios()) { + + int keyRefresh = ssidConfig.getKeyRefresh(); + + Map provisionedWifiRadioConfigs = getProvisionedWifiRadioConfigs( + ovsdbClient); + + boolean ssidBroadcast = ssidConfig.getBroadcastSsid() == StateSetting.enabled; + Map security = new HashMap<>(); + String ssidSecurityMode = ssidConfig.getSecureMode().name(); + String opensyncSecurityMode = "OPEN"; + + String ipAssignScheme = "none"; + // the following 5 attributes only applicable to static config, + // else they are + // ignored + String gateway = null; + String inet = null; + Map dns = null; + if (apElementConfig.getStaticIP() != null) { + ipAssignScheme = "static"; + inet = apElementConfig.getStaticIP().getHostAddress(); + gateway = apElementConfig.getStaticIpGw().getHostAddress(); + dns = new HashMap<>(); + dns.put(apElementConfig.getStaticDnsIp1().getHostName(), + apElementConfig.getStaticDnsIp1().getHostAddress()); + dns.put(apElementConfig.getStaticDnsIp2().getHostName(), + apElementConfig.getStaticDnsIp2().getHostAddress()); + } else if (apElementConfig.getGettingIP().equals(GettingIP.dhcp) + || apElementConfig.getGettingDNS().equals(GettingDNS.dhcp)) { + ipAssignScheme = "dhcp"; + } + + RadioConfiguration radioConfiguration = apElementConfig.getAdvancedRadioMap().get(radioType); + if (radioConfiguration == null) { + continue; // don't have a radio of this kind in the map + } + RadioMode radioMode = radioConfiguration.getRadioMode(); + + boolean uapsdEnabled = radioConfiguration.getUapsdState() == StateSetting.enabled; + + boolean apBridge = radioConfiguration.getStationIsolation() == StateSetting.enabled; // stationIsolation + boolean enable80211r = false; + + if (ssidConfig.getRadioBasedConfigs() != null) { + if (ssidConfig.getRadioBasedConfigs().containsKey(radioType) + && ssidConfig.getRadioBasedConfigs().get(radioType) != null) { + if (ssidConfig.getRadioBasedConfigs().get(radioType).getEnable80211r() != null) { + enable80211r = ssidConfig.getRadioBasedConfigs().get(radioType).getEnable80211r(); + } + } + } + + String minHwMode = "11n"; // min_hw_mode is 11ac, wifi 5, we can + // also take ++ (11ax) but 2.4GHz only + // Wifi4 -- + if (!radioType.equals(RadioType.is2dot4GHz)) { + minHwMode = "11ac"; + } + if (!radioType.equals(RadioType.is2dot4GHz) && radioMode.equals(RadioMode.modeX)) { + minHwMode = "11x"; + } + + if (ssidSecurityMode.equals("wpaPSK") || ssidSecurityMode.equals("wpa2PSK") + || ssidSecurityMode.equals("wpa2OnlyPSK")) { + opensyncSecurityMode = "WPA-PSK"; + } else if (ssidSecurityMode.equals("wep")) { + opensyncSecurityMode = "WEP"; + } else if (ssidSecurityMode.equals("wpaEAP") || ssidSecurityMode.equals("wpa2EAP") + || ssidSecurityMode.equals("wpa2OnlyEAP")) { + opensyncSecurityMode = "WPA-EAP"; + + } + + security.put("encryption", opensyncSecurityMode); + // key and mode is N/A for OPEN security + if (!opensyncSecurityMode.equals("OPEN")) { + if (ssidSecurityMode.equals("wpa2PSK")) { + security.put("key", ssidConfig.getKeyStr()); + security.put("mode", "mixed"); + } else if (ssidSecurityMode.equals("wpa2OnlyPSK")) { + security.put("key", ssidConfig.getKeyStr()); + security.put("mode", "2"); + } else if (ssidSecurityMode.equals("wpaPSK")) { + security.put("key", ssidConfig.getKeyStr()); + security.put("mode", "1"); + } else if (ssidSecurityMode.equals("wpa2OnlyEAP")) { + security.put("mode", "2"); + getRadiusConfiguration(opensyncApConfig, ssidConfig, security); + } else if (ssidSecurityMode.equals("wpa2EAP")) { + security.put("mode", "mixed"); + getRadiusConfiguration(opensyncApConfig, ssidConfig, security); + } else if (ssidSecurityMode.equals("wpaEAP")) { + security.put("mode", "1"); + getRadiusConfiguration(opensyncApConfig, ssidConfig, security); + } else if (ssidSecurityMode.equals("wep")) { + security.put("key", ssidConfig.getKeyStr()); + security.put("mode", "1"); + } + } + + boolean enabled = ssidConfig.getSsidAdminState().equals(StateSetting.enabled); + + String ifName = null; + String radioIfName = null; + + if (radioType == RadioType.is2dot4GHz) { + ifName = ifName2pt4GHz; + radioIfName = radioName2pt4GHz; + } else if (radioType == RadioType.is5GHzL) { + ifName = ifName5GHzL; + radioIfName = radioName5GHzL; + } else if (radioType == RadioType.is5GHzU) { + ifName = ifName5GHzU; + radioIfName = radioName5GHzU; + } + + if (!provisionedWifiVifConfigs.containsKey(ifName + "_" + ssidConfig.getSsid())) { + try { + configureSingleSsid(ovsdbClient, bridgeNameVifInterfaces, ifName, ssidConfig.getSsid(), + ssidBroadcast, security, provisionedWifiRadioConfigs, radioIfName, + ssidConfig.getVlanId(), rrmEnabled, enable80211r, minHwMode, enabled, keyRefresh, + uapsdEnabled, apBridge, ssidConfig.getForwardMode(), gateway, inet, dns, + ipAssignScheme); + + } catch (IllegalStateException e) { + // could not provision this SSID, but still can go on + LOG.warn("could not provision SSID {} on {}", ssidConfig.getSsid(), radioIfName); + } + } + + } + } + + } + + private void getRadiusConfiguration(OpensyncAPConfig opensyncApConfig, SsidConfiguration ssidConfig, + Map security) { + List radiusServiceList = new ArrayList<>(); + radiusServiceList = opensyncApConfig.getRadiusProfiles().stream() + .filter(p -> p.getName().equals((ssidConfig.getRadiusServiceName()))).collect(Collectors.toList()); + if (!radiusServiceList.isEmpty()) { + Profile profileRadius = radiusServiceList.get(0); + String region = opensyncApConfig.getEquipmentLocation().getName(); + List radiusServerList = new ArrayList<>(); + RadiusProfile radiusProfileDetails = ((RadiusProfile) profileRadius.getDetails()); + RadiusServiceRegion radiusServiceRegion = radiusProfileDetails.findServiceRegion(region); + radiusServerList = radiusServiceRegion.findServerConfiguration(ssidConfig.getRadiusServiceName()); + if (!radiusServerList.isEmpty()) { + RadiusServer rServer = radiusServerList.get(0); + security.put("radius_server_ip", rServer.getIpAddress().getHostAddress()); + security.put("radius_server_port", String.valueOf(rServer.getAuthPort())); + security.put("radius_server_secret", rServer.getSecret()); + } + } + } + + private void updateWifiInetConfig(OvsdbClient ovsdbClient, int vlanId, String ifName, boolean enabled, + boolean isNAT, String ifType, String gateway, String inet, Map dns, String ipAssignScheme, + Uuid vifConfigUuid) { + + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); + conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); + + try { + /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true + /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none + /// network:=true + // dhcpd + updateColumns.put("if_name", new Atom<>(ifName)); + updateColumns.put("if_type", new Atom<>(ifType)); + updateColumns.put("if_uuid", new Atom<>(vifConfigUuid.toString())); + updateColumns.put("enabled", new Atom<>(enabled)); + updateColumns.put("NAT", new Atom<>(isNAT)); + + // mtu // specified in interface, should take that value when + // implemented + updateColumns.put("mtu", new Atom<>(1500)); + updateColumns.put("network", new Atom<>(true)); + + updateColumns.put("ip_assign_scheme", new Atom<>(ipAssignScheme)); + + if (ipAssignScheme.equals("static")) { + updateColumns.put("dns", com.vmware.ovsdb.protocol.operation.notation.Map.of(dns)); + updateColumns.put("inet_addr", new Atom<>(inet)); + updateColumns.put("gateway", new Atom<>(gateway)); + // netmask + // broadcast + } + if (ipAssignScheme.equals("dhcp")) { + updateColumns.put("dhcp_sniff", new Atom<>(true)); + } else { + updateColumns.put("dhcp_sniff", new Atom<>(false)); + } + + if (ifType.equals("vlan")) { + updateColumns.put("vlan_id", new Atom<>(vlanId)); + } else { + updateColumns.put("vlan_id", new com.vmware.ovsdb.protocol.operation.notation.Set()); + } + + Row row = new Row(updateColumns); + operations.add(new Update(wifiInetConfigDbTable, conditions, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned WifiInetConfig {}", ifName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureWifiInet", e); + throw new RuntimeException(e); + } + + } + + private void insertWifiInetConfigForVif(OvsdbClient ovsdbClient, int vlanId, String ifName, boolean enabled, + boolean isNAT, String ifType, String gateway, String inet, Map dns, String ipAssignScheme, + Uuid vifConfigUuid) { + + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + try { + /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true + /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none + /// network:=true + // dhcpd + updateColumns.put("if_name", new Atom<>(ifName)); + updateColumns.put("if_type", new Atom<>(ifType)); + updateColumns.put("if_uuid", new Atom<>(vifConfigUuid.toString())); + updateColumns.put("enabled", new Atom<>(enabled)); + updateColumns.put("NAT", new Atom<>(isNAT)); + + // mtu // specified in interface, should take that value when + // implemented + updateColumns.put("mtu", new Atom<>(1500)); + updateColumns.put("network", new Atom<>(true)); + + updateColumns.put("ip_assign_scheme", new Atom<>(ipAssignScheme)); + + if (ipAssignScheme.equals("static")) { + updateColumns.put("dns", com.vmware.ovsdb.protocol.operation.notation.Map.of(dns)); + updateColumns.put("inet_addr", new Atom<>(inet)); + updateColumns.put("gateway", new Atom<>(gateway)); + // netmask + // broadcast + } + if (ipAssignScheme.equals("dhcp")) { + updateColumns.put("dhcp_sniff", new Atom<>(true)); + } else { + updateColumns.put("dhcp_sniff", new Atom<>(false)); + } + + if (ifType.equals("vlan")) { + updateColumns.put("vlan_id", new Atom<>(vlanId)); + } else { + updateColumns.put("vlan_id", new com.vmware.ovsdb.protocol.operation.notation.Set()); + } + + Row row = new Row(updateColumns); + operations.add(new Insert(wifiInetConfigDbTable, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + LOG.debug("Provisioned WifiInetConfig {}", ifName); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureWifiInet", e); + throw new RuntimeException(e); + } + + } + + public void configureWifiInet(OvsdbClient ovsdbClient, Map provisionedWifiInetConfigs, + String ifName) { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + try { + /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true + /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none + /// network:=true + + updateColumns.put("NAT", new Atom<>(false)); + updateColumns.put("enabled", new Atom<>(true)); + updateColumns.put("if_name", new Atom<>(ifName)); + updateColumns.put("if_type", new Atom<>("vif")); + updateColumns.put("ip_assign_scheme", new Atom<>("none")); + updateColumns.put("network", new Atom<>(true)); - operations.add(new Delete(wifiVifConfigDbTable, conditions)); + Row row = new Row(updateColumns); + operations.add(new Insert(wifiInetConfigDbTable, row)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - if (LOG.isDebugEnabled()) { - LOG.debug("Removed onboarding SSIDs from {}:", wifiVifConfigDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in removeOnboardingSsids", e); - throw new RuntimeException(e); - } - - } - - public void removeAllSsids(OvsdbClient ovsdbClient) { - try { - List operations = new ArrayList<>(); - - operations.add(new Delete(wifiVifConfigDbTable)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Removed all existing SSIDs from {}:", wifiVifConfigDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - // Now clean up references in the vif_configs columns - operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - Set vifConfigsSet = new HashSet<>(); - com.vmware.ovsdb.protocol.operation.notation.Set vifConfigs = com.vmware.ovsdb.protocol.operation.notation.Set - .of(vifConfigsSet); - updateColumns.put("vif_configs", vifConfigs); - - Row row = new Row(updateColumns); - operations.add(new Update(wifiRadioConfigDbTable, row)); - - fResult = ovsdbClient.transact(ovsdbName, operations); - result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Updated WifiRadioConfig "); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - LOG.info("Removed all ssids"); - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in removeAllSsids", e); - throw new RuntimeException(e); - } - - } - - public void configureWifiRadios(OvsdbClient ovsdbClient, OpensyncAPConfig opensyncAPConfig) { - - Map provisionedWifiRadios = getProvisionedWifiRadioConfigs(ovsdbClient); - LOG.debug("Existing WifiRadioConfigs: {}", provisionedWifiRadios.keySet()); - - String country = opensyncAPConfig.getCountryCode(); // should be the - // same for all - // radios on this AP - // ;-) - - ApElementConfiguration apElementConfiguration = (ApElementConfiguration) opensyncAPConfig.getCustomerEquipment() - .getDetails(); - - for (RadioType radioType : apElementConfiguration.getRadioMap().keySet()) { - Map hwConfig = new HashMap<>(); - - ElementRadioConfiguration elementRadioConfig = apElementConfiguration.getRadioMap().get(radioType); - int channel = elementRadioConfig.getChannelNumber(); - ChannelBandwidth bandwidth = elementRadioConfig.getChannelBandwidth(); - String ht_mode = null; - switch (bandwidth) { - case is20MHz: - ht_mode = "HT20"; - break; - case is40MHz: - ht_mode = "HT40"; - break; - case is80MHz: - ht_mode = "HT80"; - break; - case is160MHz: - ht_mode = "HT160"; - break; - case auto: - ht_mode = "0"; - break; - default: - ht_mode = null; - } - elementRadioConfig.getAutoChannelSelection(); - - RadioConfiguration radioConfig = apElementConfiguration.getAdvancedRadioMap().get(radioType); - int beaconInterval = radioConfig.getBeaconInterval(); - boolean enabled = radioConfig.getRadioAdminState().equals(StateSetting.enabled); - - int txPower = 0; - if (!elementRadioConfig.getEirpTxPower().isAuto()) { - txPower = elementRadioConfig.getEirpTxPower().getValue(); - } - String configName = null; - switch (radioType) { - case is2dot4GHz: - configName = radioName2pt4GHz; - break; - case is5GHz: - // 802.11h dfs (Dynamic Frequency Selection) aka military and - // weather radar - // avoidance protocol - // Must not be disabled (by law) - // NA for 2.4GHz - hwConfig.put("dfs_enable", "1"); - hwConfig.put("dfs_ignorecac", "0"); - hwConfig.put("dfs_usenol", "1"); - configName = radioName5GHzU; - break; - case is5GHzL: - // 802.11h dfs (Dynamic Frequency Selection) aka military and - // weather radar - // avoidance protocol - // Must not be disabled (by law) - // NA for 2.4GHz - hwConfig.put("dfs_enable", "1"); - hwConfig.put("dfs_ignorecac", "0"); - hwConfig.put("dfs_usenol", "1"); - configName = radioName5GHzL; - break; - case is5GHzU: - // 802.11h dfs (Dynamic Frequency Selection) aka military and - // weather radar - // avoidance protocol - // Must not be disabled (by law) - // NA for 2.4GHz - hwConfig.put("dfs_enable", "1"); - hwConfig.put("dfs_ignorecac", "0"); - hwConfig.put("dfs_usenol", "1"); - configName = radioName5GHzU; - break; - default: // don't know this interface - continue; - - } - - if (configName != null) { - try { - configureWifiRadios(ovsdbClient, configName, provisionedWifiRadios, channel, hwConfig, country, - beaconInterval, enabled, ht_mode, txPower); - } catch (OvsdbClientException e) { - LOG.error("ConfigureWifiRadios failed with OvsdbClient exception.", e); - } catch (TimeoutException e) { - LOG.error("ConfigureWifiRadios failed with Timeout.", e); - - } catch (ExecutionException e) { - LOG.error("ConfigureWifiRadios excecution failed.", e); - - } catch (InterruptedException e) { - LOG.error("ConfigureWifiRadios interrupted.", e); - } - - } - - } - - } - - public List getOpensyncAPRadioState(TableUpdates tableUpdates, String apId, - OvsdbClient ovsdbClient) { - - List ret = new ArrayList<>(); - - try { - - for (Entry tableUpdate : tableUpdates.getTableUpdates().entrySet()) { - - for (Entry rowUpdate : tableUpdate.getValue().getRowUpdates().entrySet()) { - - Row row = rowUpdate.getValue().getNew(); - // Row old = rowUpdate.getOld(); - - if (row != null) { - - OpensyncAPRadioState tableState = new OpensyncAPRadioState(); - - Map map = row.getColumns(); - - if (map.get("mac") != null && map.get("mac").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMac(row.getStringColumn("mac")); - } - if (map.get("channel") != null && map.get("channel").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setChannel(row.getIntegerColumn("channel").intValue()); - } - if (map.get("freq_band") != null && map.get("freq_band").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - String frequencyBand = row.getStringColumn("freq_band"); - switch (frequencyBand) { - case "2.4G": - tableState.setFreqBand(RadioType.is2dot4GHz); - break; - case "5G": - tableState.setFreqBand(RadioType.is5GHz); - break; - case "5GL": - tableState.setFreqBand(RadioType.is5GHzL); - break; - case "5GU": - tableState.setFreqBand(RadioType.is5GHzU); - break; - default: - tableState.setFreqBand(RadioType.UNSUPPORTED); - } - } - if (map.get("if_name") != null && map.get("if_name").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setIfName(row.getStringColumn("if_name")); - } - if (map.get("channel_mode") != null && map.get("channel_mode").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setChannelMode(row.getStringColumn("channel_mode")); - } - if (map.get("country") != null && map.get("country").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setCountry(row.getStringColumn("country")); - } - if (map.get("enabled") != null && map.get("enabled").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setEnabled(row.getBooleanColumn("enabled")); - } - if (map.get("ht_mode") != null && map.get("ht_mode").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setHtMode(row.getStringColumn("ht_mode")); - } - if (map.get("tx_power") != null && map.get("tx_power").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setTxPower(row.getIntegerColumn("tx_power").intValue()); - } - if (map.get("hw_config") != null && map.get("hw_config").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Map.class)) { - tableState.setHwConfig(row.getMapColumn("hw_config")); - } - if (map.get("_version") != null && map.get("_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_version")); - } - if (map.get("_uuid") != null && map.get("_uuid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_uuid")); - } - if (map.get("allowed_channels") != null) { - - Set allowedChannels = getSet(row, "allowed_channels"); - - Set allowed = new HashSet<>(); - for (Long channel : allowedChannels) { - allowed.add(channel.intValue()); - } - tableState.setAllowedChannels(allowed); - } - - ret.add(tableState); - } - } - } - - ret.stream().forEach(wrs -> { - LOG.debug("Wifi_Radio_State row {}", wrs); - }); - - } catch (Exception e) { - LOG.error("Could not parse update for Wifi_Radio_State", e); - } - - return ret; - } - - public List getOpensyncAPInetState(TableUpdates tableUpdates, String apId, - OvsdbClient ovsdbClient) { - List ret = new ArrayList<>(); - - try { - - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - - Row row = rowUpdate.getNew(); - // Row old = rowUpdate.getOld(); - - if (row != null) { - - OpensyncAPInetState tableState = new OpensyncAPInetState(); - Map map = row.getColumns(); - - if (map.get("NAT") != null && map.get("NAT").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setNat(row.getBooleanColumn("NAT")); - } - if (map.get("enabled") != null && map.get("enabled").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setEnabled(row.getBooleanColumn("enabled")); - } - if (map.get("if_name") != null && map.get("if_name").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setIfName(row.getStringColumn("if_name")); - } - if (map.get("if_type") != null && map.get("if_type").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setIfType(row.getStringColumn("if_type")); - } - if (map.get("ip_assign_scheme") != null && map.get("ip_assign_scheme").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setIpAssignScheme(row.getStringColumn("ip_assign_scheme")); - } - if (map.get("network") != null && map.get("network").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setNetwork(row.getBooleanColumn("network")); - } - if (map.get("hwaddr") != null && map.get("hwaddr").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setHwAddr(row.getStringColumn("hwaddr")); - } - if (map.get("_version") != null && map.get("_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_version")); - } - if (map.get("_uuid") != null && map.get("_uuid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_uuid")); - } - ret.add(tableState); - } - - } - } - - ret.stream().forEach(wrs -> { - LOG.debug("Wifi_Inet_State row {}", wrs); - }); - - } catch (Exception e) { - LOG.error("Could not parse update for Wifi_Inet_State", e); - } - return ret; - } - - public List getOpensyncAPVIFState(TableUpdates tableUpdates, String apId, - OvsdbClient ovsdbClient) { - List ret = new ArrayList<>(); - try { - - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - - Row row = rowUpdate.getNew(); - // Row old = rowUpdate.getOld(); - - if (row != null) { - - OpensyncAPVIFState tableState = new OpensyncAPVIFState(); - - Map map = row.getColumns(); - - if (map.get("mac") != null && map.get("mac").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMac(row.getStringColumn("mac")); - } - if (map.get("bridge") != null && map.get("bridge").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setBridge(row.getStringColumn("bridge")); - } - if (map.get("btm") != null && map.get("btm").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setBtm(row.getIntegerColumn("btm").intValue()); - } - - if (map.get("channel") != null && map.get("channel").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setChannel(row.getIntegerColumn("channel").intValue()); - } - - if (map.get("enabled") != null && map.get("enabled").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setEnabled(row.getBooleanColumn("enabled")); - } - - if (map.get("group_rekey") != null && map.get("group_rekey").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setGroupRekey(row.getIntegerColumn("group_rekey").intValue()); - } - if (map.get("if_name") != null && map.get("if_name").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setIfName(row.getStringColumn("if_name")); - } - - if (map.get("mode") != null && map.get("mode").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMode(row.getStringColumn("mode")); - } - - if (map.get("rrm") != null && map.get("rrm").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setRrm(row.getIntegerColumn("rrm").intValue()); - } - if (map.get("ssid") != null && map.get("ssid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setSsid(row.getStringColumn("ssid")); - } - - if (map.get("ssid_broadcast") != null && map.get("ssid_broadcast").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setSsidBroadcast(row.getStringColumn("ssid_broadcast")); - } - if (map.get("uapsd_enable") != null && map.get("uapsd_enable").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setUapsdEnable(row.getBooleanColumn("uapsd_enable")); - } - if (map.get("vif_radio_idx") != null && map.get("vif_radio_idx").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVifRadioIdx(row.getIntegerColumn("vif_radio_idx").intValue()); - } - - if (map.get("associated_clients") != null) { - tableState.setAssociatedClients(row.getSetColumn("associated_clients")); - } - - if (map.get("security") != null) { - tableState.setSecurity(row.getMapColumn("security")); - } - - if (map.get("_version") != null && map.get("_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_version")); - } - if (map.get("_uuid") != null && map.get("_uuid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_uuid")); - } - - ret.add(tableState); - - } - - } - } - - ret.stream().forEach(wrs -> { - LOG.debug("Wifi_VIF_State row {}", wrs); - }); - - } catch (Exception e) { - LOG.error("Could not parse update for Wifi_VIF_State", e); - - } - return ret; - } - - public List getOpensyncWifiAssociatedClients(TableUpdates tableUpdates, String apId, - OvsdbClient ovsdbClient) { - List ret = new ArrayList<>(); - - try { - - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - - Row row = rowUpdate.getNew(); - - if (row != null) { - - OpensyncWifiAssociatedClients tableState = new OpensyncWifiAssociatedClients(); - Map map = row.getColumns(); - - if (map.get("mac") != null && map.get("mac").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMac(row.getStringColumn("mac")); - } - if (row.getSetColumn("capabilities") != null) { - tableState.setCapabilities(row.getSetColumn("capabilities")); - } - if (map.get("state") != null && map.get("state").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setState(row.getStringColumn("state")); - } - if (map.get("_version") != null && map.get("_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_version")); - } - if (map.get("_uuid") != null && map.get("_uuid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_uuid")); - } - - ret.add(tableState); - - } - } - } - ret.stream().forEach(wrs -> { - LOG.debug("Wifi_Associated_Clients row {}", wrs); - }); - } catch (Exception e) { - LOG.error("Could not get Wifi_Associated_Clients list from table update", e); - } - - return ret; - } - - public OpensyncAWLANNode getOpensyncAWLANNode(TableUpdates tableUpdates, String apId, OvsdbClient ovsdbClient) { - OpensyncAWLANNode tableState = new OpensyncAWLANNode(); - - try { - - for (TableUpdate tableUpdate : tableUpdates.getTableUpdates().values()) { - - for (RowUpdate rowUpdate : tableUpdate.getRowUpdates().values()) { - - Row row = rowUpdate.getNew(); - - if (row != null) { - - Map map = row.getColumns(); - - if (map.get("mqtt_settings") != null) { - tableState.setMqttSettings(row.getMapColumn("mqtt_settings")); - } - if (map.get("mqtt_headers") != null) { - tableState.setMqttHeaders(row.getMapColumn("mqtt_headers")); - } - if (map.get("mqtt_topics") != null) { - tableState.setMqttHeaders(row.getMapColumn("mqtt_topics")); - } - - if (map.get("model") != null && map.get("model").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setModel(row.getStringColumn("model")); - } - if (map.get("sku_number") != null && map.get("sku_number").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setSkuNumber(row.getStringColumn("sku_number")); - } - if (map.get("id") != null && map.get("id").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setId(row.getStringColumn("id")); - } - - if (map.get("version_matrix") != null) { - tableState.setVersionMatrix(row.getMapColumn("version_matrix")); - } - if (map.get("firmware_version") != null && map.get("firmware_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setFirmwareVersion(row.getStringColumn("firmware_version")); - } - if (map.get("firmware_url") != null && map.get("firmware_url").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setFirmwareUrl(row.getStringColumn("firmware_url")); - } - - if (map.get("_uuid") != null && map.get("_uuid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_uuid")); - } - if (map.get("upgrade_dl_timer") != null && map.get("upgrade_dl_timer").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setUpgradeDlTimer(row.getIntegerColumn("upgrade_dl_timer").intValue()); - } - if (map.get("platform_version") != null && map.get("platform_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setPlatformVersion(row.getStringColumn("platform_version")); - } - if (map.get("firmware_pass") != null && map.get("firmware_pass").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setFirmwarePass(row.getStringColumn("firmware_pass")); - } - if (map.get("upgrade_timer") != null && map.get("upgrade_timer").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setUpgradeTimer(row.getIntegerColumn("upgrade_timer").intValue()); - } - if (map.get("max_backoff") != null && map.get("max_backoff").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMaxBackoff(row.getIntegerColumn("max_backoff").intValue()); - } - if (map.get("led_config") != null) { - tableState.setLedConfig(row.getMapColumn("led_config")); - } - if (map.get("redirector_addr") != null && map.get("redirector_addr").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setRedirectorAddr(row.getStringColumn("redirector_addr")); - } - if (map.get("serial_number") != null && map.get("serial_number").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setSerialNumber(row.getStringColumn("serial_number")); - } - if (map.get("_version") != null && map.get("_version").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setVersion(row.getUuidColumn("_version")); - } - if (map.get("upgrade_status") != null && map.get("upgrade_status").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setUpgradeTimer(row.getIntegerColumn("upgrade_status").intValue()); - } - if (map.get("device_mode") != null && map.get("device_mode").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setDeviceMode(row.getStringColumn("device_mode")); - } - if (map.get("min_backoff") != null && map.get("min_backoff").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setMinBackoff(row.getIntegerColumn("min_backoff").intValue()); - } - - if (map.get("revision") != null && map.get("revision").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setRevision(row.getStringColumn("revision")); - } - if (map.get("manager_addr") != null && map.get("manager_addr").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setManagerAddr(row.getStringColumn("manager_addr")); - } - if (map.get("factory_reset") != null && map.get("factory_reset").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - tableState.setFactoryReset(row.getBooleanColumn("factory_reset")); - } - } - - } - - } - } catch (Exception e) { - LOG.error("Failed to handle AWLAN_Node update", e); - } - - return tableState; - - } - - public void configureWifiRadios(OvsdbClient ovsdbClient, String configName, - Map provisionedWifiRadios, int channel, Map hwConfig, - String country, int beaconInterval, boolean enabled, String ht_mode, int txPower) - throws OvsdbClientException, TimeoutException, ExecutionException, InterruptedException { - - WifiRadioConfigInfo existingConfig = provisionedWifiRadios.get(configName); - - if (existingConfig == null) { - LOG.warn("There is no WifiRadioConfig {}", configName); - return; - } - - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(configName))); - - updateColumns.put("channel", new Atom<>(channel)); - updateColumns.put("country", new Atom<>(country)); - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map hwConfigMap = com.vmware.ovsdb.protocol.operation.notation.Map - .of(hwConfig); - updateColumns.put("hw_config", hwConfigMap); - updateColumns.put("bcn_int", new Atom<>(beaconInterval)); - updateColumns.put("enabled", new Atom<>(enabled)); - if (ht_mode != null && !ht_mode.equals("0")) { - updateColumns.put("ht_mode", new Atom<>(ht_mode)); - } else { - updateColumns.put("ht_mode", new com.vmware.ovsdb.protocol.operation.notation.Set()); - } - if (txPower > 0) { - updateColumns.put("tx_power", new Atom<>(txPower)); - } else { - updateColumns.put("tx_power", new com.vmware.ovsdb.protocol.operation.notation.Set()); - } - - Row row = new Row(updateColumns); - operations.add(new Update(wifiRadioConfigDbTable, conditions, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned channel {} for {}", channel, configName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - public void configureSingleSsid(OvsdbClient ovsdbClient, String bridge, String ifName, String ssid, - boolean ssidBroadcast, Map security, - Map provisionedWifiRadioConfigs, String radioIfName, int vlanId, - boolean rrmEnabled, boolean enable80211r, String minHwMode, boolean enabled, int keyRefresh, - boolean uapsdEnabled, boolean apBridge, NetworkForwardMode networkForwardMode, String gateway, String inet, - Map dns, String ipAssignScheme) { - - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - try { - updateColumns.put("bridge", new Atom(bridge)); - updateColumns.put("btm", new Atom<>(1)); - updateColumns.put("enabled", new Atom<>(enabled)); - if (enable80211r) { - updateColumns.put("ft_psk", new Atom<>(1)); - updateColumns.put("ft_mobility_domain", new Atom<>(17911)); - } else { - updateColumns.put("ft_psk", new Atom<>(0)); - updateColumns.put("ft_mobility_domain", new com.vmware.ovsdb.protocol.operation.notation.Set()); - } - updateColumns.put("if_name", new Atom<>(ifName)); - updateColumns.put("mode", new Atom<>("ap")); - updateColumns.put("rrm", new Atom<>(rrmEnabled ? 1 : 0)); - updateColumns.put("ssid", new Atom<>(ssid)); - updateColumns.put("ssid_broadcast", new Atom<>(ssidBroadcast ? "enabled" : "disabled")); - updateColumns.put("uapsd_enable", new Atom<>(true)); - // updateColumns.put("vif_radio_idx", new - // Atom(vifRadioIdx)); - updateColumns.put("min_hw_mode", new Atom<>(minHwMode)); - updateColumns.put("vlan_id", new Atom<>(vlanId)); - updateColumns.put("group_rekey", new Atom<>(keyRefresh)); - updateColumns.put("uapsd_enable", new Atom<>(uapsdEnabled)); - updateColumns.put("ap_bridge", new Atom<>(apBridge)); - - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map securityMap = com.vmware.ovsdb.protocol.operation.notation.Map - .of(security); - updateColumns.put("security", securityMap); - - Row row = new Row(updateColumns); - operations.add(new Insert(wifiVifConfigDbTable, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned SSID {} on {}", ssid, ifName); - - Uuid vifConfigUuid = null; - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - if (res instanceof InsertResult) { - vifConfigUuid = ((InsertResult) res).getUuid(); - } - } - - if (vifConfigUuid == null) { - throw new IllegalStateException("Wifi_VIF_Config entry was not created successfully"); - } - - // update Wifi_Radio_Config here - add vifConfigUuid - /// usr/plume/tools/ovsh u Wifi_Radio_Config - // vif_configs:='["set",[["uuid","98e42897-b567-4186-84a6-4a4e38a51e9d"],["uuid","4314920e-c4e6-42a6-93e3-261142ed9adf"]]]' - // --where if_name==wifi0 - updateColumns.clear(); - operations.clear(); - - WifiRadioConfigInfo wifiRadioConfigInfo = provisionedWifiRadioConfigs.get(radioIfName); - if (wifiRadioConfigInfo == null) { - throw new IllegalStateException("missing Wifi_Radio_Config entry " + radioIfName); - } - - Set vifConfigsSet = new HashSet<>(wifiRadioConfigInfo.vifConfigUuids); - vifConfigsSet.add(vifConfigUuid); - com.vmware.ovsdb.protocol.operation.notation.Set vifConfigs = com.vmware.ovsdb.protocol.operation.notation.Set - .of(vifConfigsSet); - updateColumns.put("vif_configs", vifConfigs); - - List conditions = new ArrayList<>(); - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(radioIfName))); - - row = new Row(updateColumns); - operations.add(new Update(wifiRadioConfigDbTable, conditions, row)); - - fResult = ovsdbClient.transact(ovsdbName, operations); - result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Updated WifiRadioConfig {} for SSID {}:", radioIfName, ssid); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - Map inetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); - if (inetConfigs.containsKey(ifName)) { - updateWifiInetConfig(ovsdbClient, vlanId, ifName, enabled, networkForwardMode == NetworkForwardMode.NAT, - "vif", gateway, inet, dns, ipAssignScheme, vifConfigUuid); - } else { - LOG.debug("No corresponding WifiInetConfig for this Interface"); - insertWifiInetConfigForVif(ovsdbClient, vlanId, ifName, enabled, - networkForwardMode == NetworkForwardMode.NAT, "vif", gateway, inet, dns, ipAssignScheme, - vifConfigUuid); - } - - LOG.info("Provisioned SSID {} on interface {} / {}", ssid, ifName, radioIfName); - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureSingleSsid", e); - throw new RuntimeException(e); - } - } - - public void configureSsids(OvsdbClient ovsdbClient, OpensyncAPConfig opensyncApConfig) { - - boolean rrmEnabled = false; - if (opensyncApConfig.getEquipmentLocation() != null - && opensyncApConfig.getEquipmentLocation().getDetails() != null) { - rrmEnabled = opensyncApConfig.getEquipmentLocation().getDetails().isRrmEnabled(); - } - - for (Profile ssidProfile : opensyncApConfig.getSsidProfile()) { - - Map provisionedWifiVifConfigs = getProvisionedWifiVifConfigs(ovsdbClient); - LOG.debug("Existing WifiVifConfigs: {}", provisionedWifiVifConfigs.keySet()); - - SsidConfiguration ssidConfig = (SsidConfiguration) ssidProfile.getDetails(); - ApElementConfiguration apElementConfig = (ApElementConfiguration) opensyncApConfig.getCustomerEquipment() - .getDetails(); - for (RadioType radioType : ssidConfig.getAppliedRadios()) { - - int keyRefresh = ssidConfig.getKeyRefresh(); - - Map provisionedWifiRadioConfigs = getProvisionedWifiRadioConfigs( - ovsdbClient); - - boolean ssidBroadcast = ssidConfig.getBroadcastSsid() == StateSetting.enabled; - Map security = new HashMap<>(); - String ssidSecurityMode = ssidConfig.getSecureMode().name(); - String opensyncSecurityMode = "OPEN"; - - String ipAssignScheme = "none"; - // the following 5 attributes only applicable to static config, - // else they are - // ignored - String gateway = null; - String inet = null; - Map dns = null; - if (apElementConfig.getStaticIP() != null) { - ipAssignScheme = "static"; - inet = apElementConfig.getStaticIP().getHostAddress(); - gateway = apElementConfig.getStaticIpGw().getHostAddress(); - dns = new HashMap<>(); - dns.put(apElementConfig.getStaticDnsIp1().getHostName(), - apElementConfig.getStaticDnsIp1().getHostAddress()); - dns.put(apElementConfig.getStaticDnsIp2().getHostName(), - apElementConfig.getStaticDnsIp2().getHostAddress()); - } else if (apElementConfig.getGettingIP().equals(GettingIP.dhcp) - || apElementConfig.getGettingDNS().equals(GettingDNS.dhcp)) { - ipAssignScheme = "dhcp"; - } - - RadioConfiguration radioConfiguration = apElementConfig.getAdvancedRadioMap().get(radioType); - if (radioConfiguration == null) { - continue; // don't have a radio of this kind in the map - } - RadioMode radioMode = radioConfiguration.getRadioMode(); - - boolean uapsdEnabled = radioConfiguration.getUapsdState() == StateSetting.enabled; - - boolean apBridge = radioConfiguration.getStationIsolation() == StateSetting.enabled; // stationIsolation - boolean enable80211r = false; - - if (ssidConfig.getRadioBasedConfigs() != null) { - if (ssidConfig.getRadioBasedConfigs().containsKey(radioType) - && ssidConfig.getRadioBasedConfigs().get(radioType) != null) { - if (ssidConfig.getRadioBasedConfigs().get(radioType).getEnable80211r() != null) { - enable80211r = ssidConfig.getRadioBasedConfigs().get(radioType).getEnable80211r(); - } - } - } - - String minHwMode = "11n"; // min_hw_mode is 11ac, wifi 5, we can - // also take ++ (11ax) but 2.4GHz only - // Wifi4 -- - if (!radioType.equals(RadioType.is2dot4GHz)) { - minHwMode = "11ac"; - } - if (!radioType.equals(RadioType.is2dot4GHz) && radioMode.equals(RadioMode.modeX)) { - minHwMode = "11x"; - } - - if (ssidSecurityMode.equals("wpaPSK") || ssidSecurityMode.equals("wpa2PSK") - || ssidSecurityMode.equals("wpa2OnlyPSK")) { - opensyncSecurityMode = "WPA-PSK"; - } else if (ssidSecurityMode.equals("wep")) { - opensyncSecurityMode = "WEP"; - } else if (ssidSecurityMode.equals("wpaEAP") || ssidSecurityMode.equals("wpa2EAP") - || ssidSecurityMode.equals("wpa2OnlyEAP")) { - opensyncSecurityMode = "WPA-EAP"; - - } - - security.put("encryption", opensyncSecurityMode); - // key and mode is N/A for OPEN security - if (!opensyncSecurityMode.equals("OPEN")) { - if (ssidSecurityMode.equals("wpa2PSK")) { - security.put("key", ssidConfig.getKeyStr()); - security.put("mode", "mixed"); - } else if (ssidSecurityMode.equals("wpa2OnlyPSK")) { - security.put("key", ssidConfig.getKeyStr()); - security.put("mode", "2"); - } else if (ssidSecurityMode.equals("wpaPSK")) { - security.put("key", ssidConfig.getKeyStr()); - security.put("mode", "1"); - } else if (ssidSecurityMode.equals("wpa2OnlyEAP")) { - security.put("mode", "2"); - getRadiusConfiguration(opensyncApConfig, ssidConfig, security); - } else if (ssidSecurityMode.equals("wpa2EAP")) { - security.put("mode", "mixed"); - getRadiusConfiguration(opensyncApConfig, ssidConfig, security); - } else if (ssidSecurityMode.equals("wpaEAP")) { - security.put("mode", "1"); - getRadiusConfiguration(opensyncApConfig, ssidConfig, security); - } else if (ssidSecurityMode.equals("wep")) { - security.put("key", ssidConfig.getKeyStr()); - security.put("mode", "1"); - } - } - - boolean enabled = ssidConfig.getSsidAdminState().equals(StateSetting.enabled); - - String ifName = null; - String radioIfName = null; - - if (radioType == RadioType.is2dot4GHz) { - ifName = ifName2pt4GHz; - radioIfName = radioName2pt4GHz; - } else if (radioType == RadioType.is5GHzL) { - ifName = ifName5GHzL; - radioIfName = radioName5GHzL; - } else if (radioType == RadioType.is5GHzU) { - ifName = ifName5GHzU; - radioIfName = radioName5GHzU; - } - - if (!provisionedWifiVifConfigs.containsKey(ifName + "_" + ssidConfig.getSsid())) { - try { - configureSingleSsid(ovsdbClient, bridgeNameVifInterfaces, ifName, ssidConfig.getSsid(), - ssidBroadcast, security, provisionedWifiRadioConfigs, radioIfName, - ssidConfig.getVlanId(), rrmEnabled, enable80211r, minHwMode, enabled, keyRefresh, - uapsdEnabled, apBridge, ssidConfig.getForwardMode(), gateway, inet, dns, - ipAssignScheme); - - } catch (IllegalStateException e) { - // could not provision this SSID, but still can go on - LOG.warn("could not provision SSID {} on {}", ssidConfig.getSsid(), radioIfName); - } - } - - } - } - - } - - private void getRadiusConfiguration(OpensyncAPConfig opensyncApConfig, SsidConfiguration ssidConfig, - Map security) { - List radiusServiceList = new ArrayList(); - radiusServiceList = opensyncApConfig.getRadiusProfiles().stream() - .filter(p -> p.getName().equals((ssidConfig.getRadiusServiceName()))).collect(Collectors.toList()); - if (!radiusServiceList.isEmpty()) { - Profile profileRadius = radiusServiceList.get(0); - String region = opensyncApConfig.getEquipmentLocation().getName(); - List radiusServerList = new ArrayList(); - RadiusProfile radiusProfileDetails = ((RadiusProfile) profileRadius.getDetails()); - RadiusServiceRegion radiusServiceRegion = radiusProfileDetails.findServiceRegion(region); - radiusServerList = radiusServiceRegion.findServerConfiguration(ssidConfig.getRadiusServiceName()); - if (!radiusServerList.isEmpty()) { - RadiusServer rServer = radiusServerList.get(0); - security.put("radius_server_ip", rServer.getIpAddress().getHostAddress()); - security.put("radius_server_port", String.valueOf(rServer.getAuthPort())); - security.put("radius_server_secret", rServer.getSecret()); - } - } - } - - private void updateWifiInetConfig(OvsdbClient ovsdbClient, int vlanId, String ifName, boolean enabled, - boolean isNAT, String ifType, String gateway, String inet, Map dns, String ipAssignScheme, - Uuid vifConfigUuid) { - - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); - - try { - /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true - /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none - /// network:=true - // dhcpd - updateColumns.put("if_name", new Atom<>(ifName)); - updateColumns.put("if_type", new Atom<>(ifType)); - updateColumns.put("if_uuid", new Atom<>(vifConfigUuid.toString())); - updateColumns.put("enabled", new Atom<>(enabled)); - updateColumns.put("NAT", new Atom<>(isNAT)); - - // mtu // specified in interface, should take that value when - // implemented - updateColumns.put("mtu", new Atom<>(1500)); - updateColumns.put("network", new Atom<>(true)); - - updateColumns.put("ip_assign_scheme", new Atom<>(ipAssignScheme)); - - if (ipAssignScheme.equals("static")) { - updateColumns.put("dns", com.vmware.ovsdb.protocol.operation.notation.Map.of(dns)); - updateColumns.put("inet_addr", new Atom<>(inet)); - updateColumns.put("gateway", new Atom<>(gateway)); - // netmask - // broadcast - } - if (ipAssignScheme.equals("dhcp")) { - updateColumns.put("dhcp_sniff", new Atom<>(true)); - } else { - updateColumns.put("dhcp_sniff", new Atom<>(false)); - } - - if (ifType.equals("vlan")) { - updateColumns.put("vlan_id", new Atom<>(vlanId)); - } else { - updateColumns.put("vlan_id", new com.vmware.ovsdb.protocol.operation.notation.Set()); - } - - Row row = new Row(updateColumns); - operations.add(new Update(wifiInetConfigDbTable, conditions, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned WifiInetConfig {}", ifName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureWifiInet", e); - throw new RuntimeException(e); - } - - } - - private void insertWifiInetConfigForVif(OvsdbClient ovsdbClient, int vlanId, String ifName, boolean enabled, - boolean isNAT, String ifType, String gateway, String inet, Map dns, String ipAssignScheme, - Uuid vifConfigUuid) { - - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - try { - /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true - /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none - /// network:=true - // dhcpd - updateColumns.put("if_name", new Atom<>(ifName)); - updateColumns.put("if_type", new Atom<>(ifType)); - updateColumns.put("if_uuid", new Atom<>(vifConfigUuid.toString())); - updateColumns.put("enabled", new Atom<>(enabled)); - updateColumns.put("NAT", new Atom<>(isNAT)); - - // mtu // specified in interface, should take that value when - // implemented - updateColumns.put("mtu", new Atom<>(1500)); - updateColumns.put("network", new Atom<>(true)); - - updateColumns.put("ip_assign_scheme", new Atom<>(ipAssignScheme)); - - if (ipAssignScheme.equals("static")) { - updateColumns.put("dns", com.vmware.ovsdb.protocol.operation.notation.Map.of(dns)); - updateColumns.put("inet_addr", new Atom<>(inet)); - updateColumns.put("gateway", new Atom<>(gateway)); - // netmask - // broadcast - } - if (ipAssignScheme.equals("dhcp")) { - updateColumns.put("dhcp_sniff", new Atom<>(true)); - } else { - updateColumns.put("dhcp_sniff", new Atom<>(false)); - } - - if (ifType.equals("vlan")) { - updateColumns.put("vlan_id", new Atom<>(vlanId)); - } else { - updateColumns.put("vlan_id", new com.vmware.ovsdb.protocol.operation.notation.Set()); - } - - Row row = new Row(updateColumns); - operations.add(new Insert(wifiInetConfigDbTable, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - LOG.debug("Provisioned WifiInetConfig {}", ifName); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureWifiInet", e); - throw new RuntimeException(e); - } - - } - - public void configureWifiInet(OvsdbClient ovsdbClient, Map provisionedWifiInetConfigs, - String ifName) { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - try { - /// usr/plume/tools/ovsh i Wifi_Inet_Config NAT:=false enabled:=true - /// if_name:=home-ap-24 if_type:=vif ip_assign_scheme:=none - /// network:=true - - updateColumns.put("NAT", new Atom<>(false)); - updateColumns.put("enabled", new Atom<>(true)); - updateColumns.put("if_name", new Atom<>(ifName)); - updateColumns.put("if_type", new Atom<>("vif")); - updateColumns.put("ip_assign_scheme", new Atom<>("none")); - updateColumns.put("network", new Atom<>(true)); + LOG.debug("Provisioned WifiInetConfig {}", ifName); - Row row = new Row(updateColumns); - operations.add(new Insert(wifiInetConfigDbTable, row)); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureWifiInet", e); + throw new RuntimeException(e); + } - LOG.debug("Provisioned WifiInetConfig {}", ifName); + } - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + public void configureWifiInetSetNetwork(OvsdbClient ovsdbClient, String ifName) { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureWifiInet", e); - throw new RuntimeException(e); - } + try { + /// usr/plume/tools/ovsh u Wifi_Inet_Config -w if_name=="br-home" + /// network:=true + + conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); + updateColumns.put("network", new Atom<>(true)); + + Row row = new Row(updateColumns); + operations.add(new Update(wifiInetConfigDbTable, conditions, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - } + LOG.debug("Enabled network on WifiInetConfig {}", ifName); - public void configureWifiInetSetNetwork(OvsdbClient ovsdbClient, String ifName) { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - try { - /// usr/plume/tools/ovsh u Wifi_Inet_Config -w if_name=="br-home" - /// network:=true - - conditions.add(new Condition("if_name", Function.EQUALS, new Atom<>(ifName))); - updateColumns.put("network", new Atom<>(true)); - - Row row = new Row(updateColumns); - operations.add(new Update(wifiInetConfigDbTable, conditions, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureWifiInetSetNetwork", e); + throw new RuntimeException(e); + } - LOG.debug("Enabled network on WifiInetConfig {}", ifName); + } - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + public void configureWifiInet(OvsdbClient ovsdbClient) { + Map provisionedWifiInetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); + LOG.debug("Existing WifiInetConfigs: {}", provisionedWifiInetConfigs.keySet()); - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureWifiInetSetNetwork", e); - throw new RuntimeException(e); - } + String ifName = ifName2pt4GHz; + if (!provisionedWifiInetConfigs.containsKey(ifName)) { + configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); + } - } + ifName = ifName5GHzL; + if (!provisionedWifiInetConfigs.containsKey(ifName)) { + configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); + } - public void configureWifiInet(OvsdbClient ovsdbClient) { - Map provisionedWifiInetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); - LOG.debug("Existing WifiInetConfigs: {}", provisionedWifiInetConfigs.keySet()); + ifName = ifName5GHzU; + if (!provisionedWifiInetConfigs.containsKey(ifName)) { + configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); + } - String ifName = ifName2pt4GHz; - if (!provisionedWifiInetConfigs.containsKey(ifName)) { - configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); - } + if (!provisionedWifiInetConfigs.containsKey(brLan) || !provisionedWifiInetConfigs.get(brLan).network) { + // set network flag on brHome in wifiInetConfig table + configureWifiInetSetNetwork(ovsdbClient, brLan); + } + } - ifName = ifName5GHzL; - if (!provisionedWifiInetConfigs.containsKey(ifName)) { - configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); - } + public void configureStats(OvsdbClient ovsdbClient) { - ifName = ifName5GHzU; - if (!provisionedWifiInetConfigs.containsKey(ifName)) { - configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); - } + try { + List operations = new ArrayList<>(); + Map thresholdMap = new HashMap<>(); + thresholdMap.put("max_delay", 600); + thresholdMap.put("util", 10); - if (!provisionedWifiInetConfigs.containsKey(brLan) || !provisionedWifiInetConfigs.get(brLan).network) { - // set network flag on brHome in wifiInetConfig table - configureWifiInetSetNetwork(ovsdbClient, brLan); - } - } + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map thresholds = com.vmware.ovsdb.protocol.operation.notation.Map + .of(thresholdMap); - public void configureStats(OvsdbClient ovsdbClient) { + Map radioConfigs = getProvisionedWifiRadioConfigs(ovsdbClient); + provisionWifiStatsConfigSurvey(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations, + thresholds); - try { - List operations = new ArrayList<>(); - Map thresholdMap = new HashMap<>(); - thresholdMap.put("max_delay", 600); - thresholdMap.put("util", 10); + provisionWifiStatsConfigNeighbor(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map thresholds = com.vmware.ovsdb.protocol.operation.notation.Map - .of(thresholdMap); - - Map radioConfigs = getProvisionedWifiRadioConfigs(ovsdbClient); - provisionWifiStatsConfigSurvey(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations, - thresholds); - - provisionWifiStatsConfigNeighbor(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsConfigClient(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsConfigBandSteering(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsConfigCapacity(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsRssi(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - if (!operations.isEmpty()) { - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Updated {}:", wifiStatsConfigDbTable); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - } - - private void provisionWifiStatsConfigCapacity(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations) { - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_capacity")) { - // - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(60)); -// rowColumns.put("sampling_interval", new Atom<>(3)); - rowColumns.put("stats_type", new Atom<>("capacity")); -// rowColumns.put("survey_interval_ms", new Atom<>(65)); -// rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - - } - - private void provisionWifiStatsConfigBandSteering(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations) { - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_steering")) { - // - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(60)); -// rowColumns.put("sampling_interval", new Atom<>(3)); - rowColumns.put("stats_type", new Atom<>("steering")); -// rowColumns.put("survey_interval_ms", new Atom<>(65)); -// rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - - } - - private void provisionWifiStatsRssi(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations) { - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_rssi")) { - // - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(30)); -// rowColumns.put("sampling_interval", new Atom<>(3)); - rowColumns.put("stats_type", new Atom<>("rssi")); - rowColumns.put("survey_interval_ms", new Atom<>(65)); -// rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - } - - private void provisionWifiStatsConfigNeighbor(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations) { - Map updateColumns; - Row row; - - // For off channel, all allowed channels -// * 2412 MHz [1] (30.0 dBm) -// * 2417 MHz [2] (30.0 dBm) -// * 2422 MHz [3] (30.0 dBm) -// * 2427 MHz [4] (30.0 dBm) -// * 2432 MHz [5] (30.0 dBm) -// * 2437 MHz [6] (30.0 dBm) -// * 2442 MHz [7] (30.0 dBm) -// * 2447 MHz [8] (30.0 dBm) -// * 2452 MHz [9] (30.0 dBm) -// * 2457 MHz [10] (30.0 dBm) -// * 2462 MHz [11] (30.0 dBm) - Set channelSet2g = new HashSet<>(); - channelSet2g.add(1); -// channelSet2g.add(2); -// channelSet2g.add(3); -// channelSet2g.add(4); -// channelSet2g.add(5); - channelSet2g.add(6); -// channelSet2g.add(7); -// channelSet2g.add(8); -// channelSet2g.add(9); -// channelSet2g.add(10); - channelSet2g.add(11); - - com.vmware.ovsdb.protocol.operation.notation.Set channels2g = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet2g); - - Set channelSet5gl = new HashSet<>(); -// * 5180 MHz [36] (23.0 dBm) -// * 5200 MHz [40] (23.0 dBm) -// * 5220 MHz [44] (23.0 dBm) -// * 5240 MHz [48] (23.0 dBm) -// * 5260 MHz [52] (24.0 dBm) (radar detection) -// * 5280 MHz [56] (24.0 dBm) (radar detection) -// * 5300 MHz [60] (24.0 dBm) (radar detection) -// * 5320 MHz [64] (24.0 dBm) (radar detection) - channelSet5gl.add(36); - channelSet5gl.add(40); - channelSet5gl.add(44); - channelSet5gl.add(48); -// channelSet5gl.add(52); -// channelSet5gl.add(56); -// channelSet5gl.add(60); -// channelSet5gl.add(64); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gl); - - Set channelSet5gu = new HashSet<>(); -// * 5500 MHz [100] (24.0 dBm) (radar detection) -// * 5520 MHz [104] (24.0 dBm) (radar detection) -// * 5540 MHz [108] (24.0 dBm) (radar detection) -// * 5560 MHz [112] (24.0 dBm) (radar detection) -// * 5580 MHz [116] (24.0 dBm) (radar detection) -// * 5600 MHz [120] (disabled) -// * 5620 MHz [124] (disabled) -// * 5640 MHz [128] (disabled) -// * 5660 MHz [132] (24.0 dBm) (radar detection) -// * 5680 MHz [136] (24.0 dBm) (radar detection) -// * 5700 MHz [140] (24.0 dBm) (radar detection) -// * 5720 MHz [144] (24.0 dBm) (radar detection) -// * 5745 MHz [149] (30.0 dBm) -// * 5765 MHz [153] (30.0 dBm) -// * 5785 MHz [157] (30.0 dBm) -// * 5805 MHz [161] (30.0 dBm) -// * 5825 MHz [165] (30.0 dBm) -// channelSet5gu.add(100); -// channelSet5gu.add(104); -// channelSet5gu.add(108); -// channelSet5gu.add(112); -// channelSet5gu.add(116); -// channelSet5gu.add(132); -// channelSet5gu.add(136); -// channelSet5gu.add(140); -// channelSet5gu.add(144); - channelSet5gu.add(149); - channelSet5gu.add(153); - channelSet5gu.add(157); - channelSet5gu.add(161); - channelSet5gu.add(165); - - com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gu); - - if (!provisionedWifiStatsConfigs.containsKey("2.4G_neighbor_off-chan")) { - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels2g); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_interval", new Atom<>(120)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_type", new Atom<>("off-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_neighbor_off-chan")) { - - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels5gl); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_interval", new Atom<>(120)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_type", new Atom<>("off-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - if (!provisionedWifiStatsConfigs.containsKey("5GU_neighbor_off-chan")) { - - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels5gu); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_interval", new Atom<>(120)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_type", new Atom<>("off-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_neighbor_on-chan")) { - // - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(60)); - rowColumns.put("stats_type", new Atom<>("neighbor")); - rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - - } - - private void provisionWifiStatsConfigSurvey(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations, - com.vmware.ovsdb.protocol.operation.notation.Map thresholds) { - - Set channelSet2g = new HashSet<>(); - channelSet2g.add(1); - channelSet2g.add(6); - channelSet2g.add(11); - com.vmware.ovsdb.protocol.operation.notation.Set channels2g = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet2g); - - Set channelSet5gl = new HashSet<>(); - channelSet5gl.add(36); - channelSet5gl.add(40); - channelSet5gl.add(44); - channelSet5gl.add(48); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gl); - - Set channelSet5gu = new HashSet<>(); - channelSet5gu.add(149); - channelSet5gu.add(153); - channelSet5gu.add(157); - channelSet5gu.add(161); - channelSet5gu.add(165); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gu); - - Map updateColumns; - Row row; - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_survey_on-chan")) { - - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(60)); - rowColumns.put("report_type", new Atom<>("raw")); - rowColumns.put("sampling_interval", new Atom<>(6)); - rowColumns.put("stats_type", new Atom<>("survey")); - rowColumns.put("survey_interval_ms", new Atom<>(65)); - rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - - if (!provisionedWifiStatsConfigs.containsKey("2.4G_survey_off-chan")) { - - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels2g); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_interval", new Atom<>(600)); - updateColumns.put("report_type", new Atom<>("raw")); - updateColumns.put("sampling_interval", new Atom<>(60)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(65)); - updateColumns.put("survey_type", new Atom<>("off-chan")); - updateColumns.put("threshold", thresholds); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_survey_off-chan")) { - - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels5gl); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_interval", new Atom<>(600)); - updateColumns.put("report_type", new Atom<>("raw")); - updateColumns.put("sampling_interval", new Atom<>(45)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(65)); - updateColumns.put("survey_type", new Atom<>("off-chan")); - updateColumns.put("threshold", thresholds); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - if (!provisionedWifiStatsConfigs.containsKey("5GU_survey_off-chan")) { - - updateColumns = new HashMap<>(); - updateColumns.put("channel_list", channels5gu); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_interval", new Atom<>(600)); - updateColumns.put("report_type", new Atom<>("raw")); - updateColumns.put("sampling_interval", new Atom<>(30)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(65)); - updateColumns.put("survey_type", new Atom<>("off-chan")); - updateColumns.put("threshold", thresholds); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - } - - private void provisionWifiStatsConfigClient(Map radioConfigs, - Map provisionedWifiStatsConfigs, List operations) { - - radioConfigs.values().stream().forEach(rc -> { - if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_client")) { - // - Map rowColumns = new HashMap<>(); - rowColumns.put("radio_type", new Atom<>(rc.freqBand)); - rowColumns.put("reporting_interval", new Atom<>(60)); - rowColumns.put("report_type", new Atom<>("raw")); - rowColumns.put("sampling_interval", new Atom<>(10)); - rowColumns.put("stats_type", new Atom<>("client")); - rowColumns.put("survey_interval_ms", new Atom<>(65)); -// rowColumns.put("survey_type", new Atom<>("on-chan")); - - Row updateRow = new Row(rowColumns); - operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); - - } - }); - - } - - public String changeRedirectorAddress(OvsdbClient ovsdbClient, String apId, String newRedirectorAddress) { - try { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - - updateColumns.put("redirector_addr", new Atom<>(newRedirectorAddress)); - - Row row = new Row(updateColumns); - operations.add(new Update(awlanNodeDbTable, row)); - - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - - if (LOG.isDebugEnabled()) { - LOG.debug("Updated {} redirector_addr = {}", awlanNodeDbTable, newRedirectorAddress); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - - return newRedirectorAddress; - } + provisionWifiStatsConfigClient(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + provisionWifiStatsConfigBandSteering(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + provisionWifiStatsConfigCapacity(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + provisionWifiStatsRssi(radioConfigs, getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + if (!operations.isEmpty()) { + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Updated {}:", wifiStatsConfigDbTable); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + private void provisionWifiStatsConfigCapacity(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations) { + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_capacity")) { + // + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(60)); + // rowColumns.put("sampling_interval", new Atom<>(3)); + rowColumns.put("stats_type", new Atom<>("capacity")); + // rowColumns.put("survey_interval_ms", new Atom<>(65)); + // rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + + } + + private void provisionWifiStatsConfigBandSteering(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations) { + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_steering")) { + // + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(60)); + // rowColumns.put("sampling_interval", new Atom<>(3)); + rowColumns.put("stats_type", new Atom<>("steering")); + // rowColumns.put("survey_interval_ms", new Atom<>(65)); + // rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + + } + + private void provisionWifiStatsRssi(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations) { + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_rssi")) { + // + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(30)); + // rowColumns.put("sampling_interval", new Atom<>(3)); + rowColumns.put("stats_type", new Atom<>("rssi")); + rowColumns.put("survey_interval_ms", new Atom<>(65)); + // rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + } + + private void provisionWifiStatsConfigNeighbor(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations) { + Map updateColumns; + Row row; + + // For off channel, all allowed channels + // * 2412 MHz [1] (30.0 dBm) + // * 2417 MHz [2] (30.0 dBm) + // * 2422 MHz [3] (30.0 dBm) + // * 2427 MHz [4] (30.0 dBm) + // * 2432 MHz [5] (30.0 dBm) + // * 2437 MHz [6] (30.0 dBm) + // * 2442 MHz [7] (30.0 dBm) + // * 2447 MHz [8] (30.0 dBm) + // * 2452 MHz [9] (30.0 dBm) + // * 2457 MHz [10] (30.0 dBm) + // * 2462 MHz [11] (30.0 dBm) + Set channelSet2g = new HashSet<>(); + channelSet2g.add(1); + // channelSet2g.add(2); + // channelSet2g.add(3); + // channelSet2g.add(4); + // channelSet2g.add(5); + channelSet2g.add(6); + // channelSet2g.add(7); + // channelSet2g.add(8); + // channelSet2g.add(9); + // channelSet2g.add(10); + channelSet2g.add(11); + + com.vmware.ovsdb.protocol.operation.notation.Set channels2g = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet2g); + + Set channelSet5gl = new HashSet<>(); + // * 5180 MHz [36] (23.0 dBm) + // * 5200 MHz [40] (23.0 dBm) + // * 5220 MHz [44] (23.0 dBm) + // * 5240 MHz [48] (23.0 dBm) + // * 5260 MHz [52] (24.0 dBm) (radar detection) + // * 5280 MHz [56] (24.0 dBm) (radar detection) + // * 5300 MHz [60] (24.0 dBm) (radar detection) + // * 5320 MHz [64] (24.0 dBm) (radar detection) + channelSet5gl.add(36); + channelSet5gl.add(40); + channelSet5gl.add(44); + channelSet5gl.add(48); + // channelSet5gl.add(52); + // channelSet5gl.add(56); + // channelSet5gl.add(60); + // channelSet5gl.add(64); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gl); + + Set channelSet5gu = new HashSet<>(); + // * 5500 MHz [100] (24.0 dBm) (radar detection) + // * 5520 MHz [104] (24.0 dBm) (radar detection) + // * 5540 MHz [108] (24.0 dBm) (radar detection) + // * 5560 MHz [112] (24.0 dBm) (radar detection) + // * 5580 MHz [116] (24.0 dBm) (radar detection) + // * 5600 MHz [120] (disabled) + // * 5620 MHz [124] (disabled) + // * 5640 MHz [128] (disabled) + // * 5660 MHz [132] (24.0 dBm) (radar detection) + // * 5680 MHz [136] (24.0 dBm) (radar detection) + // * 5700 MHz [140] (24.0 dBm) (radar detection) + // * 5720 MHz [144] (24.0 dBm) (radar detection) + // * 5745 MHz [149] (30.0 dBm) + // * 5765 MHz [153] (30.0 dBm) + // * 5785 MHz [157] (30.0 dBm) + // * 5805 MHz [161] (30.0 dBm) + // * 5825 MHz [165] (30.0 dBm) + // channelSet5gu.add(100); + // channelSet5gu.add(104); + // channelSet5gu.add(108); + // channelSet5gu.add(112); + // channelSet5gu.add(116); + // channelSet5gu.add(132); + // channelSet5gu.add(136); + // channelSet5gu.add(140); + // channelSet5gu.add(144); + channelSet5gu.add(149); + channelSet5gu.add(153); + channelSet5gu.add(157); + channelSet5gu.add(161); + channelSet5gu.add(165); + + com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gu); + + if (!provisionedWifiStatsConfigs.containsKey("2.4G_neighbor_off-chan")) { + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels2g); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_interval", new Atom<>(120)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_type", new Atom<>("off-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_neighbor_off-chan")) { + + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels5gl); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_interval", new Atom<>(120)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_type", new Atom<>("off-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + if (!provisionedWifiStatsConfigs.containsKey("5GU_neighbor_off-chan")) { + + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels5gu); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_interval", new Atom<>(120)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_type", new Atom<>("off-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_neighbor_on-chan")) { + // + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(60)); + rowColumns.put("stats_type", new Atom<>("neighbor")); + rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + + } + + private void provisionWifiStatsConfigSurvey(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations, + com.vmware.ovsdb.protocol.operation.notation.Map thresholds) { + + Set channelSet2g = new HashSet<>(); + channelSet2g.add(1); + channelSet2g.add(6); + channelSet2g.add(11); + com.vmware.ovsdb.protocol.operation.notation.Set channels2g = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet2g); + + Set channelSet5gl = new HashSet<>(); + channelSet5gl.add(36); + channelSet5gl.add(40); + channelSet5gl.add(44); + channelSet5gl.add(48); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gl); + + Set channelSet5gu = new HashSet<>(); + channelSet5gu.add(149); + channelSet5gu.add(153); + channelSet5gu.add(157); + channelSet5gu.add(161); + channelSet5gu.add(165); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gu); + + Map updateColumns; + Row row; + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_survey_on-chan")) { + + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(60)); + rowColumns.put("report_type", new Atom<>("raw")); + rowColumns.put("sampling_interval", new Atom<>(6)); + rowColumns.put("stats_type", new Atom<>("survey")); + rowColumns.put("survey_interval_ms", new Atom<>(65)); + rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + + if (!provisionedWifiStatsConfigs.containsKey("2.4G_survey_off-chan")) { + + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels2g); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_interval", new Atom<>(600)); + updateColumns.put("report_type", new Atom<>("raw")); + updateColumns.put("sampling_interval", new Atom<>(60)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(65)); + updateColumns.put("survey_type", new Atom<>("off-chan")); + updateColumns.put("threshold", thresholds); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_survey_off-chan")) { + + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels5gl); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_interval", new Atom<>(600)); + updateColumns.put("report_type", new Atom<>("raw")); + updateColumns.put("sampling_interval", new Atom<>(45)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(65)); + updateColumns.put("survey_type", new Atom<>("off-chan")); + updateColumns.put("threshold", thresholds); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + if (!provisionedWifiStatsConfigs.containsKey("5GU_survey_off-chan")) { + + updateColumns = new HashMap<>(); + updateColumns.put("channel_list", channels5gu); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_interval", new Atom<>(600)); + updateColumns.put("report_type", new Atom<>("raw")); + updateColumns.put("sampling_interval", new Atom<>(30)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(65)); + updateColumns.put("survey_type", new Atom<>("off-chan")); + updateColumns.put("threshold", thresholds); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + } + + private void provisionWifiStatsConfigClient(Map radioConfigs, + Map provisionedWifiStatsConfigs, List operations) { + + radioConfigs.values().stream().forEach(rc -> { + if (!provisionedWifiStatsConfigs.containsKey(rc.freqBand + "_client")) { + // + Map rowColumns = new HashMap<>(); + rowColumns.put("radio_type", new Atom<>(rc.freqBand)); + rowColumns.put("reporting_interval", new Atom<>(60)); + rowColumns.put("report_type", new Atom<>("raw")); + rowColumns.put("sampling_interval", new Atom<>(10)); + rowColumns.put("stats_type", new Atom<>("client")); + rowColumns.put("survey_interval_ms", new Atom<>(65)); + // rowColumns.put("survey_type", new Atom<>("on-chan")); + + Row updateRow = new Row(rowColumns); + operations.add(new Insert(wifiStatsConfigDbTable, updateRow)); + + } + }); + + } + + public String changeRedirectorAddress(OvsdbClient ovsdbClient, String apId, String newRedirectorAddress) { + try { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + + updateColumns.put("redirector_addr", new Atom<>(newRedirectorAddress)); + + Row row = new Row(updateColumns); + operations.add(new Update(awlanNodeDbTable, row)); + + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + + if (LOG.isDebugEnabled()) { + LOG.debug("Updated {} redirector_addr = {}", awlanNodeDbTable, newRedirectorAddress); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } + + } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + throw new RuntimeException(e); + } + + return newRedirectorAddress; + } }