From b91adbcd4cf9a6bb7d599c56d429267d0a667057 Mon Sep 17 00:00:00 2001 From: Mike Hansen Date: Thu, 4 Jun 2020 09:10:01 -0400 Subject: [PATCH] Wifi_Radio_State table updates handling. Remove temp objects, begin refactor for MQTT messages --- .../OpensyncExternalIntegrationCloud.java | 2598 ++++----- .../models/OpensyncAPRadioState.java | 7 +- ...yncProcess (local, KDC certs) cloud.launch | 2 +- .../opensync/ovsdb/ConnectusOvsdbClient.java | 740 +-- .../wlan/opensync/ovsdb/dao/OvsdbDao.java | 5023 +++++++++-------- 5 files changed, 3995 insertions(+), 4375 deletions(-) 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 1104848..5b0cdd4 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 @@ -3,7 +3,6 @@ package com.telecominfraproject.wlan.opensync.external.integration; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -22,23 +21,18 @@ import org.springframework.cache.CacheManager; import org.springframework.stereotype.Component; import com.telecominfraproject.wlan.client.ClientServiceInterface; -import com.telecominfraproject.wlan.client.info.models.ClientInfoDetails; -import com.telecominfraproject.wlan.client.session.models.ClientDhcpDetails; -import com.telecominfraproject.wlan.client.session.models.ClientSession; -import com.telecominfraproject.wlan.client.session.models.ClientSessionDetails; -import com.telecominfraproject.wlan.client.session.models.ClientSessionMetricDetails; import com.telecominfraproject.wlan.cloudeventdispatcher.CloudEventDispatcherInterface; import com.telecominfraproject.wlan.core.model.entity.CountryCode; +import com.telecominfraproject.wlan.core.model.equipment.AutoOrManualValue; import com.telecominfraproject.wlan.core.model.equipment.EquipmentType; import com.telecominfraproject.wlan.core.model.equipment.MacAddress; import com.telecominfraproject.wlan.core.model.equipment.RadioType; -import com.telecominfraproject.wlan.core.model.equipment.SecurityType; import com.telecominfraproject.wlan.customer.models.Customer; import com.telecominfraproject.wlan.customer.service.CustomerServiceInterface; import com.telecominfraproject.wlan.equipment.EquipmentServiceInterface; import com.telecominfraproject.wlan.equipment.models.ApElementConfiguration; -import com.telecominfraproject.wlan.equipment.models.ElementRadioConfiguration; import com.telecominfraproject.wlan.equipment.models.Equipment; +import com.telecominfraproject.wlan.equipment.models.StateSetting; import com.telecominfraproject.wlan.location.models.Location; import com.telecominfraproject.wlan.location.service.LocationServiceInterface; import com.telecominfraproject.wlan.opensync.external.integration.controller.OpensyncCloudGatewayController; @@ -61,8 +55,6 @@ import com.telecominfraproject.wlan.servicemetric.apnode.models.ApNodeMetrics; import com.telecominfraproject.wlan.servicemetric.apnode.models.ApPerformance; import com.telecominfraproject.wlan.servicemetric.apnode.models.EthernetLinkState; import com.telecominfraproject.wlan.servicemetric.apnode.models.RadioUtilization; -import com.telecominfraproject.wlan.servicemetric.apssid.models.ApSsidMetrics; -import com.telecominfraproject.wlan.servicemetric.apssid.models.SsidStatistics; import com.telecominfraproject.wlan.servicemetric.client.models.ClientMetrics; import com.telecominfraproject.wlan.servicemetric.models.ServiceMetric; import com.telecominfraproject.wlan.status.StatusServiceInterface; @@ -73,8 +65,6 @@ import com.telecominfraproject.wlan.status.equipment.models.EquipmentProtocolSta import com.telecominfraproject.wlan.status.equipment.models.EquipmentUpgradeState; import com.telecominfraproject.wlan.status.equipment.models.EquipmentUpgradeStatusData; import com.telecominfraproject.wlan.status.equipment.models.VLANStatusData; -import com.telecominfraproject.wlan.status.equipment.report.models.ActiveBSSID; -import com.telecominfraproject.wlan.status.equipment.report.models.ActiveBSSIDs; import com.telecominfraproject.wlan.status.models.Status; import com.telecominfraproject.wlan.status.models.StatusCode; import com.telecominfraproject.wlan.status.models.StatusDataType; @@ -97,1573 +87,1109 @@ import wc.stats.IpDnsTelemetry.WCStatsReport; @Component public class OpensyncExternalIntegrationCloud implements OpensyncExternalIntegrationInterface { - private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); - - @Autowired - private CustomerServiceInterface customerServiceInterface; - @Autowired - private LocationServiceInterface locationServiceInterface; - @Autowired - private OvsdbSessionMapInterface ovsdbSessionMapInterface; - @Autowired - private 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:2}") - 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; - private Map opensyncNodeMap; - - @Value("${connectus.ovsdb.configFileName:/Users/mikehansen/git/wlan-cloud-workspace/wlan-cloud-opensync-controller/opensync-ext-cloud/src/main/resources/config_2_ssids.json}") - private String configFileName; - - @PostConstruct - private void postCreate() { - LOG.info("Using Cloud integration"); - cloudEquipmentRecordCache = cacheManagerShortLived.getCache("equipment_record_cache"); - opensyncNodeMap = Collections.synchronizedMap(new HashMap()); - } - - 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; - } - - public void apConnected(String apId, ConnectNodeInfo connectNodeInfo) { - LOG.info("AP {} got connected to the gateway", apId); - LOG.debug("ConnectNodeInfo {}", connectNodeInfo); - - Equipment ce = null; - try { - ce = getCustomerEquipment(apId); - } catch (Exception e) { - LOG.error("Caught exception getting equipment for Id {}", apId, e); - } - - try { - - if (ce == null) { - - ce = new Equipment(); - ce.setCustomerId(autoProvisionedCustomerId); - ce.setInventoryId(apId); - ce.setEquipmentType(EquipmentType.AP); - ce.setName(apId); - - ce.setSerial(connectNodeInfo.serialNumber); - ApElementConfiguration apElementConfig = ApElementConfiguration.createWithDefaults(); - apElementConfig.setDeviceName(apId); - ce.setDetails(apElementConfig); - ce.setLocationId(autoProvisionedLocationId); - ce.setProfileId(autoProvisionedProfileId); - - ce = equipmentServiceInterface.create(ce); - } - - Profile apProfile = profileServiceInterface.getOrNull(ce.getProfileId()); - - if (apProfile == null || !apProfile.getProfileType().equals(ProfileType.equipment_ap)) { - apProfile = new Profile(); - apProfile.setCustomerId(ce.getCustomerId()); - apProfile.setName("autoprovisionedApProfile"); - apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); - apProfile = profileServiceInterface.create(apProfile); - - Profile profileSsid2do4GHz = new Profile(); - profileSsid2do4GHz.setCustomerId(ce.getCustomerId()); - profileSsid2do4GHz.setName("autoProvisionedSsid"); - SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); - Set appliedRadios = new HashSet(); - appliedRadios.add(RadioType.is2dot4GHz); - ssidConfig.setAppliedRadios(appliedRadios); - profileSsid2do4GHz.setDetails(ssidConfig); - profileSsid2do4GHz = profileServiceInterface.create(profileSsid2do4GHz); - - Profile profileSsid5GHzL = new Profile(); - profileSsid5GHzL.setCustomerId(ce.getCustomerId()); - profileSsid5GHzL.setName("autoProvisionedSsid-5l"); - ssidConfig = SsidConfiguration.createWithDefaults(); - appliedRadios = new HashSet(); - appliedRadios.add(RadioType.is5GHzL); - ssidConfig.setAppliedRadios(appliedRadios); - profileSsid5GHzL.setDetails(ssidConfig); - profileSsid5GHzL = profileServiceInterface.create(profileSsid5GHzL); - - Profile profileSsid5GHzU = new Profile(); - profileSsid5GHzU.setCustomerId(ce.getCustomerId()); - profileSsid5GHzU.setName("autoProvisionedSsid-5u"); - ssidConfig = SsidConfiguration.createWithDefaults(); - appliedRadios = new HashSet(); - appliedRadios.add(RadioType.is5GHzU); - ssidConfig.setAppliedRadios(appliedRadios); - profileSsid5GHzU.setDetails(ssidConfig); - profileSsid5GHzU = profileServiceInterface.create(profileSsid5GHzU); - - Set childProfileIds = new HashSet(); - childProfileIds.add(profileSsid2do4GHz.getId()); - childProfileIds.add(profileSsid5GHzL.getId()); - childProfileIds.add(profileSsid5GHzU.getId()); - apProfile.setChildProfileIds(childProfileIds); - - apProfile = profileServiceInterface.update(apProfile); - - // update AP only if the apProfile was missing - 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); - } - - updateApStatus(ce, connectNodeInfo); - - // register equipment routing record - EquipmentRoutingRecord equipmentRoutingRecord = new EquipmentRoutingRecord(); - equipmentRoutingRecord.setGatewayId(gatewayController.getRegisteredGwId()); - equipmentRoutingRecord.setCustomerId(ce.getCustomerId()); - equipmentRoutingRecord.setEquipmentId(ce.getId()); - equipmentRoutingRecord = routingServiceInterface.create(equipmentRoutingRecord); - - gatewayController.registerCustomerEquipment(ce.getName(), ce.getCustomerId(), ce.getId()); - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - ovsdbSession.setRoutingId(equipmentRoutingRecord.getId()); - ovsdbSession.setEquipmentId(ce.getId()); - ovsdbSession.setCustomerId(ce.getCustomerId()); - - LOG.debug("Equipment {}", Equipment.toPrettyJsonString(ce)); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - 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); - - 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); - - 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(), 0, - 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(), 0, - StatusDataType.NETWORK_AGGREGATE); - if (networkAggStatusRec == null) { - networkAggStatusRec = new Status(); - networkAggStatusRec.setCustomerId(ce.getCustomerId()); - NetworkAggregateStatusData naStatusData = new NetworkAggregateStatusData(); - networkAggStatusRec.setDetails(naStatusData); - } - - UserDetails userDetails = ((NetworkAggregateStatusData) networkAggStatusRec.getDetails()).getUserDetails(); - if (userDetails != null) - LOG.debug("UserDetails {}", userDetails.toPrettyString()); - - statusServiceInterface.update(networkAggStatusRec); - - } catch (Exception e) { - // do nothing - LOG.debug("Exception in updateApStatus", e); - } - - } - - public void apDisconnected(String apId) { - LOG.info("AP {} got disconnected from the gateway", apId); - try { - // removed the 'in-memory' cached node - synchronized (opensyncNodeMap) { - opensyncNodeMap.remove(apId); - LOG.info("AP {} and table state data removed from memory cache", apId); - } - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession != null) { - routingServiceInterface.delete(ovsdbSession.getRoutingId()); - } else { - LOG.warn("Cannot find ap {} in inventory", apId); - } - } catch (Exception e) { - LOG.error("Exception when registering ap routing {}", apId, e); - } - - } - - 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); - } + private static final Logger LOG = LoggerFactory.getLogger(OpensyncExternalIntegrationCloud.class); + + @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:2}") + 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; + // private Map opensyncNodeMap; + + // @Value("${connectus.ovsdb.configFileName:/Users/mikehansen/git/wlan-cloud-workspace/wlan-cloud-opensync-controller/opensync-ext-cloud/src/main/resources/config_2_ssids.json}") + // private String configFileName; + + @PostConstruct + private void postCreate() { + LOG.info("Using Cloud integration"); + cloudEquipmentRecordCache = cacheManagerShortLived.getCache("equipment_record_cache"); + // opensyncNodeMap = Collections.synchronizedMap(new HashMap()); + } + + 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.setCustomerId(autoProvisionedCustomerId); + ce.setEquipmentType(EquipmentType.AP); + ce.setInventoryId(apId); + ce.setLocationId(autoProvisionedLocationId); + + ce.setProfileId(autoProvisionedProfileId); + ce.setName(apId); + ce.setSerial(connectNodeInfo.serialNumber); + ce.setDetails(ApElementConfiguration.createWithDefaults()); + + ce = equipmentServiceInterface.create(ce); + // + // ce = new Equipment(); + // ce.setCustomerId(autoProvisionedCustomerId); + // ce.setInventoryId(apId); + // ce.setEquipmentType(EquipmentType.AP); + // ce.setName(apId); + // + // ce.setSerial(connectNodeInfo.serialNumber); + // ApElementConfiguration apElementConfig = + // ApElementConfiguration.createWithDefaults(); + // apElementConfig.setDeviceName(apId); + // ce.setDetails(apElementConfig); + // ce.setLocationId(autoProvisionedLocationId); + // ce.setProfileId(autoProvisionedProfileId); + + // ce = equipmentServiceInterface.create(ce); + } + + Profile apProfile = profileServiceInterface.getOrNull(ce.getProfileId()); + + if (apProfile == null || !apProfile.getProfileType().equals(ProfileType.equipment_ap)) { + apProfile = new Profile(); + apProfile.setCustomerId(ce.getCustomerId()); + apProfile.setName("autoprovisionedApProfile"); + apProfile.setDetails(ApNetworkConfiguration.createWithDefaults()); + apProfile = profileServiceInterface.create(apProfile); + + Profile ssidProfile = new Profile(); + ssidProfile.setCustomerId(ce.getCustomerId()); + ssidProfile.setName(autoProvisionedSsid); + SsidConfiguration ssidConfig = SsidConfiguration.createWithDefaults(); + Set appliedRadios = new HashSet<>(); + appliedRadios.addAll(((ApElementConfiguration) ce.getDetails()).getRadioMap().keySet()); + ssidConfig.setAppliedRadios(appliedRadios); + ssidProfile.setDetails(ssidConfig); + ssidProfile = profileServiceInterface.create(ssidProfile); + + Set childProfileIds = new HashSet<>(); + childProfileIds.add(ssidProfile.getId()); + + apProfile.setChildProfileIds(childProfileIds); + + apProfile = profileServiceInterface.update(apProfile); + + // update AP only if the apProfile was missing + 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); + } + + updateApStatus(ce, connectNodeInfo); + + EquipmentRoutingRecord equipmentRoutingRecord = gatewayController.registerCustomerEquipment(ce.getName(), + ce.getCustomerId(), ce.getId()); + + 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(), 0, + 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(), 0, + StatusDataType.NETWORK_AGGREGATE); + if (networkAggStatusRec == null) { + networkAggStatusRec = new Status(); + networkAggStatusRec.setCustomerId(ce.getCustomerId()); + NetworkAggregateStatusData naStatusData = new NetworkAggregateStatusData(); + networkAggStatusRec.setDetails(naStatusData); + } + + networkAggStatusRec.setEquipmentId(ce.getId()); + + statusServiceInterface.update(networkAggStatusRec); + + } + catch (Exception e) { + // do nothing + LOG.debug("Exception in updateApStatus", e); + } + + } + + @Override + public void apDisconnected(String apId) { + LOG.info("AP {} got disconnected from the gateway", apId); + try { + // removed the 'in-memory' cached node + // synchronized (opensyncNodeMap) { + // if (opensyncNodeMap.containsKey(apId)) { + // opensyncNodeMap.remove(apId); + // LOG.info("AP {} and table state data removed from memory cache", + // apId); + // } + // } + + 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); + + // CountryCode countryCode = Location.getCountryCode(eqLocation); + // if (countryCode != null && countryCode != + // CountryCode.UNSUPPORTED) { + // countryCode.toString().toUpperCase(); + // } + // + // ApElementConfiguration apElementConfiguration = + // (ApElementConfiguration) equipmentConfig.getDetails(); + + // Map erc = + // apElementConfiguration.getRadioMap(); + // if (erc != null) { + // + // ElementRadioConfiguration erc24 = erc.get(RadioType.is2dot4GHz); + // ElementRadioConfiguration erc5gl = erc.get(RadioType.is5GHzL); + // ElementRadioConfiguration erc5gh = erc.get(RadioType.is5GHzU); + // + // if (erc24 != null) { + // erc24.getChannelNumber(); + // } + // + // if (erc5gl != null) { + // erc5gl.getChannelNumber(); + // } + // + // if (erc5gh != null) { + // erc5gh.getChannelNumber(); + // } + // + // } + + com.telecominfraproject.wlan.profile.models.Profile apProfile = profileServiceInterface + .getOrNull(equipmentConfig.getProfileId()); + + ret.setApProfile(apProfile); + + if (apProfile != null) { + List ssidProfiles = new ArrayList<>(); + + Set childProfileIds = apProfile.getChildProfileIds(); + for (Long id : childProfileIds) { + com.telecominfraproject.wlan.profile.models.Profile profile = profileServiceInterface.get(id); + if (profile.getProfileType().equals(ProfileType.ssid)) { + + SsidConfiguration ssidConfig = ((SsidConfiguration) profile.getDetails()); + ssidConfig.setSsid(autoProvisionedSsid); + if (ssidConfig.getSecureMode().equals(SecureMode.open)) { + ssidConfig.setSecureMode(SecureMode.wpa2PSK); + ssidConfig.setKeyStr("12345678"); + } + profile.setDetails(ssidConfig); + profile = profileServiceInterface.update(profile); + + ssidProfiles.add(profile); + + } + } + ret.setSsidProfile(ssidProfiles); + + } + + LOG.debug("Config content : Equipment {}", ret.getCustomerEquipment()); + LOG.debug("Config content : APProfile {}", ret.getApProfile()); + ret.getSsidProfile().stream().forEach(ssid -> LOG.debug("Config content : SSIDProfile {}", ssid)); + LOG.debug("Config content : Location {}", ret.getEquipmentLocation()); + + } + catch (Exception e) { + LOG.error("Cannot read config for AP {}", apId, e); + } + + return ret; + } + + /** + * @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; + } + + String[] parts = topic.split("/"); + if (parts.length < 3) { + return null; + } + + // 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) { + + String apId = extractApIdFromTopic(topic); + if (apId == null) { + return -1; + } + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession != null) { + return ovsdbSession.getCustomerId(); + } + + return -1; + + } + + public long extractEquipmentIdFromTopic(String topic) { + + String apId = extractApIdFromTopic(topic); + if (apId == null) { + return -1; + } + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession != null) { + return ovsdbSession.getEquipmentId(); + } + + return -1; + + } + + @Override + public void processMqttMessage(String topic, Report report) { + LOG.info("Received report on topic {} for ap {}", topic, report.getNodeID()); + 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; + } + + List metricRecordList = new ArrayList<>(); + + populateApClientMetrics(metricRecordList, report, customerId, equipmentId); + populateApNodeMetrics(metricRecordList, report, customerId, equipmentId); + + try { + populateApSsidMetrics(metricRecordList, report, customerId, equipmentId, extractApIdFromTopic(topic)); + } + catch (Exception e) { + LOG.error("Exception when processing populateApSsidMetrics", e); + } + + if (!metricRecordList.isEmpty()) { + equipmentMetricsCollectorInterface.publishMetrics(metricRecordList); + } + + } + + private void populateApNodeMetrics(List metricRecordList, Report report, int customerId, + long equipmentId) { + { + LOG.debug("populateApNodeMetrics for Customer {} Equipment {}", customerId, equipmentId); + ApNodeMetrics apNodeMetrics = null; + + for (Device deviceReport : report.getDeviceList()) { + + ServiceMetric smr = new ServiceMetric(customerId, equipmentId); + metricRecordList.add(smr); + + apNodeMetrics = new ApNodeMetrics(); + smr.setDetails(apNodeMetrics); + 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()); + } + if (apNodeMetrics != null) { + + // 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 + long rxBytes2g = 0; + long txBytes2g = 0; + + long rxBytes5g = 0; + long txBytes5g = 0; + + for (ClientReport clReport : report.getClientsList()) { + for (Client cl : clReport.getClientListList()) { + if (clReport.getBand() == RadioBandType.BAND2G) { + if (cl.getStats().hasTxBytes()) { + txBytes2g += cl.getStats().getTxBytes(); + } + if (cl.getStats().hasRxBytes()) { + rxBytes2g += cl.getStats().getRxBytes(); + } + } + else { + if (cl.getStats().hasTxBytes()) { + txBytes5g += cl.getStats().getTxBytes(); + } + if (cl.getStats().hasRxBytes()) { + rxBytes5g += cl.getStats().getRxBytes(); + } + } + } + } + + apNodeMetrics.setRxBytes(RadioType.is2dot4GHz, rxBytes2g); + apNodeMetrics.setTxBytes(RadioType.is2dot4GHz, txBytes2g); + apNodeMetrics.setRxBytes(RadioType.is5GHz, rxBytes5g); + apNodeMetrics.setTxBytes(RadioType.is5GHz, txBytes5g); + 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; + + // TODO: temporary solution as this was causing Noise Floor to + // disappear from Dashboard and Access Point rows + apNodeMetrics.setNoiseFloor(RadioType.is2dot4GHz, -98); + apNodeMetrics.setNoiseFloor(RadioType.is5GHz, -98); + + apNodeMetrics.setRadioUtilization(RadioType.is2dot4GHz, new ArrayList<>()); + apNodeMetrics.setRadioUtilization(RadioType.is5GHz, new ArrayList<>()); + + // populate it from report.survey + for (Survey survey : report.getSurveyList()) { + // 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()); + if (survey.getBand() == RadioBandType.BAND2G) { + apNodeMetrics.getRadioUtilization(RadioType.is2dot4GHz).add(radioUtil); + } + else { + apNodeMetrics.getRadioUtilization(RadioType.is5GHz).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()); + // } + } + + } + LOG.debug("ApNodeMetrics Report {}", apNodeMetrics); + + } + + } + + private void populateApClientMetrics(List metricRecordList, Report report, int customerId, + long equipmentId) { + LOG.debug("populateApClientMetrics for Customer {} Equipment {}", customerId, equipmentId); + + for (ClientReport clReport : report.getClientsList()) { + + 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; + } + + 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()) { + cMetrics.setRssi(cl.getStats().getRssi()); + } + + // 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().getRxRate()); + } + + 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(cl.getStats().getTxRate()); + } + + if (cl.getStats().hasTxRate() && cl.getStats().hasRxRate()) { + cMetrics.setRates( + new byte[] { (byte) cl.getStats().getTxRate(), (byte) cl.getStats().getRxRate() }); + } - Equipment equipmentConfig = getCustomerEquipment(apId); + if (cl.getStats().hasTxErrors()) { + cMetrics.setNumTxDropped((int) cl.getStats().getTxErrors()); + } - if (equipmentConfig == null) { - throw new IllegalStateException("Cannot retrieve configuration for " + apId); - } + if (cl.getStats().hasRxFrames()) { + // cMetrics.setNumTxFramesTransmitted(cl.getStats().getTxFrames()); + cMetrics.setNumTxPackets(cl.getStats().getRxFrames()); + } - ret = new OpensyncAPConfig(); + if (cl.getStats().hasTxRetries()) { + cMetrics.setNumTxDataRetries((int) cl.getStats().getTxRetries()); + } - ret.setCustomerEquipment(equipmentConfig); + } - Location eqLocation = locationServiceInterface.get(equipmentConfig.getLocationId()); + LOG.debug("APClientMetrics Report {}", cMetrics); - ret.setEquipmentLocation(eqLocation); + } + + } - // extract country, radio channels from resolvedEqCfg - String country = "CA"; - CountryCode countryCode = Location.getCountryCode(eqLocation); - if (countryCode != null && countryCode != CountryCode.UNSUPPORTED) { - country = countryCode.toString().toUpperCase(); - } + } - int radioChannel24G = 1; - int radioChannel5LG = 44; - int radioChannel5HG = 149; + private void populateApSsidMetrics(List metricRecordList, Report report, int customerId, + long equipmentId, String apId) { - ApElementConfiguration apElementConfiguration = (ApElementConfiguration) equipmentConfig.getDetails(); + if (report.getClientsCount() == 0) { + LOG.debug("No clients reported, will not populate ApSsidMetrics report"); + return; + } + else { + LOG.debug("populateApSsidMetrics for Customer {} Equipment {} AP {}", customerId, equipmentId, apId); + } - Map erc = apElementConfiguration.getRadioMap(); - if (erc != null) { + // TODO: implement, using information from status and config to + // populate/correlate AP data with the Client SSID data + + } + + @Override + public void processMqttMessage(String topic, FlowReport flowReport) { + + LOG.info("Received report on topic {}", topic); + int customerId = extractCustomerIdFromTopic(topic); - ElementRadioConfiguration erc24 = erc.get(RadioType.is2dot4GHz); - ElementRadioConfiguration erc5gl = erc.get(RadioType.is5GHzL); - ElementRadioConfiguration erc5gh = erc.get(RadioType.is5GHzU); + long equipmentId = extractEquipmentIdFromTopic(topic); + if (equipmentId <= 0 || customerId <= 0) { + LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, + equipmentId); + return; + } - if (erc24 != null) { - radioChannel24G = erc24.getChannelNumber(); - } + String apId = extractApIdFromTopic(topic); - if (erc5gl != null) { - radioChannel5LG = erc5gl.getChannelNumber(); - } + if (apId == null) { + LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, + equipmentId, apId); + return; + } - if (erc5gh != null) { - radioChannel5HG = erc5gh.getChannelNumber(); - } + } - } + @Override + public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { + LOG.debug("Received WCStatsReport {}", wcStatsReport.toString()); - com.telecominfraproject.wlan.profile.models.Profile apProfile = profileServiceInterface - .getOrNull(equipmentConfig.getProfileId()); + LOG.info("Received report on topic {}", topic); + int customerId = extractCustomerIdFromTopic(topic); - ret.setApProfile(apProfile); + long equipmentId = extractEquipmentIdFromTopic(topic); + if (equipmentId <= 0 || customerId <= 0) { + LOG.warn("Cannot determine equipment ids from topic {} - customerId {} equipmentId {}", topic, customerId, + equipmentId); + return; + } - if (apProfile != null) { - List ssidProfiles = new ArrayList(); + String apId = extractApIdFromTopic(topic); - Set childProfileIds = apProfile.getChildProfileIds(); - for (Long id : childProfileIds) { - com.telecominfraproject.wlan.profile.models.Profile profile = profileServiceInterface.get(id); - if (profile.getProfileType().equals(ProfileType.ssid)) { + if (apId == null) { + LOG.warn("Cannot determine AP id from topic {} - customerId {} equipmentId {} apId {}", topic, customerId, + equipmentId, apId); + return; + } - SsidConfiguration ssidCfg = (SsidConfiguration) profile.getDetails(); - ssidCfg.setSsid(profile.getName()); + } - for (RadioType radioType : ssidCfg.getAppliedRadios()) { - if (ssidCfg.getSecureMode() == SecureMode.wpa2OnlyPSK - || ssidCfg.getSecureMode() == SecureMode.wpa2PSK) { + @Override + public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { - ssidCfg.setSecureMode(SecureMode.wpa2PSK); - } else if (ssidCfg.getSecureMode() == SecureMode.wpaPSK) { + Equipment ce = getCustomerEquipment(apId); + if (ce == null) { + LOG.debug("wifiVIFStateDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - ssidCfg.setSecureMode(SecureMode.wpaPSK); + long equipmentId = ce.getId(); - } else { - LOG.warn("Unsupported encryption mode {} - will use WPA-PSK instead", - ssidCfg.getSecureMode()); + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } - ssidCfg.setSecureMode(SecureMode.wpa2PSK); - } + if (vifStateTables == null || vifStateTables.isEmpty() || apId == null) { + return; + } - if (ssidCfg.getKeyStr() == null) { - ssidCfg.setKeyStr("12345678"); - } + // TODO: update Equipment and Profiles related to VIF_State table update - } - profile.setDetails(ssidCfg); - ssidProfiles.add(profile); + } - } - } - ret.setSsidProfile(ssidProfiles); + @Override + public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { - ret.getSsidProfile().stream().forEach(p -> LOG.debug("SSID Profile {}", p.toPrettyString())); + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - } + if (ovsdbSession == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } - } catch (Exception e) { - LOG.error("Cannot read config for AP {}", apId, e); - } + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiRadioStatusDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } - LOG.debug("Config content : Equipment {}", ret.getCustomerEquipment().toPrettyString()); - LOG.debug("Config content : APProfile {}", ret.getApProfile().toPrettyString()); + for (OpensyncAPRadioState radioState : radioStateTables) { - ret.getSsidProfile().stream() - .forEach(ssid -> LOG.debug("Config content : SSIDProfile {}", ssid.toPrettyString())); - LOG.debug("Config content : Location {}", ret.getEquipmentLocation().toPrettyString()); + if (radioState.getFreqBand().equals(RadioType.UNSUPPORTED)) { + LOG.debug("Could not get radio configuration for AP {}", apId); + continue; + } - return ret; - } + if (radioState.getAllowedChannels() != null && !radioState.getAllowedChannels().isEmpty()) { + ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setAllowedChannels(new ArrayList<>(radioState.getAllowedChannels())); + ce.setDetails(apElementConfiguration); + ce = equipmentServiceInterface.update(ce); + LOG.debug("Updated AllowedChannels from Wifi_Radio_State table change {}", ce); - /** - * @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; - } + } - String[] parts = topic.split("/"); - if (parts.length < 3) { - return null; - } + if (radioState.getTxPower() > 0) { + ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + apElementConfiguration.getRadioMap().get(radioState.getFreqBand()) + .setEirpTxPower(AutoOrManualValue.createManualInstance(radioState.getTxPower())); + ce.setDetails(apElementConfiguration); + ce = equipmentServiceInterface.update(ce); + LOG.debug("Updated TxPower from Wifi_Radio_State table change {}", ce); - // 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) { + StateSetting state = StateSetting.disabled; + if (radioState.isEnabled()) { + state = StateSetting.enabled; + } + ApElementConfiguration apElementConfiguration = ((ApElementConfiguration) ce.getDetails()); + if (!apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).getRadioAdminState() + .equals(state)) { + // only update if changed + apElementConfiguration.getAdvancedRadioMap().get(radioState.getFreqBand()).setRadioAdminState(state); + ce.setDetails(apElementConfiguration); + ce = equipmentServiceInterface.update(ce); - String apId = extractApIdFromTopic(topic); - if (apId == null) { - return -1; - } + LOG.debug("Updated RadioAdminState from Wifi_Radio_State table change {}", ce); - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + } - if (ovsdbSession != null) { - return ovsdbSession.getCustomerId(); - } + } - return -1; + } - } + @Override + public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - public long extractEquipmentIdFromTopic(String topic) { - - String apId = extractApIdFromTopic(topic); - if (apId == null) { - return -1; - } - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - - if (ovsdbSession != null) { - return ovsdbSession.getEquipmentId(); - } - - return -1; - - } - - public void processMqttMessage(String topic, Report report) { - LOG.info("Received report on topic {} for ap {}", topic, report.getNodeID()); - 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; - } - - List metricRecordList = new ArrayList<>(); - - populateApClientMetrics(metricRecordList, report, customerId, equipmentId); - populateApNodeMetrics(metricRecordList, report, customerId, equipmentId); - // TODO: populateApNodeMetrics(metricRecordList, report, customerId, - // equipmentId, extractApIdFromTopic(topic)); - - try { - populateApSsidMetrics(metricRecordList, report, customerId, equipmentId, extractApIdFromTopic(topic)); - } catch (Exception e) { - LOG.error("Exception when processing populateApSsidMetrics", e); - } - - if (!metricRecordList.isEmpty()) { - equipmentMetricsCollectorInterface.publishMetrics(metricRecordList); - } - - } - - private void populateApNodeMetrics(List metricRecordList, Report report, int customerId, - long equipmentId) { - { - LOG.debug("populateApNodeMetrics for Customer {} Equipment {}", customerId, equipmentId); - ApNodeMetrics apNodeMetrics = null; - - for (Device deviceReport : report.getDeviceList()) { - - ServiceMetric smr = new ServiceMetric(customerId, equipmentId); - metricRecordList.add(smr); - - apNodeMetrics = new ApNodeMetrics(); - smr.setDetails(apNodeMetrics); - 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()); - } - if (apNodeMetrics != null) { - - // 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 - long rxBytes2g = 0; - long txBytes2g = 0; - - long rxBytes5g = 0; - long txBytes5g = 0; - - for (ClientReport clReport : report.getClientsList()) { - for (Client cl : clReport.getClientListList()) { - if (clReport.getBand() == RadioBandType.BAND2G) { - if (cl.getStats().hasTxBytes()) { - txBytes2g += cl.getStats().getTxBytes(); - } - if (cl.getStats().hasRxBytes()) { - rxBytes2g += cl.getStats().getRxBytes(); - } - } else { - if (cl.getStats().hasTxBytes()) { - txBytes5g += cl.getStats().getTxBytes(); - } - if (cl.getStats().hasRxBytes()) { - rxBytes5g += cl.getStats().getRxBytes(); - } - } - } - } - - apNodeMetrics.setRxBytes(RadioType.is2dot4GHz, rxBytes2g); - apNodeMetrics.setTxBytes(RadioType.is2dot4GHz, txBytes2g); - apNodeMetrics.setRxBytes(RadioType.is5GHz, rxBytes5g); - apNodeMetrics.setTxBytes(RadioType.is5GHz, txBytes5g); - 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; - - // TODO: temporary solution as this was causing Noise Floor to - // disappear from Dashboard and Access Point rows - apNodeMetrics.setNoiseFloor(RadioType.is2dot4GHz, Integer.valueOf(-98)); - apNodeMetrics.setNoiseFloor(RadioType.is5GHz, Integer.valueOf(-98)); - - apNodeMetrics.setRadioUtilization(RadioType.is2dot4GHz, new ArrayList<>()); - apNodeMetrics.setRadioUtilization(RadioType.is5GHz, new ArrayList<>()); - - // populate it from report.survey - for (Survey survey : report.getSurveyList()) { - // 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()); - if (survey.getBand() == RadioBandType.BAND2G) { - apNodeMetrics.getRadioUtilization(RadioType.is2dot4GHz).add(radioUtil); - } else { - apNodeMetrics.getRadioUtilization(RadioType.is5GHz).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()); - // } - } - - } - LOG.debug("ApNodeMetrics Report {}", apNodeMetrics.toPrettyString()); - - } - - } - - private void populateApClientMetrics(List metricRecordList, Report report, int customerId, - long equipmentId) { - LOG.debug("populateApClientMetrics for Customer {} Equipment {}", customerId, equipmentId); - - for (ClientReport clReport : report.getClientsList()) { - - 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; - } - - 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()) { - cMetrics.setRssi(cl.getStats().getRssi()); - } - - // 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().getRxRate()); - } - - 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(cl.getStats().getTxRate()); - } - - if (cl.getStats().hasTxRate() && cl.getStats().hasRxRate()) { - cMetrics.setRates( - new byte[] { (byte) (cl.getStats().getTxRate()), (byte) (cl.getStats().getRxRate()) }); - } - - if (cl.getStats().hasTxErrors()) { - cMetrics.setNumTxDropped((int) cl.getStats().getTxErrors()); - } - - if (cl.getStats().hasRxFrames()) { - // cMetrics.setNumTxFramesTransmitted(cl.getStats().getTxFrames()); - cMetrics.setNumTxPackets(cl.getStats().getRxFrames()); - } - - if (cl.getStats().hasTxRetries()) { - cMetrics.setNumTxDataRetries((int) cl.getStats().getTxRetries()); - } - - } - - LOG.debug("APClientMetrics Report {}", cMetrics.toPrettyString()); - - } - - } - - } - - private void populateApSsidMetrics(List metricRecordList, Report report, int customerId, - long equipmentId, String apId) { - - if (report.getClientsCount() == 0) { - LOG.debug("No clients reported, will not populate ApSsidMetrics report"); - return; - } else { - LOG.debug("populateApSsidMetrics for Customer {} Equipment {} AP {}", customerId, equipmentId, apId); - } - - // Need Radios to get BSSID value - OpensyncAPRadioState radio2g = null; - OpensyncAPRadioState radio5GHz = null; - OpensyncAPRadioState radio5GHzL = null; - OpensyncAPRadioState radio5GHzU = null; - - OpensyncAPVIFState vif2g = null; - OpensyncAPVIFState vif5GHz = null; - OpensyncAPVIFState vif5GHzL = null; - OpensyncAPVIFState vif5GHzU = null; - - synchronized (opensyncNodeMap) { - OpensyncNode node = opensyncNodeMap.get(apId); - if (node == null) { - LOG.debug("No AP Data present for AP SSID report"); - return; - } - radio2g = node.getRadioForBand(RadioType.is2dot4GHz.toString()); - radio5GHz = node.getRadioForBand(RadioType.is5GHz.toString()); - radio5GHzL = node.getRadioForBand(RadioType.is5GHzL.toString()); - radio5GHzU = node.getRadioForBand(RadioType.is5GHzU.toString()); - - if (radio2g == null && radio5GHzL == null && radio5GHzU == null && radio5GHz == null) { - LOG.debug("No Radio Data present for AP SSID report"); - return; - } - - if (radio2g != null) - vif2g = node.getVIFForChannel(radio2g.getChannel()); - if (radio5GHz != null) - vif5GHz = node.getVIFForChannel(radio5GHz.getChannel()); - if (radio5GHzL != null) - vif5GHzL = node.getVIFForChannel(radio5GHzL.getChannel()); - if (radio5GHzU != null) - vif5GHzU = node.getVIFForChannel(radio5GHzU.getChannel()); - - if (vif2g == null && vif5GHzL == null && vif5GHzU == null && vif5GHz == null) { - LOG.debug("No Wifi SSID Data present for AP SSID report"); - return; - } - } - - ServiceMetric smr = new ServiceMetric(customerId, equipmentId); - ApSsidMetrics apSsidMetrics = new ApSsidMetrics(); - List ssidStatsList2pt4GHz = new ArrayList<>(); - List ssidStatsList5GHzL = new ArrayList<>(); - List ssidStatsList5GHzU = new ArrayList<>(); - List ssidStatsList5GHz = new ArrayList<>(); - - if (vif2g != null) - apSsidMetrics.getSsidStats().put(RadioType.is2dot4GHz, ssidStatsList2pt4GHz); - if (vif5GHz != null) - apSsidMetrics.getSsidStats().put(RadioType.is5GHz, ssidStatsList5GHz); - if (vif5GHzL != null) - apSsidMetrics.getSsidStats().put(RadioType.is5GHzL, ssidStatsList5GHzL); - if (vif5GHzU != null) - apSsidMetrics.getSsidStats().put(RadioType.is5GHzU, ssidStatsList5GHzU); - - smr.setDetails(apSsidMetrics); - metricRecordList.add(smr); - - for (ClientReport clientReport : report.getClientsList()) { - - // Always report the AP radio for that SSID if we are sending a - // report - // The '0' values will be overwritten, if applicable, from the - // aggregated client information - // TODO: security/encryption disabled until client session updates re-enabled -// String encryption = null; - SsidStatistics ssidStat = new SsidStatistics(); - -// SecurityType securityType = SecurityType.UNSUPPORTED; -// if (encryption != null) { -// if (encryption.endsWith("PSK")) { -// securityType = SecurityType.PSK; -// } else if (encryption.equals("RADIUS")) { -// securityType = SecurityType.RADIUS; -// } else if (encryption.equals("OPEN")) { -// securityType = SecurityType.OPEN; -// } -// } - - long txBytes = 0L; - long rxBytes = 0L; - int txErrors = 0; - int rxRetries = 0; - int lastRssi = 0; - - for (Client client : clientReport.getClientListList()) { - - if (client.hasSsid() && client.hasStats()) { - - txBytes += client.getStats().getTxBytes(); - rxBytes += client.getStats().getRxBytes(); - txErrors += client.getStats().getTxErrors(); - rxRetries += client.getStats().getRxRetries(); - lastRssi = client.getStats().getRssi(); - // TODO: Disabled, enable when AP starts to send MAC/BSSID -// try { -// handleClientSessionUpdate(customerId, equipmentId, apId, clientReport.getChannel(), -// clientReport.getBand(), clientReport.getTimestampMs(), client, securityType); -// } catch (Exception e) { -// LOG.debug("Unabled to update client {} session {}", client, e); -// } - } - - } - - ssidStat.setRxLastRssi(-1 * lastRssi); - ssidStat.setRxBytes(rxBytes); - ssidStat.setNumTxBytesSucc(txBytes - txErrors); - ssidStat.setNumRxRetry(rxRetries); - - // TODO: disable BSSID/MAC setting until reported by radio - if (clientReport.getBand() == RadioBandType.BAND2G) { - if (radio2g != null && vif2g != null) { -// ssidStat.setBssid(new MacAddress(radio2g.getMac())); - ssidStat.setSsid(vif2g.getSsid()); - ssidStat.setNumClient(vif2g.getAssociatedClients().size()); -// encryption = vif2g.getSecurity().get("encryption"); - } - ssidStatsList2pt4GHz.add(ssidStat); - } else if (clientReport.getBand() == RadioBandType.BAND5G) { - if (radio5GHz != null && vif5GHz != null) { -// ssidStat.setBssid(new MacAddress(radio5GHz.getMac())); - ssidStat.setSsid(vif5GHz.getSsid()); - ssidStat.setNumClient(vif5GHz.getAssociatedClients().size()); -// encryption = vif5GHz.getSecurity().get("encryption"); - } - ssidStatsList5GHz.add(ssidStat); - } else if (clientReport.getBand() == RadioBandType.BAND5GL) { - if (radio5GHzL != null && vif5GHzL != null) { -// ssidStat.setBssid(new MacAddress(radio5GHzL.getMac())); - ssidStat.setSsid(vif5GHzL.getSsid()); - ssidStat.setNumClient(vif5GHzL.getAssociatedClients().size()); -// encryption = vif5GHzL.getSecurity().get("encryption"); - } - ssidStatsList5GHzL.add(ssidStat); - } else if (clientReport.getBand() == RadioBandType.BAND5GU) { - if (radio5GHzU != null && vif5GHzU != null) { -// ssidStat.setBssid(new MacAddress(radio5GHzU.getMac())); - ssidStat.setSsid(vif5GHzU.getSsid()); - ssidStat.setNumClient(vif5GHzU.getAssociatedClients().size()); -// encryption = vif5GHzU.getSecurity().get("encryption"); - } - ssidStatsList5GHzU.add(ssidStat); - - } - - } - - if (apSsidMetrics.getSsidStatsCount(RadioType.is2dot4GHz) == 0 && vif2g != null) { - SsidStatistics ssidStat = new SsidStatistics(); - if (radio2g.getMac() != null) - ssidStat.setBssid(new MacAddress(radio2g.getMac())); - ssidStat.setSsid(vif2g.getSsid()); - ssidStat.setNumClient(vif2g.getAssociatedClients().size()); - ssidStatsList2pt4GHz.add(ssidStat); - - } - if (apSsidMetrics.getSsidStatsCount(RadioType.is5GHz) == 0 && vif5GHz != null) { - SsidStatistics ssidStat = new SsidStatistics(); - if (radio5GHz.getMac() != null) - ssidStat.setBssid(new MacAddress(radio5GHz.getMac())); - ssidStat.setSsid(vif5GHz.getSsid()); - ssidStat.setNumClient(vif5GHz.getAssociatedClients().size()); - ssidStatsList5GHzL.add(ssidStat); - } - if (apSsidMetrics.getSsidStatsCount(RadioType.is5GHzL) == 0 && vif5GHzL != null) { - SsidStatistics ssidStat = new SsidStatistics(); - if (radio5GHzL.getMac() != null) - ssidStat.setBssid(new MacAddress(radio5GHzL.getMac())); - ssidStat.setSsid(vif5GHzL.getSsid()); - ssidStat.setNumClient(vif5GHzL.getAssociatedClients().size()); - ssidStatsList5GHzL.add(ssidStat); - } - if (apSsidMetrics.getSsidStatsCount(RadioType.is5GHzU) == 0 && vif5GHzU != null) { - SsidStatistics ssidStat = new SsidStatistics(); - if (radio5GHzU.getMac() != null) - ssidStat.setBssid(new MacAddress(radio5GHzU.getMac())); - ssidStat.setSsid(vif5GHzU.getSsid()); - ssidStat.setNumClient(vif5GHzU.getAssociatedClients().size()); - ssidStatsList5GHzU.add(ssidStat); - } - - LOG.debug("Created ApSsidMetrics Report {}", apSsidMetrics.toPrettyString()); - - } - - private void handleClientSessionUpdate(int customerId, long equipmentId, String apId, int channel, - RadioBandType band, long timestamp, Client client, SecurityType securityType) { - - boolean found = false; - List clientRecords = clientServiceInterface.get(customerId, - Collections.singleton(new MacAddress(client.getMacAddress()))); - if (!clientRecords.isEmpty()) { - com.telecominfraproject.wlan.client.models.Client record = clientRecords.get(0); - LOG.debug("Found Client {}", record.toPrettyString()); - found = true; - } - - if (!found) { - com.telecominfraproject.wlan.client.models.Client clientRecord = new com.telecominfraproject.wlan.client.models.Client(); - clientRecord.setCustomerId(customerId); - clientRecord.setMacAddress(new MacAddress(client.getMacAddress())); - clientRecord.setCreatedTimestamp(timestamp); - - ClientInfoDetails cid = new ClientInfoDetails(); - cid.setHostName(clientRecord.getMacAddress().getAddressAsString()); - cid.setApFingerprint(apId); - clientRecord.setDetails(cid); - - try { - LOG.debug("Created Client {}", clientServiceInterface.create(clientRecord).toPrettyString()); - } catch (Exception e) { - LOG.error("Unabled to create client for {}", client.getMacAddress(), e); - } - } - - try { - - ClientSession clientSession = clientServiceInterface.getSessionOrNull(customerId, equipmentId, - new MacAddress(client.getMacAddress())); - if (clientSession == null) { - LOG.debug("No session found for Client {}, creating new one.", client.getMacAddress()); - clientSession = new ClientSession(); - clientSession.setMacAddress(new MacAddress(client.getMacAddress())); - clientSession.setCustomerId(customerId); - clientSession.setEquipmentId(equipmentId); - ClientSessionDetails clientSessionDetails = new ClientSessionDetails(); - clientSession.setDetails(clientSessionDetails); - - RadioType radioType = RadioType.UNSUPPORTED; - switch (band) { - case BAND2G: - radioType = RadioType.is2dot4GHz; - break; - case BAND5G: - radioType = RadioType.is5GHz; - break; - case BAND5GL: - radioType = RadioType.is5GHzL; - break; - case BAND5GU: - radioType = RadioType.is5GHzU; - break; - } - clientSessionDetails.setRadioType(radioType); - clientSessionDetails.setSessionId(clientSession.getMacAddress().getAddressAsLong()); - clientSessionDetails.setSsid(client.getSsid()); - clientSessionDetails.setAssociationStatus(0); - clientSessionDetails.setAssocTimestamp(timestamp - client.getConnectOffsetMs()); - clientSessionDetails.setAuthTimestamp(timestamp - client.getConnectOffsetMs()); - clientSessionDetails.setFirstDataRcvdTimestamp(timestamp); - clientSessionDetails.setFirstDataSentTimestamp(timestamp); - clientSessionDetails.setLastRxTimestamp(timestamp); - clientSessionDetails.setHostname(clientSession.getMacAddress().toOuiString()); - clientSessionDetails.setSessionId(clientSession.getMacAddress().getAddressAsLong()); - clientSessionDetails.setSecurityType(securityType); - ClientDhcpDetails dhcpDetails = new ClientDhcpDetails(clientSessionDetails.getSessionId()); - clientSessionDetails.setDhcpDetails(dhcpDetails); - ClientSessionMetricDetails metricDetails = new ClientSessionMetricDetails(); - metricDetails.setRssi(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())); - metricDetails.setRxMbps((float) client.getStats().getRxRate()); - metricDetails.setTxMbps((float) client.getStats().getTxRate()); - clientSessionDetails.setMetricDetails(metricDetails); - } else { - ClientSessionDetails clientSessionDetails = clientSession.getDetails(); - clientSessionDetails.setAssociationStatus(0); - if (clientSessionDetails.getDhcpDetails() == null) { - ClientDhcpDetails dhcpDetails = new ClientDhcpDetails(clientSessionDetails.getSessionId()); - clientSessionDetails.setDhcpDetails(dhcpDetails); - } - - clientSessionDetails.setSecurityType(securityType); - clientSessionDetails.setAssocTimestamp(timestamp - client.getConnectOffsetMs()); - clientSessionDetails.setAuthTimestamp(timestamp - client.getConnectOffsetMs()); - clientSessionDetails.setFirstDataRcvdTimestamp(timestamp); - clientSessionDetails.setFirstDataSentTimestamp(timestamp); - clientSessionDetails.setLastRxTimestamp(timestamp); - clientSessionDetails.setIsReassociation(true); - clientSession.setCustomerId(customerId); - clientSession.setEquipmentId(equipmentId); - clientSessionDetails.setSessionId(clientSession.getMacAddress().getAddressAsLong()); - ClientSessionMetricDetails metricDetails = clientSessionDetails.getMetricDetails(); - - if (client.hasStats()) { - if (metricDetails == null) { - - LOG.debug("No metric details for client {} session {}, creating", clientSession.getMacAddress(), - clientSessionDetails.getSessionId()); - metricDetails = new ClientSessionMetricDetails(); - } - metricDetails.setRssi(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())); - metricDetails.setRxMbps((float) client.getStats().getRxRate()); - metricDetails.setTxMbps((float) client.getStats().getTxRate()); - - metricDetails.setLastRxTimestamp(timestamp); - metricDetails.setLastTxTimestamp(timestamp); - - } - clientSessionDetails.setMetricDetails(metricDetails); - LOG.debug("Association State {}", clientSessionDetails.getAssociationState()); - - } - - // TODO: We support bulk updates for sessions, which is more efficient way of - // updating many sessions at once. - // Need to rewrite this to make use of bulk operation. - ClientSession session = clientServiceInterface.updateSession(clientSession); - - if (session != null) - LOG.debug("CreatedOrUpdated clientSession {}", session.toPrettyString()); - - } catch (Exception e) { - LOG.error("Error while attempting to create ClientSession and Info", e); - } - } - - 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; - } - - } - - public void processMqttMessage(String topic, WCStatsReport wcStatsReport) { - LOG.debug("Received WCStatsReport {}", wcStatsReport.toString()); - - 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; - } - - } - - @Override - public void wifiVIFStateDbTableUpdate(List vifStateTables, String apId) { - if (vifStateTables == null || vifStateTables.isEmpty() || apId == null) - return; - - Equipment ce = getCustomerEquipment(apId); - if (ce == null) { - LOG.debug("Cannot get equipmentId {} for apId {}", apId); - return; - } - - int customerId = ce.getCustomerId(); - long equipmentId = ce.getId(); - - OpensyncNode osNode = null; - - synchronized (opensyncNodeMap) { - - if (opensyncNodeMap.containsKey(apId)) { - - Status activeBssids = statusServiceInterface.getOrNull(customerId, equipmentId, - StatusDataType.ACTIVE_BSSIDS); - if (activeBssids == null) { - activeBssids = new Status(); - activeBssids.setCustomerId(customerId); - activeBssids.setEquipmentId(equipmentId); - activeBssids.setStatusDataType(StatusDataType.ACTIVE_BSSIDS); - activeBssids.setDetails(new ActiveBSSIDs()); - statusServiceInterface.update(activeBssids); - } - ActiveBSSIDs bssids = (ActiveBSSIDs) activeBssids.getDetails(); - List bssidList = bssids.getActiveBSSIDs(); - - osNode = opensyncNodeMap.get(apId); - for (OpensyncAPVIFState vifState : vifStateTables) { - if (vifState.isEnabled()) { - osNode.updateVifState(vifState); - String ssid = vifState.getSsid(); // ssid - if (ssid != null) { - int channel = vifState.getChannel(); // channel for this ssid - int numDevicesConnected = vifState.getAssociatedClients().size(); - if (channel > 0) { - OpensyncAPRadioState radioState = osNode.getRadioForChannel(channel); - if (radioState != null) { - String bssidAsMacString = radioState.getMac(); - RadioType radioType = null; - if (osNode.getRadioForChannel(channel).getFreqBand().equals("2.4G")) - radioType = RadioType.is2dot4GHz; - else if (osNode.getRadioForChannel(channel).getFreqBand().equals("5GL")) - radioType = RadioType.is5GHzL; - else if (osNode.getRadioForChannel(channel).getFreqBand().equals("5GU")) - radioType = RadioType.is5GHzU; - else if (osNode.getRadioForChannel(channel).getFreqBand().equals("5G")) - radioType = RadioType.is5GHz; - - if (bssidAsMacString != null && bssidAsMacString != "" && radioType != null) { - - boolean found = false; - for (ActiveBSSID activeBssid : bssidList) { - if (activeBssid.getBssid().equals(bssidAsMacString) - && activeBssid.getRadioType().equals(radioType)) { - found = true; - } - } - if (!found) { - ActiveBSSID newBssid = new ActiveBSSID(); - newBssid.setBssid(bssidAsMacString); - newBssid.setSsid(ssid); - newBssid.setRadioType(radioType); - newBssid.setNumDevicesConnected(numDevicesConnected); - bssidList.add(newBssid); - bssids.setActiveBSSIDs(bssidList); - activeBssids.setDetails(bssids); - statusServiceInterface.update(activeBssids); - - } - } - } - } - } - } - } - opensyncNodeMap.put(apId, osNode); - // LOG.debug("Updated VIF States for AP to NodeMap {}", - // opensyncNodeMap.get(apId).toPrettyString()); - } else { - - // Do not add Status updates here as this is the only object in this map, and - // therefore it will not contain the required peer entities to do the status - // updates. These will be handled in subsequent table status updates. - - osNode = new OpensyncNode(apId, null, customerId, equipmentId); - for (OpensyncAPVIFState vifState : vifStateTables) { - if (vifState.isEnabled()) - osNode.updateVifState(vifState); - } - opensyncNodeMap.put(apId, osNode); - } - - osNode = opensyncNodeMap.get(apId); - - } - - } - - @Override - public void wifiRadioStatusDbTableUpdate(List radioStateTables, String apId) { - - if (radioStateTables == null || radioStateTables.isEmpty() || apId == null) - return; - - Equipment ce = getCustomerEquipment(apId); - - if (ce == null) { - LOG.debug("No equipment present for {}", apId); - return; - } - - for (OpensyncAPRadioState radioState : radioStateTables) { - - ApElementConfiguration apElementConfig = ((ApElementConfiguration) ce.getDetails()); - - ElementRadioConfiguration elementRadioConfiguration = null; - RadioType radioType = RadioType.UNSUPPORTED; - switch (radioState.getFreqBand()) { - case "2.4G": - elementRadioConfiguration = apElementConfig.getRadioMap().get(RadioType.is2dot4GHz); - radioType = RadioType.is2dot4GHz; - break; - case "5G": - elementRadioConfiguration = apElementConfig.getRadioMap().get(RadioType.is5GHz); - radioType = RadioType.is5GHz; - - break; - case "5GL": - elementRadioConfiguration = apElementConfig.getRadioMap().get(RadioType.is5GHzL); - radioType = RadioType.is5GHzL; - - break; - case "5GU": - elementRadioConfiguration = apElementConfig.getRadioMap().get(RadioType.is5GHzU); - radioType = RadioType.is5GHzU; - break; - default: - break; - } - - if (radioType.equals(RadioType.UNSUPPORTED)) { - LOG.debug("Could not get radio configuration for AP {}", apId); - return; - } -//TODO: once the AP is sending us actual allowed channels, we can remove the empty check as it may be valid - if (radioState.getAllowedChannels() != null && !radioState.getAllowedChannels().isEmpty()) { - elementRadioConfiguration.setAllowedChannels(new ArrayList(radioState.getAllowedChannels())); - apElementConfig.getRadioMap().put(radioType, elementRadioConfiguration); - ce.setDetails(apElementConfig); - ce = equipmentServiceInterface.update(ce); - apElementConfig = ((ApElementConfiguration) ce.getDetails()); - LOG.debug("Updated Allowed Channels for Radio {} to {}", radioState.getFreqBand(), - apElementConfig.getRadioMap().get(radioType).getAllowedChannels()); - } - - } - - } - - @Override - public void wifiInetStateDbTableUpdate(List inetStateTables, String apId) { - OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); - int customerId = session.getCustomerId(); - long equipmentId = session.getEquipmentId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - if (inetStateTables == null || inetStateTables.isEmpty() || apId == null) - return; - - // add to Inet States Map - OpensyncNode osNode = null; - synchronized (opensyncNodeMap) { - if (opensyncNodeMap.containsKey(apId)) { - osNode = opensyncNodeMap.get(apId); - for (OpensyncAPInetState inetState : inetStateTables) { - if (inetState.isEnabled()) - osNode.updateInetState(inetState); - } - opensyncNodeMap.put(apId, osNode); - } else { - osNode = new OpensyncNode(apId, null, customerId, equipmentId); - for (OpensyncAPInetState inetState : inetStateTables) { - if (inetState.isEnabled()) - osNode.updateInetState(inetState); - } - opensyncNodeMap.put(apId, osNode); - - } - } - - } - - @Override - public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, - String apId) { - OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); - int customerId = session.getCustomerId(); - long equipmentId = session.getEquipmentId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - if (wifiAssociatedClients == null || wifiAssociatedClients.isEmpty() || apId == null) - return; - - OpensyncNode osNode = null; - synchronized (opensyncNodeMap) { - if (opensyncNodeMap.containsKey(apId)) { - osNode = opensyncNodeMap.get(apId); - for (OpensyncWifiAssociatedClients wifiClient : wifiAssociatedClients) { - osNode.updateWifiClients(wifiClient); - } - opensyncNodeMap.put(apId, osNode); - } else { - - osNode = new OpensyncNode(apId, null, customerId, equipmentId); - for (OpensyncWifiAssociatedClients wifiClient : wifiAssociatedClients) { - osNode.updateWifiClients(wifiClient); - } - opensyncNodeMap.put(apId, osNode); - } - - } - } - - @Override - public void awlanNodeDbTableUpdate(OpensyncAWLANNode opensyncAPState, String apId) { - - OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); - int customerId = session.getCustomerId(); - long equipmentId = session.getEquipmentId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - if (opensyncAPState == null || apId == null) - return; - - OpensyncNode osNode = null; - synchronized (opensyncNodeMap) { - if (opensyncNodeMap.containsKey(apId)) { - osNode = opensyncNodeMap.get(apId); - osNode.updateAWLANNode(opensyncAPState); - opensyncNodeMap.put(apId, osNode); - LOG.debug("Updated AWLAN_Node to map {}", osNode.toPrettyString()); - - } else { - - osNode = new OpensyncNode(apId, opensyncAPState, customerId, equipmentId); - opensyncNodeMap.put(apId, osNode); - } - - } - - } - - @Override - public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { - - Equipment ce = getCustomerEquipment(apId); - if (ce == null) { - LOG.debug("Cannot get equipmentId {} for apId {}", apId); - return; - } - - int customerId = ce.getCustomerId(); - long equipmentId = ce.getId(); - - synchronized (opensyncNodeMap) { - - if (opensyncNodeMap.containsKey(apId)) { - OpensyncNode osNode = opensyncNodeMap.get(apId); - - for (OpensyncAPVIFState vifToDelete : vifStateTables) { - if (osNode.deleteVif(vifToDelete)) { - opensyncNodeMap.put(apId, osNode); - LOG.debug("Deleted VIF for interface {} ssid {} from AP {}", vifToDelete.getIfName(), - vifToDelete.getSsid(), apId); - } else { - LOG.debug("Cannot find VIF for interface {} ssid {} marked for deletion under AP {}", - vifToDelete.getIfName(), vifToDelete.getSsid(), apId); - } - } - - } else { - LOG.debug("AP {} is not present in cache, cannot delete VIFs", apId); - } - } - } - - @Override - public void wifiAssociatedClientsDbTableDelete(String deletedClientMac, String apId) { - - OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); - long equipmentId = session.getEquipmentId(); - - if (equipmentId < 0L) { - LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); - return; - } - - synchronized (opensyncNodeMap) { - if (opensyncNodeMap.containsKey(apId)) { - OpensyncNode osNode = opensyncNodeMap.get(apId); - if (osNode.deleteWifiClient(deletedClientMac)) { - opensyncNodeMap.put(apId, osNode); - LOG.debug("Deleted WifiClient {} from AP {}", deletedClientMac, apId); - } else { - LOG.debug("Cannot find WifiClient {} marked for deletion under AP {}", deletedClientMac, apId); - } - } else { - LOG.debug("AP {} is not present in cache, cannot delete WifiClient {}", apId, deletedClientMac); - } - } - - try { -// LOG.debug("Deleted AssociatedClient {}", -// clientServiceInterface.delete(new MacAddress(deletedClientMac).getAddressAsLong())); - } catch (Exception e) { - LOG.error("Error deleting AssociatedClient {}", deletedClientMac, e); - } - - } + if (ovsdbSession == null) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } + + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiInetStateDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } + + if (inetStateTables == null || inetStateTables.isEmpty() || apId == null) { + return; + } + + // TODO: update Config/Status for Network from Wifi_Inet_State where + // applicable + + } + + @Override + public void wifiAssociatedClientsDbTableUpdate(List wifiAssociatedClients, + String apId) { + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + if (ovsdbSession == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Session for AP {}", apId); + return; + } + + Equipment ce = equipmentServiceInterface.getByInventoryIdOrNull(apId); + if (ce == null) { + LOG.debug("wifiAssociatedClientsDbTableUpdate::Cannot get Equipment for AP {}", apId); + return; + } + + long equipmentId = ce.getId(); + + if (equipmentId < 0L) { + LOG.debug("Cannot get equipmentId {} for session {}", equipmentId); + return; + } + + if (wifiAssociatedClients == null || wifiAssociatedClients.isEmpty() || apId == null) { + return; + } + + // TODO: update activeBSSDs, etc based on associated clients + + } + + @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; + } + + long equipmentId = ce.getId(); + + if (equipmentId < 0L) { + LOG.debug("awlanNodeDbTableUpdate::Cannot get equipmentId {} for session {}", equipmentId); + return; + } + + // TODO: update config where applicable + } + + @Override + public void wifiVIFStateDbTableDelete(List vifStateTables, String apId) { + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + + 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-ext-interface/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/models/OpensyncAPRadioState.java b/opensync-ext-interface/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/models/OpensyncAPRadioState.java index ccfdf43..de34a62 100644 --- a/opensync-ext-interface/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/models/OpensyncAPRadioState.java +++ b/opensync-ext-interface/src/main/java/com/telecominfraproject/wlan/opensync/external/integration/models/OpensyncAPRadioState.java @@ -6,6 +6,7 @@ package com.telecominfraproject.wlan.opensync.external.integration.models; import java.util.Map; import java.util.Set; +import com.telecominfraproject.wlan.core.model.equipment.RadioType; import com.telecominfraproject.wlan.core.model.json.BaseJsonModel; import com.vmware.ovsdb.protocol.operation.notation.Uuid; @@ -41,7 +42,7 @@ public class OpensyncAPRadioState extends BaseJsonModel { public Map channels; public int thermalUpgradeTemp; public Map hwParams; - public String freqBand; + public RadioType freqBand; public int thermalIntegration; public String channelMode; public Uuid _uuid; @@ -239,11 +240,11 @@ public class OpensyncAPRadioState extends BaseJsonModel { this.hwParams = hwParams; } - public String getFreqBand() { + public RadioType getFreqBand() { return freqBand; } - public void setFreqBand(String freqBand) { + public void setFreqBand(RadioType freqBand) { this.freqBand = freqBand; } diff --git a/opensync-gateway-cloud-process/src/main/resources/launchers/OpenSyncProcess (local, KDC certs) cloud.launch b/opensync-gateway-cloud-process/src/main/resources/launchers/OpenSyncProcess (local, KDC certs) cloud.launch index 46bce75..3a4223f 100644 --- a/opensync-gateway-cloud-process/src/main/resources/launchers/OpenSyncProcess (local, KDC certs) cloud.launch +++ b/opensync-gateway-cloud-process/src/main/resources/launchers/OpenSyncProcess (local, KDC certs) cloud.launch @@ -20,5 +20,5 @@ - + 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 2a1e758..bee53f0 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 @@ -45,370 +45,378 @@ import io.netty.handler.ssl.SslContext; @Component public class ConnectusOvsdbClient implements ConnectusOvsdbClientInterface { - private static final Logger LOG = LoggerFactory.getLogger(ConnectusOvsdbClient.class); - - @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.listenPort:6640}") - private int ovsdbListenPort; - - @org.springframework.beans.factory.annotation.Value("${connectus.manager.collectionIntervalSec.deviceStats:10}") - private long collectionIntervalSecDeviceStats; - - @Autowired - private SslContext sslContext; - - @Autowired - private OvsdbPassiveConnectionListener listener; - - @Autowired - private OvsdbDao ovsdbDao; - - @Autowired - private OpensyncExternalIntegrationInterface extIntegrationInterface; - - @Autowired - private OvsdbSessionMapInterface ovsdbSessionMapInterface; - - @PostConstruct - private void postCreate() { - listenForConnections(); - } - - public void listenForConnections() { - - ConnectionCallback connectionCallback = new ConnectionCallback() { - public void connected(OvsdbClient ovsdbClient) { - String remoteHost = ovsdbClient.getConnectionInfo().getRemoteAddress().getHostAddress(); - int localPort = ovsdbClient.getConnectionInfo().getLocalPort(); - String subjectDn = null; - try { - subjectDn = ((X509Certificate) ovsdbClient.getConnectionInfo().getRemoteCertificate()) - .getSubjectDN().getName(); - - String clientCn = SslUtil.extractCN(subjectDn); - LOG.info("ovsdbClient connecting from {} on port {} clientCn {}", remoteHost, localPort, clientCn); - - ConnectNodeInfo connectNodeInfo = ovsdbDao.getConnectNodeInfo(ovsdbClient); - - // successfully connected - register it in our - // connectedClients table - // In Plume's environment clientCn is not unique that's why - // we are augmenting it - // with the serialNumber and using it as a key (equivalent - // of KDC unique qrCode) - String key = clientCn + "_" + connectNodeInfo.serialNumber; - ConnectusOvsdbClient.this.ovsdbSessionMapInterface.newSession(key, ovsdbClient); - extIntegrationInterface.apConnected(key, connectNodeInfo); - monitorOvsdbStateTables(ovsdbClient, key); - - // push configuration to AP - connectNodeInfo = processConnectRequest(ovsdbClient, clientCn, connectNodeInfo); - - LOG.info("ovsdbClient connected from {} on port {} key {} ", remoteHost, localPort, key); - LOG.info("ovsdbClient connectedClients = {}", - ConnectusOvsdbClient.this.ovsdbSessionMapInterface.getNumSessions()); - - - } catch (Exception e) { - LOG.error("ovsdbClient error", e); - // something is wrong with the SSL - ovsdbClient.shutdown(); - return; - } - - } - - public void disconnected(OvsdbClient ovsdbClient) { - String remoteHost = ovsdbClient.getConnectionInfo().getRemoteAddress().getHostAddress(); - int localPort = ovsdbClient.getConnectionInfo().getLocalPort(); - String subjectDn = null; - try { - subjectDn = ((X509Certificate) ovsdbClient.getConnectionInfo().getRemoteCertificate()) - .getSubjectDN().getName(); - } catch (Exception e) { - // do nothing - } - - String clientCn = SslUtil.extractCN(subjectDn); - - // disconnected - deregister ovsdbClient from our - // connectedClients table - // unfortunately we only know clientCn at this point, but in - // Plume's environment - // they are not unique - // so we are doing a reverse lookup here, and then if we find - // the key we will - // remove the entry from the connectedClients. - String key = ConnectusOvsdbClient.this.ovsdbSessionMapInterface.lookupClientId(ovsdbClient); - - if (key != null) { - - // turn off monitor - try { - ovsdbClient.cancelMonitor(OvsdbDao.wifiRadioStateDbTable + "_" + key); - ovsdbClient.cancelMonitor(OvsdbDao.wifiVifStateDbTable + "_" + key); - ovsdbClient.cancelMonitor(OvsdbDao.wifiInetStateDbTable + "_" + key); - ovsdbClient.cancelMonitor(OvsdbDao.wifiAssociatedClientsDbTable + "_" + key); - ovsdbClient.cancelMonitor(OvsdbDao.awlanNodeDbTable + "_" + key); - - } catch (OvsdbClientException e) { - LOG.warn("Could not cancel Monitor {}", e.getMessage()); - } - - extIntegrationInterface.apDisconnected(key); - ConnectusOvsdbClient.this.ovsdbSessionMapInterface.removeSession(key); - } - - ovsdbClient.shutdown(); - - LOG.info("ovsdbClient disconnected from {} on port {} clientCn {} key {} ", remoteHost, localPort, - clientCn, key); - LOG.info("ovsdbClient connectedClients = {}", - ConnectusOvsdbClient.this.ovsdbSessionMapInterface.getNumSessions()); - } - - }; - - listener.startListeningWithSsl(ovsdbListenPort, sslContext, connectionCallback).join(); - - LOG.debug("manager waiting for connection on port {}...", ovsdbListenPort); - } - - private ConnectNodeInfo processConnectRequest(OvsdbClient ovsdbClient, String clientCn, - ConnectNodeInfo connectNodeInfo) { - - LOG.debug("Starting Client connect"); - connectNodeInfo = ovsdbDao.updateConnectNodeInfoOnConnect(ovsdbClient, clientCn, connectNodeInfo); - - String apId = clientCn + "_" + connectNodeInfo.serialNumber; - OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); - - 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); - } - - 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) { - ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); - ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); - } - -// ovsdbDao.configureWifiInet(ovsdbClient); - - LOG.debug("Client connect Done"); - return connectNodeInfo; - } - - public Set getConnectedClientIds() { - return ovsdbSessionMapInterface.getConnectedClientIds(); - } - - /** - * @param apId - * @param newRedirectorAddress - * @return updated value of the redirector - */ - public String changeRedirectorAddress(String apId, String newRedirectorAddress) { - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession == null) { - throw new IllegalStateException("AP with id " + apId + " is not connected"); - } - - String ret = ovsdbDao.changeRedirectorAddress(ovsdbSession.getOvsdbClient(), apId, newRedirectorAddress); - - return ret; - } - - @Override - public void processConfigChanged(String apId) { - LOG.debug("Starting processConfigChanged for {}", apId); - - OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); - if (ovsdbSession == null) { - throw new IllegalStateException("AP with id " + apId + " is not connected"); - } - - OvsdbClient ovsdbClient = ovsdbSession.getOvsdbClient(); - OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); - - if (opensyncAPConfig != null) { - ovsdbDao.removeAllSsids(ovsdbClient); - ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); - ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); - } - - LOG.debug("Finished processConfigChanged for {}", apId); - } - - 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, true, true, true)))), - new MonitorCallback() { - - @Override - public void update(TableUpdates tableUpdates) { - extIntegrationInterface.wifiRadioStatusDbTableUpdate( - ovsdbDao.getOpensyncAPRadioState(tableUpdates, key, ovsdbClient), key); - } - - }); - - extIntegrationInterface - .wifiRadioStatusDbTableUpdate(ovsdbDao.getOpensyncAPRadioState(rsCf.join(), key, ovsdbClient), key); - - CompletableFuture isCf = ovsdbClient - .monitor(OvsdbDao.ovsdbName, OvsdbDao.wifiInetStateDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiInetStateDbTable, - new MonitorRequest(new MonitorSelect(true, true, true, true)))), - new MonitorCallback() { - - @Override - public void update(TableUpdates tableUpdates) { - - extIntegrationInterface.wifiInetStateDbTableUpdate( - ovsdbDao.getOpensyncAPInetState(tableUpdates, key, ovsdbClient), key); - - } - - }); - - extIntegrationInterface - .wifiInetStateDbTableUpdate(ovsdbDao.getOpensyncAPInetState(isCf.join(), key, ovsdbClient), key); - - CompletableFuture vsCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, - OvsdbDao.wifiVifStateDbTable + "_" + key, - new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiVifStateDbTable, - new MonitorRequest(new MonitorSelect(true, true, true, true)))), - new MonitorCallback() { - @Override - public void update(TableUpdates tableUpdates) { - // extIntegrationInterface.wifiVIFStateDbTableUpdate( - // ovsdbDao.getOpensyncAPVIFState(tableUpdates, - // key, ovsdbClient), key); - List vifsToDelete = new ArrayList(); - for (Entry tableUpdate : tableUpdates.getTableUpdates().entrySet()) { - - for (Entry rowUpdate : tableUpdate.getValue().getRowUpdates().entrySet()) { - if (rowUpdate.getValue().getOld() != null && rowUpdate.getValue().getNew() == null) { - Row row = rowUpdate.getValue().getOld(); - String ifName = null; - String ssid = null; - if (row.getColumns().get("ssid") != null && row.getColumns().get("ssid").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - ssid = row.getStringColumn("ssid"); - } - if (row.getColumns().get("if_name") != null - && row.getColumns().get("if_name").getClass() - .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { - ifName = row.getStringColumn("if_name"); - } - if (ifName != null && ssid != null) { - OpensyncAPVIFState toBeDeleted = new OpensyncAPVIFState(); - toBeDeleted.setSsid(ssid); - toBeDeleted.setIfName(ifName); - vifsToDelete.add(toBeDeleted); - } - tableUpdate.getValue().getRowUpdates().remove(rowUpdate.getKey()); - } - - } - - if (tableUpdate.getValue().getRowUpdates().values().isEmpty()) { - tableUpdates.getTableUpdates().remove(tableUpdate.getKey()); - } - - } - - if (!vifsToDelete.isEmpty()) { - extIntegrationInterface.wifiVIFStateDbTableDelete(vifsToDelete, key); - } - if (tableUpdates.getTableUpdates().entrySet().isEmpty()) - extIntegrationInterface.wifiVIFStateDbTableUpdate( - ovsdbDao.getOpensyncAPVIFState(tableUpdates, key, ovsdbClient), key); - - } - - }); - - 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(true, true, true, true)))), - new MonitorCallback() { - - @Override - public void update(TableUpdates tableUpdates) { - - 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); - } - } - - } - - 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, true, true, true)))), - new MonitorCallback() { - - @Override - public void update(TableUpdates tableUpdates) { - extIntegrationInterface.awlanNodeDbTableUpdate( - ovsdbDao.getOpensyncAWLANNode(tableUpdates, key, ovsdbClient), key); - } - - }); - extIntegrationInterface.awlanNodeDbTableUpdate(ovsdbDao.getOpensyncAWLANNode(awCf.join(), key, ovsdbClient), - key); - - } - - @Override - public String closeSession(String apId) { - OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); - try { - session.getOvsdbClient().shutdown(); - } catch (Exception e) { - LOG.error("Failed to close session to " + apId + " " + e.getLocalizedMessage()); - return "Failed to close session to " + apId + " " + e.getLocalizedMessage(); - - } - LOG.debug("Closed session to " + apId); - return "Closed session to " + apId; - } + private static final Logger LOG = LoggerFactory.getLogger(ConnectusOvsdbClient.class); + + @org.springframework.beans.factory.annotation.Value("${connectus.ovsdb.listenPort:6640}") + private int ovsdbListenPort; + + @org.springframework.beans.factory.annotation.Value("${connectus.manager.collectionIntervalSec.deviceStats:10}") + private long collectionIntervalSecDeviceStats; + + @Autowired + private SslContext sslContext; + + @Autowired + private OvsdbPassiveConnectionListener listener; + + @Autowired + private OvsdbDao ovsdbDao; + + @Autowired + private OpensyncExternalIntegrationInterface extIntegrationInterface; + + @Autowired + private OvsdbSessionMapInterface ovsdbSessionMapInterface; + + @PostConstruct + private void postCreate() { + listenForConnections(); + } + + public void listenForConnections() { + + ConnectionCallback connectionCallback = new ConnectionCallback() { + @Override + public void connected(OvsdbClient ovsdbClient) { + String remoteHost = ovsdbClient.getConnectionInfo().getRemoteAddress().getHostAddress(); + int localPort = ovsdbClient.getConnectionInfo().getLocalPort(); + String subjectDn = null; + try { + subjectDn = ((X509Certificate) ovsdbClient.getConnectionInfo().getRemoteCertificate()) + .getSubjectDN().getName(); + + String clientCn = SslUtil.extractCN(subjectDn); + LOG.info("ovsdbClient connecting from {} on port {} clientCn {}", remoteHost, localPort, clientCn); + + ConnectNodeInfo connectNodeInfo = ovsdbDao.getConnectNodeInfo(ovsdbClient); + + // successfully connected - register it in our + // connectedClients table + // In Plume's environment clientCn is not unique that's why + // we are augmenting it + // with the serialNumber and using it as a key (equivalent + // of KDC unique qrCode) + String key = clientCn + "_" + connectNodeInfo.serialNumber; + ConnectusOvsdbClient.this.ovsdbSessionMapInterface.newSession(key, ovsdbClient); + extIntegrationInterface.apConnected(key, connectNodeInfo); + + // push configuration to AP + connectNodeInfo = processConnectRequest(ovsdbClient, clientCn, connectNodeInfo); + monitorOvsdbStateTables(ovsdbClient, key); + + LOG.info("ovsdbClient connected from {} on port {} key {} ", remoteHost, localPort, key); + LOG.info("ovsdbClient connectedClients = {}", + ConnectusOvsdbClient.this.ovsdbSessionMapInterface.getNumSessions()); + + } + catch (Exception e) { + LOG.error("ovsdbClient error", e); + // something is wrong with the SSL + ovsdbClient.shutdown(); + return; + } + + } + + @Override + public void disconnected(OvsdbClient ovsdbClient) { + String remoteHost = ovsdbClient.getConnectionInfo().getRemoteAddress().getHostAddress(); + int localPort = ovsdbClient.getConnectionInfo().getLocalPort(); + String subjectDn = null; + try { + subjectDn = ((X509Certificate) ovsdbClient.getConnectionInfo().getRemoteCertificate()) + .getSubjectDN().getName(); + } + catch (Exception e) { + // do nothing + } + + String clientCn = SslUtil.extractCN(subjectDn); + + // disconnected - deregister ovsdbClient from our + // connectedClients table + // unfortunately we only know clientCn at this point, but in + // Plume's environment + // they are not unique + // so we are doing a reverse lookup here, and then if we find + // the key we will + // remove the entry from the connectedClients. + String key = ConnectusOvsdbClient.this.ovsdbSessionMapInterface.lookupClientId(ovsdbClient); + + if (key != null) { + + // turn off monitor + try { + ovsdbClient.cancelMonitor(OvsdbDao.wifiRadioStateDbTable + "_" + key); + ovsdbClient.cancelMonitor(OvsdbDao.wifiVifStateDbTable + "_" + key); + ovsdbClient.cancelMonitor(OvsdbDao.wifiInetStateDbTable + "_" + key); + ovsdbClient.cancelMonitor(OvsdbDao.wifiAssociatedClientsDbTable + "_" + key); + ovsdbClient.cancelMonitor(OvsdbDao.awlanNodeDbTable + "_" + key); + + } + catch (OvsdbClientException e) { + LOG.warn("Could not cancel Monitor {}", e.getMessage()); + } + + extIntegrationInterface.apDisconnected(key); + ConnectusOvsdbClient.this.ovsdbSessionMapInterface.removeSession(key); + } + + ovsdbClient.shutdown(); + + LOG.info("ovsdbClient disconnected from {} on port {} clientCn {} key {} ", remoteHost, localPort, + clientCn, key); + LOG.info("ovsdbClient connectedClients = {}", + ConnectusOvsdbClient.this.ovsdbSessionMapInterface.getNumSessions()); + } + + }; + + listener.startListeningWithSsl(ovsdbListenPort, sslContext, connectionCallback).join(); + + LOG.debug("manager waiting for connection on port {}...", ovsdbListenPort); + } + + private ConnectNodeInfo processConnectRequest(OvsdbClient ovsdbClient, String clientCn, + ConnectNodeInfo connectNodeInfo) { + + LOG.debug("Starting Client connect"); + connectNodeInfo = ovsdbDao.updateConnectNodeInfoOnConnect(ovsdbClient, clientCn, connectNodeInfo); + + String apId = clientCn + "_" + connectNodeInfo.serialNumber; + OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); + + 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); + } + + 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) { + ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); + ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); + } + + // ovsdbDao.configureWifiInet(ovsdbClient); + + LOG.debug("Client connect Done"); + return connectNodeInfo; + } + + @Override + public Set getConnectedClientIds() { + return ovsdbSessionMapInterface.getConnectedClientIds(); + } + + /** + * @param apId + * @param newRedirectorAddress + * @return updated value of the redirector + */ + @Override + public String changeRedirectorAddress(String apId, String newRedirectorAddress) { + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + if (ovsdbSession == null) { + throw new IllegalStateException("AP with id " + apId + " is not connected"); + } + + String ret = ovsdbDao.changeRedirectorAddress(ovsdbSession.getOvsdbClient(), apId, newRedirectorAddress); + + return ret; + } + + @Override + public void processConfigChanged(String apId) { + LOG.debug("Starting processConfigChanged for {}", apId); + + OvsdbSession ovsdbSession = ovsdbSessionMapInterface.getSession(apId); + if (ovsdbSession == null) { + throw new IllegalStateException("AP with id " + apId + " is not connected"); + } + + OvsdbClient ovsdbClient = ovsdbSession.getOvsdbClient(); + OpensyncAPConfig opensyncAPConfig = extIntegrationInterface.getApConfig(apId); + + if (opensyncAPConfig != null) { + ovsdbDao.removeAllSsids(ovsdbClient); + ovsdbDao.configureWifiRadios(ovsdbClient, opensyncAPConfig); + ovsdbDao.configureSsids(ovsdbClient, opensyncAPConfig); + } + + LOG.debug("Finished processConfigChanged for {}", apId); + } + + 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() { + + @Override + public void update(TableUpdates tableUpdates) { + extIntegrationInterface.wifiRadioStatusDbTableUpdate( + ovsdbDao.getOpensyncAPRadioState(tableUpdates, key, ovsdbClient), key); + } + + }); + + extIntegrationInterface + .wifiRadioStatusDbTableUpdate(ovsdbDao.getOpensyncAPRadioState(rsCf.join(), key, ovsdbClient), key); + + CompletableFuture isCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, + OvsdbDao.wifiInetStateDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiInetStateDbTable, + new MonitorRequest(new MonitorSelect(true, true, true, true)))), + new MonitorCallback() { + + @Override + public void update(TableUpdates tableUpdates) { + + extIntegrationInterface.wifiInetStateDbTableUpdate( + ovsdbDao.getOpensyncAPInetState(tableUpdates, key, ovsdbClient), key); + + } + + }); + + extIntegrationInterface + .wifiInetStateDbTableUpdate(ovsdbDao.getOpensyncAPInetState(isCf.join(), key, ovsdbClient), key); + + CompletableFuture vsCf = ovsdbClient.monitor(OvsdbDao.ovsdbName, + OvsdbDao.wifiVifStateDbTable + "_" + key, + new MonitorRequests(ImmutableMap.of(OvsdbDao.wifiVifStateDbTable, + new MonitorRequest(new MonitorSelect(true, true, true, true)))), + new MonitorCallback() { + @Override + public void update(TableUpdates tableUpdates) { + // extIntegrationInterface.wifiVIFStateDbTableUpdate( + // ovsdbDao.getOpensyncAPVIFState(tableUpdates, + // key, ovsdbClient), key); + List vifsToDelete = new ArrayList<>(); + for (Entry tableUpdate : tableUpdates.getTableUpdates().entrySet()) { + + for (Entry rowUpdate : tableUpdate.getValue().getRowUpdates().entrySet()) { + if (rowUpdate.getValue().getOld() != null && rowUpdate.getValue().getNew() == null) { + Row row = rowUpdate.getValue().getOld(); + String ifName = null; + String ssid = null; + if (row.getColumns().get("ssid") != null && row.getColumns().get("ssid").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + ssid = row.getStringColumn("ssid"); + } + if (row.getColumns().get("if_name") != null + && row.getColumns().get("if_name").getClass() + .equals(com.vmware.ovsdb.protocol.operation.notation.Atom.class)) { + ifName = row.getStringColumn("if_name"); + } + if (ifName != null && ssid != null) { + OpensyncAPVIFState toBeDeleted = new OpensyncAPVIFState(); + toBeDeleted.setSsid(ssid); + toBeDeleted.setIfName(ifName); + vifsToDelete.add(toBeDeleted); + } + tableUpdate.getValue().getRowUpdates().remove(rowUpdate.getKey()); + } + + } + + if (tableUpdate.getValue().getRowUpdates().values().isEmpty()) { + tableUpdates.getTableUpdates().remove(tableUpdate.getKey()); + } + + } + + if (!vifsToDelete.isEmpty()) { + extIntegrationInterface.wifiVIFStateDbTableDelete(vifsToDelete, key); + } + if (tableUpdates.getTableUpdates().entrySet().isEmpty()) { + extIntegrationInterface.wifiVIFStateDbTableUpdate( + ovsdbDao.getOpensyncAPVIFState(tableUpdates, key, ovsdbClient), key); + } + + } + + }); + + 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() { + + @Override + public void update(TableUpdates tableUpdates) { + + 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); + } + } + + } + + 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() { + + @Override + public void update(TableUpdates tableUpdates) { + extIntegrationInterface.awlanNodeDbTableUpdate( + ovsdbDao.getOpensyncAWLANNode(tableUpdates, key, ovsdbClient), key); + } + + }); + extIntegrationInterface.awlanNodeDbTableUpdate(ovsdbDao.getOpensyncAWLANNode(awCf.join(), key, ovsdbClient), + key); + + } + + @Override + public String closeSession(String apId) { + OvsdbSession session = ovsdbSessionMapInterface.getSession(apId); + try { + session.getOvsdbClient().shutdown(); + } + catch (Exception e) { + LOG.error("Failed to close session to " + apId + " " + e.getLocalizedMessage()); + return "Failed to close session to " + apId + " " + e.getLocalizedMessage(); + + } + LOG.debug("Closed session to " + apId); + return "Closed session to " + apId; + } } 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 c26657f..d4edb12 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 @@ -65,2548 +65,2633 @@ import com.vmware.ovsdb.service.OvsdbClient; @Component public class OvsdbDao { - 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.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.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(); - - 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"); - - 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.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(10)); - 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)); + 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.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.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(); + + 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"); + + 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.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<>(10)); + 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); + } + } + + } + 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); + + LOG.debug("Select from AWLAN_Node:"); - 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"); + String skuNumber = null; + String serialNumber = null; + String model = null; + String firmwareVersion = null; - try { - LOG.debug("Starting Redirect"); + Row row = null; + if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { + row = ((SelectResult) result[0]).getRows().iterator().next(); + } - operations.add(new Select(awlanNodeDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + firmwareVersion = row != null ? row.getStringColumn("firmware_version") : null; - LOG.debug("Select from AWLAN_Node:"); + skuNumber = getSingleValueFromSet(row, "sku_number"); + serialNumber = getSingleValueFromSet(row, "serial_number"); + model = getSingleValueFromSet(row, "model"); - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + LOG.info("Redirecting AP Node: clientCn {} serialNumber {} model {} firmwareVersion {} skuNumber {}", + clientCn, serialNumber, model, firmwareVersion, skuNumber); - String skuNumber = null; - String serialNumber = null; - String model = null; - String firmwareVersion = null; + // Update table AWLAN_Node - set manager_addr + operations.clear(); + Map updateColumns = new HashMap<>(); - Row row = null; - if (result != null && result.length > 0 && !((SelectResult) result[0]).getRows().isEmpty()) { - row = ((SelectResult) result[0]).getRows().iterator().next(); - } + updateColumns.put("manager_addr", new Atom<>("ssl:" + managerIpAddr + ":" + ovsdbListenPort)); - firmwareVersion = (row != null) ? row.getStringColumn("firmware_version") : null; + row = new Row(updateColumns); + operations.add(new Update(awlanNodeDbTable, row)); - skuNumber = getSingleValueFromSet(row, "sku_number"); - serialNumber = getSingleValueFromSet(row, "serial_number"); - model = getSingleValueFromSet(row, "model"); + fResult = ovsdbClient.transact(ovsdbName, operations); + result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - LOG.info("Redirecting AP Node: clientCn {} serialNumber {} model {} firmwareVersion {} skuNumber {}", - clientCn, serialNumber, model, firmwareVersion, skuNumber); + LOG.debug("Updated AWLAN_Node:"); - // Update table AWLAN_Node - set manager_addr - operations.clear(); - Map updateColumns = new HashMap<>(); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - updateColumns.put("manager_addr", new Atom("ssl:" + managerIpAddr + ":" + ovsdbListenPort)); + LOG.debug("Redirect Done"); + } + catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error when redirecting AP Node", e); + throw new RuntimeException(e); + } - row = new Row(updateColumns); - operations.add(new Update(awlanNodeDbTable, row)); + } - fResult = ovsdbClient.transact(ovsdbName, operations); - result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + public Set getSet(Row row, String columnName) { - LOG.debug("Updated AWLAN_Node:"); + Set set = row != null ? row.getSetColumn(columnName) : null; - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + return set; + } - LOG.debug("Redirect Done"); - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error when redirecting AP Node", e); - throw new RuntimeException(e); - } + public T getSingleValueFromSet(Row row, String columnName) { - } + Set set = row != null ? row.getSetColumn(columnName) : null; + T ret = set != null && !set.isEmpty() ? set.iterator().next() : null; - public Set getSet(Row row, String columnName) { + return ret; + } - Set set = (row != null) ? row.getSetColumn(columnName) : null; + public Map getProvisionedInterfaces(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); - return set; - } + 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"); - public T getSingleValueFromSet(Row row, String columnName) { + try { + LOG.debug("Retrieving Interfaces:"); - Set set = (row != null) ? row.getSetColumn(columnName) : null; - T ret = (set != null && !set.isEmpty()) ? set.iterator().next() : null; + operations.add(new Select(interfaceDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - return ret; - } + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - public Map getProvisionedInterfaces(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); + for (Row row : ((SelectResult) result[0]).getRows()) { - 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"); + InterfaceInfo interfaceInfo = new InterfaceInfo(); + interfaceInfo.name = row.getStringColumn("name"); + interfaceInfo.type = row.getStringColumn("type"); + interfaceInfo.uuid = row.getUuidColumn("_uuid"); - try { - LOG.debug("Retrieving Interfaces:"); + Long tmp = getSingleValueFromSet(row, "ofport"); + interfaceInfo.ofport = tmp != null ? tmp.intValue() : 0; - operations.add(new Select(interfaceDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + tmp = getSingleValueFromSet(row, "mtu"); + interfaceInfo.mtu = tmp != null ? tmp.intValue() : 0; - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + tmp = getSingleValueFromSet(row, "ifindex"); + interfaceInfo.ifIndex = tmp != null ? tmp.intValue() : 0; - for (Row row : ((SelectResult) result[0]).getRows()) { + String tmpStr = getSingleValueFromSet(row, "link_state"); + interfaceInfo.linkState = tmpStr != null ? tmpStr : ""; - InterfaceInfo interfaceInfo = new InterfaceInfo(); - interfaceInfo.name = row.getStringColumn("name"); - interfaceInfo.type = row.getStringColumn("type"); - interfaceInfo.uuid = row.getUuidColumn("_uuid"); + tmpStr = getSingleValueFromSet(row, "admin_state"); + interfaceInfo.adminState = tmpStr != null ? tmpStr : ""; - Long tmp = getSingleValueFromSet(row, "ofport"); - interfaceInfo.ofport = tmp != null ? tmp.intValue() : 0; + interfaceInfo.options = row.getMapColumn("options"); - tmp = getSingleValueFromSet(row, "mtu"); - interfaceInfo.mtu = tmp != null ? tmp.intValue() : 0; + ret.put(interfaceInfo.name, interfaceInfo); + } - tmp = getSingleValueFromSet(row, "ifindex"); - interfaceInfo.ifIndex = tmp != null ? tmp.intValue() : 0; + LOG.debug("Retrieved Interfaces: {}", ret); - String tmpStr = getSingleValueFromSet(row, "link_state"); - interfaceInfo.linkState = tmpStr != null ? tmpStr : ""; + } + catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { + LOG.error("Error in getProvisionedInterfaces", e); - tmpStr = getSingleValueFromSet(row, "admin_state"); - interfaceInfo.adminState = tmpStr != null ? tmpStr : ""; + throw new RuntimeException(e); + } - interfaceInfo.options = row.getMapColumn("options"); + return ret; + } - ret.put(interfaceInfo.name, interfaceInfo); - } + public Map getProvisionedPorts(OvsdbClient ovsdbClient) { + Map ret = new HashMap<>(); - LOG.debug("Retrieved Interfaces: {}", ret); + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + List columns = new ArrayList<>(); + columns.add("name"); + columns.add("_uuid"); + columns.add("interfaces"); - } catch (ExecutionException | InterruptedException | OvsdbClientException | TimeoutException e) { - LOG.error("Error in getProvisionedInterfaces", e); + try { + LOG.debug("Retrieving Ports:"); - throw new RuntimeException(e); - } + operations.add(new Select(portDbTable, conditions, columns)); + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - return ret; - } + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } - public Map getProvisionedPorts(OvsdbClient ovsdbClient) { - Map ret = new HashMap<>(); + for (Row row : ((SelectResult) result[0]).getRows()) { - List operations = new ArrayList<>(); - List conditions = new ArrayList<>(); - List columns = new ArrayList<>(); - columns.add("name"); - columns.add("_uuid"); - columns.add("interfaces"); + PortInfo portInfo = new PortInfo(); + portInfo.name = row.getStringColumn("name"); + portInfo.uuid = row.getUuidColumn("_uuid"); + portInfo.interfaceUuids = row.getSetColumn("interfaces"); - try { - LOG.debug("Retrieving Ports:"); + 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); + } + } + + } + + if (portUuid == null) { + throw new IllegalStateException("Port entry was not created successfully"); + } - operations.add(new Select(portDbTable, conditions, columns)); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + operations = new ArrayList<>(); - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } + // link the port to the bridge + if (provisionedBridges.containsKey(bridgeName)) { + BridgeInfo existingBridge = provisionedBridges.get(bridgeName); - for (Row row : ((SelectResult) result[0]).getRows()) { + conditions = new ArrayList<>(); + updateColumns = new HashMap<>(); + + conditions.add(new Condition("name", Function.EQUALS, new Atom<>(bridgeName))); - PortInfo portInfo = new PortInfo(); - portInfo.name = row.getStringColumn("name"); - portInfo.uuid = row.getUuidColumn("_uuid"); - portInfo.interfaceUuids = row.getSetColumn("interfaces"); + Set bridgePortsSet = new HashSet<>(); + if (existingBridge.portUuids != null) { + bridgePortsSet.addAll(existingBridge.portUuids); + } + + bridgePortsSet.add(portUuid); + com.vmware.ovsdb.protocol.operation.notation.Set bridgePorts = com.vmware.ovsdb.protocol.operation.notation.Set + .of(bridgePortsSet); + updateColumns.put("ports", bridgePorts); - 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"); + row = new Row(updateColumns); + operations.add(new Update(bridgeDbTable, row)); - try { - LOG.debug("Retrieving Bridges:"); + } + else { + LOG.warn("provisionedBridges does not have bridge {} - {} - port will be dangling", bridgeName, + provisionedBridges.keySet()); + } - 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); - } - } - - } + CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); + OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); - if (portUuid == null) { - throw new IllegalStateException("Port entry was not created successfully"); - } + if (LOG.isDebugEnabled()) { + LOG.debug("Finished provisioning Interface/port/bridge for {} / {}", interfaceName, bridgeName); - operations = new ArrayList<>(); + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + } - // link the port to the bridge - if (provisionedBridges.containsKey(bridgeName)) { - BridgeInfo existingBridge = provisionedBridges.get(bridgeName); + } + } - conditions = new ArrayList<>(); - updateColumns = new HashMap<>(); + // public static final String homeAp24 = "home-ap-24"; + // public static final String homeApL50 = "home-ap-l50"; + // public static final String homeApU50 = "home-ap-u50"; - conditions.add(new Condition("name", Function.EQUALS, new Atom<>(bridgeName))); + public static final String brWan = "br-wan"; + public static final String brLan = "br-lan"; - Set bridgePortsSet = new HashSet<>(); - if (existingBridge.portUuids != null) { - bridgePortsSet.addAll(existingBridge.portUuids); - } + public static final String patchW2h = "patch-w2h"; + public static final String patchH2w = "patch-h2w"; - bridgePortsSet.add(portUuid); - com.vmware.ovsdb.protocol.operation.notation.Set bridgePorts = com.vmware.ovsdb.protocol.operation.notation.Set - .of(bridgePortsSet); - updateColumns.put("ports", bridgePorts); + public void provisionBridgePortInterface(OvsdbClient ovsdbClient) { + try { + Map provisionedInterfaces = getProvisionedInterfaces(ovsdbClient); + LOG.debug("Existing Interfaces: {}", provisionedInterfaces.keySet()); - row = new Row(updateColumns); - operations.add(new Update(bridgeDbTable, row)); + Map provisionedPorts = getProvisionedPorts(ovsdbClient); + LOG.debug("Existing Ports: {}", provisionedPorts.keySet()); - } else { - LOG.warn("provisionedBridges does not have bridge {} - {} - port will be dangling", bridgeName, - provisionedBridges.keySet()); - } + Map provisionedBridges = getProvisionedBridges(ovsdbClient); + LOG.debug("Existing Bridges: {}", provisionedBridges.keySet()); - CompletableFuture fResult = ovsdbClient.transact(ovsdbName, operations); - OperationResult[] result = fResult.get(ovsdbTimeoutSec, TimeUnit.SECONDS); + Map patchH2wOptions = new HashMap<>(); + patchH2wOptions.put("peer", "patch-w2h"); - if (LOG.isDebugEnabled()) { - LOG.debug("Finished provisioning Interface/port/bridge for {} / {}", interfaceName, bridgeName); + Map patchW2hOptions = new HashMap<>(); + patchH2wOptions.put("peer", "patch-h2w"); - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - } + 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 static final String homeAp24 = "home-ap-24"; -// public static final String homeApL50 = "home-ap-l50"; -// public static final String homeApU50 = "home-ap-u50"; + } + catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in provisionBridgePortInterface", e); + throw new RuntimeException(e); + } - 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 void removeOnboardingSsids(OvsdbClient ovsdbClient) { + try { + List operations = new ArrayList<>(); + List conditions = new ArrayList<>(); + conditions.add(new Condition("ssid", Function.EQUALS, new Atom<>("opensync.onboard"))); - public void provisionBridgePortInterface(OvsdbClient ovsdbClient) { - try { - Map provisionedInterfaces = getProvisionedInterfaces(ovsdbClient); - LOG.debug("Existing Interfaces: {}", provisionedInterfaces.keySet()); + operations.add(new Delete(wifiVifConfigDbTable, conditions)); - Map provisionedPorts = getProvisionedPorts(ovsdbClient); - LOG.debug("Existing Ports: {}", provisionedPorts.keySet()); + 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; + default: + ht_mode = "HT20"; + } + 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)); + updateColumns.put("ht_mode", new Atom<>(ht_mode)); + 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, 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)); + updateColumns.put("ft_psk", new Atom<>(0)); + 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 + + 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.equalsIgnoreCase("wpaPSK") || ssidSecurityMode.equalsIgnoreCase("wpa2PSK")) { + opensyncSecurityMode = "WPA-PSK"; + } + else if (ssidSecurityMode.equalsIgnoreCase("wep")) { + opensyncSecurityMode = "WEP"; + } + + security.put("encryption", opensyncSecurityMode); + // key and mode is N/A for OPEN security + if (!opensyncSecurityMode.equals("OPEN")) { + security.put("key", ssidConfig.getKeyStr()); + security.put("mode", Long.toString(ssidConfig.getSecureMode().getId())); + } + + 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, 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 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)); - Map provisionedBridges = getProvisionedBridges(ovsdbClient); - LOG.debug("Existing Bridges: {}", provisionedBridges.keySet()); - - Map patchH2wOptions = new HashMap<>(); - patchH2wOptions.put("peer", "patch-w2h"); - - Map patchW2hOptions = new HashMap<>(); - patchH2wOptions.put("peer", "patch-h2w"); - - 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); - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in provisionBridgePortInterface", e); - throw new RuntimeException(e); - } - - } - - 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"))); - - operations.add(new Delete(wifiVifConfigDbTable, conditions)); - - 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; - default: - ht_mode = "HT20"; - } - 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) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TimeoutException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ExecutionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - } - - } - - 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)) { - tableState.setFreqBand(row.getStringColumn("freq_band")); - } - 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.toPrettyString()); - }); - - } 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.toPrettyString()); - }); - - } 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.toPrettyString()); - }); - - } 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.toPrettyString()); - }); - } 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)); - updateColumns.put("ht_mode", new Atom<>(ht_mode)); - 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, 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)); - updateColumns.put("ft_psk", new Atom<>(0)); - 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 - - 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.equalsIgnoreCase("wpaPSK") || ssidSecurityMode.equalsIgnoreCase("wpa2PSK")) - opensyncSecurityMode = "WPA-PSK"; - else if (ssidSecurityMode.equalsIgnoreCase("wep")) - opensyncSecurityMode = "WEP"; - - security.put("encryption", opensyncSecurityMode); - // key and mode is N/A for OPEN security - if (!opensyncSecurityMode.equals("OPEN")) { - security.put("key", ssidConfig.getKeyStr()); - security.put("mode", Long.toString(ssidConfig.getSecureMode().getId())); - } - - 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, 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 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)); - - 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 configureWifiInetSetNetwork(OvsdbClient ovsdbClient, String ifName) { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - List conditions = new ArrayList<>(); - - 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); - - for (OperationResult res : result) { - LOG.debug("Op Result {}", res); - } - - } catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { - LOG.error("Error in configureWifiInetSetNetwork", e); - throw new RuntimeException(e); - } - - } - - public void configureWifiInet(OvsdbClient ovsdbClient) { - Map provisionedWifiInetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); - LOG.debug("Existing WifiInetConfigs: {}", provisionedWifiInetConfigs.keySet()); - - String ifName = ifName2pt4GHz; - if (!provisionedWifiInetConfigs.containsKey(ifName)) { - configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); - } - - ifName = ifName5GHzL; - if (!provisionedWifiInetConfigs.containsKey(ifName)) { - configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); - } - - ifName = ifName5GHzU; - 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); - } - } - - public void configureStats(OvsdbClient ovsdbClient) { - - try { - List operations = new ArrayList<>(); - Map updateColumns = new HashMap<>(); - Map thresholdMap = new HashMap<>(); - thresholdMap.put("max_delay", 600); - thresholdMap.put("util", 10); - - @SuppressWarnings("unchecked") - com.vmware.ovsdb.protocol.operation.notation.Map thresholds = com.vmware.ovsdb.protocol.operation.notation.Map - .of(thresholdMap); - - provisionWifiStatsConfigDevice(getProvisionedWifiStatsConfigs(ovsdbClient), operations, updateColumns); - - provisionWifiStatsConfigSurvey(getProvisionedWifiStatsConfigs(ovsdbClient), operations, thresholds); - - provisionWifiStatsConfigNeighbor(getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsConfigClient(getProvisionedWifiStatsConfigs(ovsdbClient), operations); - - provisionWifiStatsRssi(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 provisionWifiStatsRssi(Map provisionedWifiStatsConfigs, - List operations) { - Map updateColumns; - Row row; - for (String band : new String[] { "2.4G", "5GL", "5GU" }) { - if (!provisionedWifiStatsConfigs.containsKey(band + "_rssi_on-chan")) { - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>(band)); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("rssi")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - row = new Row(updateColumns); - - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - - } - } - - private void provisionWifiStatsConfigNeighbor(Map provisionedWifiStatsConfigs, - List operations) { - Map updateColumns; - Row row; - - 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(44); - channelSet5gl.add(52); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gl); - - Set channelSet5gu = new HashSet<>(); - channelSet5gu.add(100); - channelSet5gu.add(108); - channelSet5gu.add(116); - 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("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - 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_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("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - 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_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("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - 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_neighbor_on-chan")) { - // - updateColumns = new HashMap<>(); - // updateColumns.put("channel_list", channels ); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - // updateColumns.put("threshold", thresholds ); - - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_neighbor_on-chan")) { - // - updateColumns = new HashMap<>(); - // updateColumns.put("channel_list", channels ); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - // updateColumns.put("threshold", thresholds ); - - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - - if (!provisionedWifiStatsConfigs.containsKey("2.4G_neighbor_on-chan")) { - // - updateColumns = new HashMap<>(); - // updateColumns.put("channel_list", channels ); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("neighbor")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - // updateColumns.put("threshold", thresholds ); - - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - } - - private void provisionWifiStatsConfigSurvey(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(44); - channelSet5gl.add(52); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gl); - - Set channelSet5gu = new HashSet<>(); - channelSet5gu.add(100); - channelSet5gu.add(108); - channelSet5gu.add(116); - com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set - .of(channelSet5gu); - - Map updateColumns; - Row row; - - if (!provisionedWifiStatsConfigs.containsKey("2.4G_survey_on-chan")) { - // - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_survey_on-chan")) { - // - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - - if (!provisionedWifiStatsConfigs.containsKey("5GU_survey_on-chan")) { - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(0)); - updateColumns.put("survey_type", new Atom<>("on-chan")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - - 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<>(0)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(10)); - 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<>(0)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(10)); - 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<>(0)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("survey")); - updateColumns.put("survey_interval_ms", new Atom<>(10)); - updateColumns.put("survey_type", new Atom<>("off-chan")); - updateColumns.put("threshold", thresholds); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - // - } - - } - - private void provisionWifiStatsConfigDevice(Map provisionedWifiStatsConfigs, - List operations, Map updateColumns) { - Row row; - if (!provisionedWifiStatsConfigs.containsKey("2.4G_device")) { - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_interval", new Atom<>(900)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("device")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_device")) { - // updateColumns.put("channel_list", channels ); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_interval", new Atom<>(900)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("device")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - - if (!provisionedWifiStatsConfigs.containsKey("5GU_device")) { - // updateColumns.put("channel_list", channels ); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_interval", new Atom<>(900)); - updateColumns.put("sampling_interval", new Atom<>(0)); - updateColumns.put("stats_type", new Atom<>("device")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - } - - private void provisionWifiStatsConfigClient(Map provisionedWifiStatsConfigs, - List operations) { - Map updateColumns; - Row row; - if (!provisionedWifiStatsConfigs.containsKey("2.4G_client")) { - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("2.4G")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("client")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - - if (!provisionedWifiStatsConfigs.containsKey("5GL_client")) { - - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("5GL")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("client")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - - } - - if (!provisionedWifiStatsConfigs.containsKey("5GU_client")) { - - updateColumns = new HashMap<>(); - updateColumns.put("radio_type", new Atom<>("5GU")); - updateColumns.put("reporting_count", new Atom<>(0)); - updateColumns.put("reporting_interval", new Atom<>(60)); - updateColumns.put("sampling_interval", new Atom<>(10)); - updateColumns.put("stats_type", new Atom<>("client")); - row = new Row(updateColumns); - operations.add(new Insert(wifiStatsConfigDbTable, row)); - } - } - - 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; - } + 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 configureWifiInetSetNetwork(OvsdbClient ovsdbClient, String ifName) { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + List conditions = new ArrayList<>(); + + 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); + + for (OperationResult res : result) { + LOG.debug("Op Result {}", res); + } + + } + catch (OvsdbClientException | TimeoutException | ExecutionException | InterruptedException e) { + LOG.error("Error in configureWifiInetSetNetwork", e); + throw new RuntimeException(e); + } + + } + + public void configureWifiInet(OvsdbClient ovsdbClient) { + Map provisionedWifiInetConfigs = getProvisionedWifiInetConfigs(ovsdbClient); + LOG.debug("Existing WifiInetConfigs: {}", provisionedWifiInetConfigs.keySet()); + + String ifName = ifName2pt4GHz; + if (!provisionedWifiInetConfigs.containsKey(ifName)) { + configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); + } + + ifName = ifName5GHzL; + if (!provisionedWifiInetConfigs.containsKey(ifName)) { + configureWifiInet(ovsdbClient, provisionedWifiInetConfigs, ifName); + } + + ifName = ifName5GHzU; + 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); + } + } + + public void configureStats(OvsdbClient ovsdbClient) { + + try { + List operations = new ArrayList<>(); + Map updateColumns = new HashMap<>(); + Map thresholdMap = new HashMap<>(); + thresholdMap.put("max_delay", 600); + thresholdMap.put("util", 10); + + @SuppressWarnings("unchecked") + com.vmware.ovsdb.protocol.operation.notation.Map thresholds = com.vmware.ovsdb.protocol.operation.notation.Map + .of(thresholdMap); + + provisionWifiStatsConfigDevice(getProvisionedWifiStatsConfigs(ovsdbClient), operations, updateColumns); + + provisionWifiStatsConfigSurvey(getProvisionedWifiStatsConfigs(ovsdbClient), operations, thresholds); + + provisionWifiStatsConfigNeighbor(getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + provisionWifiStatsConfigClient(getProvisionedWifiStatsConfigs(ovsdbClient), operations); + + provisionWifiStatsRssi(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 provisionWifiStatsRssi(Map provisionedWifiStatsConfigs, + List operations) { + Map updateColumns; + Row row; + for (String band : new String[] { "2.4G", "5GL", "5GU" }) { + if (!provisionedWifiStatsConfigs.containsKey(band + "_rssi_on-chan")) { + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>(band)); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("rssi")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + row = new Row(updateColumns); + + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + + } + } + + private void provisionWifiStatsConfigNeighbor(Map provisionedWifiStatsConfigs, + List operations) { + Map updateColumns; + Row row; + + 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(44); + channelSet5gl.add(52); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gl); + + Set channelSet5gu = new HashSet<>(); + channelSet5gu.add(100); + channelSet5gu.add(108); + channelSet5gu.add(116); + 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("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + 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_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("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + 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_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("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + 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_neighbor_on-chan")) { + // + updateColumns = new HashMap<>(); + // updateColumns.put("channel_list", channels ); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + // updateColumns.put("threshold", thresholds ); + + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_neighbor_on-chan")) { + // + updateColumns = new HashMap<>(); + // updateColumns.put("channel_list", channels ); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + // updateColumns.put("threshold", thresholds ); + + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + + if (!provisionedWifiStatsConfigs.containsKey("2.4G_neighbor_on-chan")) { + // + updateColumns = new HashMap<>(); + // updateColumns.put("channel_list", channels ); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("neighbor")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + // updateColumns.put("threshold", thresholds ); + + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + } + + private void provisionWifiStatsConfigSurvey(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(44); + channelSet5gl.add(52); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gl = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gl); + + Set channelSet5gu = new HashSet<>(); + channelSet5gu.add(100); + channelSet5gu.add(108); + channelSet5gu.add(116); + com.vmware.ovsdb.protocol.operation.notation.Set channels5gu = com.vmware.ovsdb.protocol.operation.notation.Set + .of(channelSet5gu); + + Map updateColumns; + Row row; + + if (!provisionedWifiStatsConfigs.containsKey("2.4G_survey_on-chan")) { + // + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_survey_on-chan")) { + // + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + + if (!provisionedWifiStatsConfigs.containsKey("5GU_survey_on-chan")) { + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(0)); + updateColumns.put("survey_type", new Atom<>("on-chan")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + + 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<>(0)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(10)); + 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<>(0)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(10)); + 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<>(0)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("survey")); + updateColumns.put("survey_interval_ms", new Atom<>(10)); + updateColumns.put("survey_type", new Atom<>("off-chan")); + updateColumns.put("threshold", thresholds); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + // + } + + } + + private void provisionWifiStatsConfigDevice(Map provisionedWifiStatsConfigs, + List operations, Map updateColumns) { + Row row; + if (!provisionedWifiStatsConfigs.containsKey("2.4G_device")) { + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_interval", new Atom<>(900)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("device")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_device")) { + // updateColumns.put("channel_list", channels ); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_interval", new Atom<>(900)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("device")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + + if (!provisionedWifiStatsConfigs.containsKey("5GU_device")) { + // updateColumns.put("channel_list", channels ); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_interval", new Atom<>(900)); + updateColumns.put("sampling_interval", new Atom<>(0)); + updateColumns.put("stats_type", new Atom<>("device")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + } + + private void provisionWifiStatsConfigClient(Map provisionedWifiStatsConfigs, + List operations) { + Map updateColumns; + Row row; + if (!provisionedWifiStatsConfigs.containsKey("2.4G_client")) { + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("2.4G")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("client")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + + if (!provisionedWifiStatsConfigs.containsKey("5GL_client")) { + + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("5GL")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("client")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + + } + + if (!provisionedWifiStatsConfigs.containsKey("5GU_client")) { + + updateColumns = new HashMap<>(); + updateColumns.put("radio_type", new Atom<>("5GU")); + updateColumns.put("reporting_count", new Atom<>(0)); + updateColumns.put("reporting_interval", new Atom<>(60)); + updateColumns.put("sampling_interval", new Atom<>(10)); + updateColumns.put("stats_type", new Atom<>("client")); + row = new Row(updateColumns); + operations.add(new Insert(wifiStatsConfigDbTable, row)); + } + } + + 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; + } }