org.onosproject.ospf.controller.impl.Controller.java Source code

Java tutorial

Introduction

Here is the source code for org.onosproject.ospf.controller.impl.Controller.java

Source

/*
 * Copyright 2014-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.ospf.controller.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.onosproject.net.driver.DriverService;
import org.onosproject.ospf.controller.OSPFAgent;
import org.onosproject.ospf.controller.area.Configuration;
import org.onosproject.ospf.controller.area.OSPFArea;
import org.onosproject.ospf.controller.area.OSPFInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Netty server controller which creates ServerBootstrap.
 */
public class Controller {

    protected static final Logger log = LoggerFactory.getLogger(Controller.class);
    protected static final int BUFFER_SIZE = 4 * 1024 * 1024;
    // Configuration options
    private static final String CONFIG_DIR = "/home/sdn/onos/resources";
    private static final String DEFAULT_CONFIG_FILE = "area-config.json";
    protected int ospfPort = 7000;
    protected int workerThreads = 16;
    // start time of the controller
    protected long systemStartTime;
    private String configFileName = DEFAULT_CONFIG_FILE;
    private OSPFAgent agent;
    private ChannelGroup cg;
    private List<NioServerSocketChannelFactory> execFactoryLst = new ArrayList<>();
    private DriverService driverService;
    private OSPFInterface interfc = null;

    //For testing out of ONOS purpose.
    //.........................
    public static void main(String[] args) {
        log.debug("Controller::Starting the Netty Server..");
        Controller ctl = new Controller();
        ctl.run();
    }

    //for testing need to remove.
    public OSPFInterface getInterface() {
        return interfc;
    }

    /**
     * Tell controller that we're ready to handle channels.
     */
    public void run() {
        try {
            //get the configuration from json file
            List<OSPFArea> areas = getConfiguration();
            //get the connected interfaces
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            // Check NetworkInterfaces and area-config have same IP Address
            for (NetworkInterface netInt : Collections.list(nets)) {
                // if the interface is up & not loopback
                if (!netInt.isUp() && !netInt.isLoopback()) {
                    continue;
                }
                //get all the InetAddresses
                Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    String ipAddress = inetAddress.getHostAddress();
                    //Search for the address in all configured areas interfaces
                    for (OSPFArea area : areas) {
                        for (OSPFInterface ospfIf : area.getInterfacesLst()) {
                            String ipFromConfig = ospfIf.getIpAddress();
                            if (ipFromConfig.trim().equals(ipAddress.trim())) {
                                log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress,
                                        area.getAreaID());
                                // if same IP address create
                                try {
                                    log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort);

                                    final ServerBootstrap bootstrap = createServerBootStrap();
                                    bootstrap.setOption("reuseAddr", true);
                                    bootstrap.setOption("child.keepAlive", true);
                                    bootstrap.setOption("child.tcpNoDelay", true);
                                    bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);

                                    //Set the interface name in ospfInterface
                                    ospfIf.setInterfaceName(netInt.getDisplayName());
                                    //netInt.get
                                    // passing OSPFArea and interface to pipelinefactory
                                    ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area,
                                            ospfIf);
                                    bootstrap.setPipelineFactory(pfact);
                                    InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress),
                                            ospfPort);

                                    cg = new DefaultChannelGroup();
                                    cg.add(bootstrap.bind(sa));

                                    log.debug("Listening for connections on {}", sa);
                                    //For testing. remove this
                                    interfc = ospfIf;

                                    //Start aging process
                                    area.initializeDB();
                                    area.initializeArea();
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("Error::Controller:: {}", e.getMessage());
        }
    }

    /**
     * Get the area configuration from a json file.
     *
     * @return areas List<OSPFArea>
     */
    private List getConfiguration() {
        List<OSPFArea> areas = null;
        try {
            // Read network configuration from area-config.json
            // read the configuration area wise .
            File configFile = new File(CONFIG_DIR, configFileName);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(configFile);
            Configuration config = mapper.treeToValue(node, Configuration.class);
            log.debug("OSPF area Configuration : {}", config);
            areas = config.getOspfAreas();
            return areas;

        } catch (Exception e) {
            log.debug("Error::Controller:: {}", e.getMessage());
            return areas;
        }

    }

    /**
     * Create a server bootstrap.
     *
     * @return ServerBootstrap
     */
    private ServerBootstrap createServerBootStrap() {

        Executor bossPool = Executors.newCachedThreadPool();
        Executor workerPool = Executors.newCachedThreadPool();
        NioServerSocketChannelFactory executerFactory;
        if (workerThreads == 0) {
            executerFactory = new NioServerSocketChannelFactory(bossPool, workerPool);
            execFactoryLst.add(executerFactory);
        } else {
            executerFactory = new NioServerSocketChannelFactory(bossPool, workerPool, workerThreads);
            execFactoryLst.add(executerFactory);
        }
        return new ServerBootstrap(executerFactory);
    }

    /**
     * Initialize internal data structures.
     */
    public void init() {

        this.systemStartTime = System.currentTimeMillis();
    }

    // **************
    // Utility methods
    // **************

    public Map<String, Long> getMemory() {
        Map<String, Long> m = new HashMap<>();
        Runtime runtime = Runtime.getRuntime();
        m.put("total", runtime.totalMemory());
        m.put("free", runtime.freeMemory());
        return m;
    }

    /**
     * get the up time.
     *
     * @return rb.getUptime
     */
    public Long getUptime() {
        RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
        return rb.getUptime();
    }

    /**
     * Start the controller.
     *
     * @param ag
     * @param driverService
     */
    public void start(OSPFAgent ag, DriverService driverService) {
        log.info("Starting OSPF Controller...!!!");
        this.agent = ag;
        this.driverService = driverService;
        this.init();
        this.run();
    }

    /**
     * Stop the Controller.
     */
    public void stop() {
        log.info("Stopping OSPF Controller...!!!");
        cg.close();
        for (NioServerSocketChannelFactory execFactory : execFactoryLst) {
            execFactory.shutdown();
        }
    }

}