Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2015 Open Networking Laboratory
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.onosproject.provider.netconf.device.impl;
 
 import static com.google.common.base.Strings.isNullOrEmpty;
 import static org.onlab.util.Tools.delay;
 import static org.onlab.util.Tools.get;
 import static org.onlab.util.Tools.groupedThreads;
 import static org.slf4j.LoggerFactory.getLogger;
 
 import java.net.URI;
 import java.util.Map;
 
Provider which will try to fetch the details of NETCONF devices from the core and run a capability discovery on each of the device.
 
 @Component(immediate = true)
 public class NetconfDeviceProvider extends AbstractProvider
         implements DeviceProvider {
 
     private final Logger log = getLogger(NetconfDeviceProvider.class);
 
 
 
 
     protected DeviceService deviceService;
 
     protected ClusterService clusterService;
 
     protected ComponentConfigService cfgService;
 
     private ExecutorService deviceBuilder = Executors
             .newFixedThreadPool(1, groupedThreads("onos/netconf""device-creator"));
 
     // Delay between events in ms.
     private static final int EVENTINTERVAL = 5;
 
     private static final String SCHEME = "netconf";
 
     @Property(name = "devConfigs", value = "", label = "Instance-specific configurations")
     private String devConfigs = null;
 
     @Property(name = "devPasswords", value = "", label = "Instance-specific password")
     private String devPasswords = null;

    
Creates a provider with the supplier identifier.
    public NetconfDeviceProvider() {
        super(new ProviderId("netconf""org.onosproject.provider.netconf"));
    }
    @Activate
    public void activate(ComponentContext context) {
         = .register(this);
        modified(context);
        .info("Started");
    }
    @Deactivate
    public void deactivate(ComponentContext context) {
        .unregisterProperties(getClass(), false);
        try {
            for (Entry<DeviceIdNetconfDevicedeviceEntry : 
                    .entrySet()) {
                .submit(new DeviceCreator(deviceEntry.getValue(),
                                                       false));
            }
            .awaitTermination(1000, .);
        } catch (InterruptedException e) {
            .error("Device builder did not terminate");
        }
        .shutdownNow();
        .clear();
        .unregister(this);
         = null;
        .info("Stopped");
    }
    @Modified
    public void modified(ComponentContext context) {
        if (context == null) {
            .info("No configuration file");
            return;
        }
        Dictionary<?, ?> properties = context.getProperties();
        String deviceCfgValue = get(properties"devConfigs");
        .info("Settings: devConfigs={}"deviceCfgValue);
        if (!isNullOrEmpty(deviceCfgValue)) {
            addOrRemoveDevicesConfig(deviceCfgValue);
        }
    }
    private void addOrRemoveDevicesConfig(String deviceConfig) {
        for (String deviceEntry : deviceConfig.split(",")) {
            NetconfDevice device = processDeviceEntry(deviceEntry);
            if (device != null) {
                .info("Device Detail: username: {}, host={}, port={}, state={}",
                        device.getUsername(), device.getSshHost(),
                         device.getSshPort(), device.getDeviceState().name());
                if (device.isActive()) {
                    .submit(new DeviceCreator(devicetrue));
                } else {
                    .submit(new DeviceCreator(devicefalse));
                }
            }
        }
    }
    private NetconfDevice processDeviceEntry(String deviceEntry) {
        if (deviceEntry == null) {
            .info("No content for Device Entry, so cannot proceed further.");
            return null;
        }
        .info("Trying to convert Device Entry String: " + deviceEntry
                + " to a Netconf Device Object");
        NetconfDevice device = null;
        try {
            String userInfo = deviceEntry.substring(0, deviceEntry
                    .lastIndexOf('@'));
            String hostInfo = deviceEntry.substring(deviceEntry
                    .lastIndexOf('@') + 1);
            String[] infoSplit = userInfo.split(":");
            String username = infoSplit[0];
            String password = infoSplit[1];
            infoSplit = hostInfo.split(":");
            String hostIp = infoSplit[0];
            Integer hostPort;
            try {
                hostPort = Integer.parseInt(infoSplit[1]);
            } catch (NumberFormatException nfe) {
                .error("Bad Configuration Data: Failed to parse host port number string: "
                        + infoSplit[1]);
                throw nfe;
            }
            String deviceState = infoSplit[2];
            if (isNullOrEmpty(username) || isNullOrEmpty(password)
                    || isNullOrEmpty(hostIp) || hostPort == 0) {
                .warn("Bad Configuration Data: both user and device information parts of Configuration "
                        + deviceEntry + " should be non-nullable");
            } else {
                device = new NetconfDevice(hostIphostPortusernamepassword);
                if (!isNullOrEmpty(deviceState)) {
                    if (deviceState.toUpperCase().equals(.
                                                                 .name())) {
                        device.setDeviceState(.);
                    } else if (deviceState.toUpperCase()
                            .equals(..name())) {
                        device.setDeviceState(.);
                    } else {
                        .warn("Device State Information can not be empty, so marking the state as INVALID");
                        device.setDeviceState(.);
                    }
                } else {
                    .warn("The device entry do not specify state information, so marking the state as INVALID");
                    device.setDeviceState(.);
                }
            }
        } catch (ArrayIndexOutOfBoundsException aie) {
            .error("Error while reading config infromation from the config file: "
                              + "The user, host and device state infomation should be "
                              + "in the order 'userInfo@hostInfo:deviceState'"
                              + deviceEntryaie);
        } catch (Exception e) {
            .error("Error while parsing config information for the device entry: "
                              + deviceEntrye);
        }
        return device;
    }
    @Override
    public void triggerProbe(DeviceId deviceId) {
        // TODO Auto-generated method stub
    }
    @Override
    public void roleChanged(DeviceId deviceIdMastershipRole newRole) {
    }
    @Override
    public boolean isReachable(DeviceId deviceId) {
        NetconfDevice netconfDevice = .get(deviceId);
        if (netconfDevice == null) {
            .warn("BAD REQUEST: the requested device id: "
                    + deviceId.toString()
                    + "  is not associated to any NETCONF Device");
            return false;
        }
        return netconfDevice.isReachable();
    }

    
This class is intended to add or remove Configured Netconf Devices. Functionality relies on 'createFlag' and 'NetconfDevice' content. The functionality runs as a thread and dependening on the 'createFlag' value it will create or remove Device entry from the core.
    private class DeviceCreator implements Runnable {
        private NetconfDevice device;
        private boolean createFlag;
        public DeviceCreator(NetconfDevice deviceboolean createFlag) {
            this. = device;
            this. = createFlag;
        }
        @Override
        public void run() {
            if () {
                .info("Trying to create Device Info on ONOS core");
                advertiseDevices();
            } else {
                .info("Trying to remove Device Info on ONOS core");
                removeDevices();
            }
        }

        
For each Netconf Device, remove the entry from the device store.
        private void removeDevices() {
            if ( == null) {
                .warn("The Request Netconf Device is null, cannot proceed further");
                return;
            }
            try {
                DeviceId did = getDeviceId();
                if (!.containsKey(did)) {
                    .error("BAD Request: 'Currently device is not discovered, "
                            + "so cannot remove/disconnect the device: "
                            + .deviceInfo() + "'");
                    return;
                }
                .deviceDisconnected(did);
                .disconnect();
                .remove(did);
                delay();
            } catch (URISyntaxException uriSyntaxExcpetion) {
                .error("Syntax Error while creating URI for the device: "
                                  + .deviceInfo()
                                  + " couldn't remove the device from the store",
                          uriSyntaxExcpetion);
            }
        }

        
Initialize Netconf Device object, and notify core saying device connected.
        private void advertiseDevices() {
            try {
                if ( == null) {
                    .warn("The Request Netconf Device is null, cannot proceed further");
                    return;
                }
                .init();
                DeviceId did = getDeviceId();
                ChassisId cid = new ChassisId();
                DeviceDescription desc = new DefaultDeviceDescription(
                                                                      did.uri(),
                                                                      ..,
                                                                      """",
                                                                      """",
                                                                      cid);
                .info("Persisting Device" + did.uri().toString());
                .put(did);
                .deviceConnected(diddesc);
                .info("Done with Device Info Creation on ONOS core. Device Info: "
                        + .deviceInfo() + " " + did.uri().toString());
                delay();
            } catch (URISyntaxException e) {
                .error("Syntax Error while creating URI for the device: "
                        + .deviceInfo()
                        + " couldn't persist the device onto the store"e);
            } catch (SocketTimeoutException e) {
                .error("Error while setting connection for the device: "
                        + .deviceInfo(), e);
            } catch (IOException e) {
                .error("Error while setting connection for the device: "
                        + .deviceInfo(), e);
            } catch (Exception e) {
                .error("Error while initializing session for the device: "
                        + .deviceInfo(), e);
            }
        }

        
This will build a device id for the device.
        private DeviceId getDeviceId() throws URISyntaxException {
            String additionalSSP = new StringBuilder(.getUsername())
                    .append("@").append(.getSshHost()).append(":")
                    .append(.getSshPort()).toString();
            DeviceId did = DeviceId.deviceId(new URI(additionalSSP,
                                                     null));
            return did;
        }
    }
New to GrepCode? Check out our FAQ X