package org.freertr.serv;

import java.util.ArrayList;
import java.util.List;
import org.freertr.addr.addrIP;
import org.freertr.addr.addrPrefix;
import org.freertr.cfg.cfgAll;
import org.freertr.cfg.cfgBrdg;
import org.freertr.cfg.cfgIfc;
import org.freertr.ifc.ifcBridgeIfc;
import org.freertr.ifc.ifcEthTyp;
import org.freertr.ip.ipFwdIface;
import org.freertr.ip.ipIfcLoop;
import org.freertr.pack.packHolder;
import org.freertr.pipe.pipeLine;
import org.freertr.pipe.pipeSide;
import org.freertr.prt.prtGenConn;
import org.freertr.prt.prtServS;
import org.freertr.spf.spfCalc;
import org.freertr.tab.tabGen;
import org.freertr.tab.tabLabel;
import org.freertr.tab.tabLabelBierN;
import org.freertr.tab.tabLabelEntry;
import org.freertr.tab.tabRoute;
import org.freertr.tab.tabRouteEntry;
import org.freertr.tab.tabRouteIface;
import org.freertr.user.userFilter;
import org.freertr.user.userFormat;
import org.freertr.user.userHelp;
import org.freertr.util.bits;
import org.freertr.util.cmds;
import org.freertr.util.logger;

/**
 * stack handler
 *
 * @author matecsaba
 */
public class servStack extends servGeneric implements prtServS, servGenFwdr {

    /**
     * create instance
     */
    public servStack() {
        fwds = new ArrayList<servStackFwd>();
        bckplnLab = new tabLabelEntry[0];
        dscvry = new servStackDisc(this);
    }

    /**
     * convert forwarder id to address
     *
     * @param i id
     * @return address
     */
    protected final static addrIP forwarder2addr(int i) {
        addrIP adr = new addrIP();
        byte[] buf = adr.getBytes();
        bits.msbPutD(buf, 0, 0xfe800bad);
        bits.msbPutD(buf, buf.length - 4, i + 1);
        return adr;
    }

    /**
     * convert address to forwarder id
     *
     * @param adr address
     * @return id
     */
    protected final static int addr2forwarder(addrIP adr) {
        byte[] buf = adr.getBytes();
        return bits.msbGetD(buf, buf.length - 4) - 1;
    }

    /**
     * convert forwarder id to address
     *
     * @param i id
     * @return address
     */
    protected final static tabRouteEntry<addrIP> forwarder2route(int i) {
        addrIP adr = forwarder2addr(i);
        tabRouteEntry<addrIP> rou = new tabRouteEntry<addrIP>();
        rou.prefix = new addrPrefix<addrIP>(adr, addrIP.size * 8);
        return rou;
    }

    /**
     * port
     */
    public final static int port = 9080;

    /**
     * discovery timer
     */
    protected servStackDisc dscvry;

    /**
     * buffer size
     */
    protected int bufSiz = 65536;

    /**
     * discovery interval
     */
    protected int discoInt = 1000;

    /**
     * discovery timeout
     */
    protected int discoTim = 5000;

    /**
     * forwarders
     */
    protected final List<servStackFwd> fwds;

    /**
     * topology version
     */
    protected int vers;

    /**
     * label base
     */
    protected int labelBase;

    /**
     * advertisement base
     */
    protected addrIP advertBase;

    /**
     * backplane
     */
    protected tabLabelEntry[] bckplnLab;

    /**
     * random id
     */
    protected int randId;

    /**
     * defaults text
     */
    public final static userFilter[] defaultF = {
        new userFilter("server stack .*", cmds.tabulator + "port " + port, null),
        new userFilter("server stack .*", cmds.tabulator + "protocol " + proto2string(protoAllStrm), null),
        new userFilter("server stack .*", cmds.tabulator + "buffer 65536", null),
        new userFilter("server stack .*", cmds.tabulator + "dataplanes 0", null),
        new userFilter("server stack .*", cmds.tabulator + "label-base 0", null),
        new userFilter("server stack .*", cmds.tabulator + "advert-base null", null),
        new userFilter("server stack .*", cmds.tabulator + "discovery 1000 5000", null)
    };

    public userFilter[] srvDefFlt() {
        return defaultF;
    }

    public void srvShRun(String beg, List<String> lst, int filter) {
        lst.add(beg + "dataplanes " + fwds.size());
        lst.add(beg + "label-base " + labelBase);
        lst.add(beg + "advert-base " + advertBase);
        lst.add(beg + "discovery " + discoInt + " " + discoTim);
        for (int i = 0; i < fwds.size(); i++) {
            lst.add(beg + cmds.comment);
            servStackFwd ntry = fwds.get(i);
            ntry.getShowRun(beg, "forwarder " + i + cmds.tabulator, lst);
        }
        lst.add(beg + cmds.comment);
    }

    public boolean srvCfgStr(cmds cmd) {
        String s = cmd.word();
        boolean neg = s.equals(cmds.negated);
        if (neg) {
            s = cmd.word();
        }
        if (s.equals("buffer")) {
            bufSiz = bits.str2num(cmd.word());
            return false;
        }
        if (s.equals("discovery")) {
            discoInt = bits.str2num(cmd.word());
            discoTim = bits.str2num(cmd.word());
            return false;
        }
        if (s.equals("advert-base")) {
            advertBase = new addrIP();
            advertBase.fromString(cmd.word());
            if (neg) {
                advertBase = null;
            }
            restartDiscovery(true);
            return false;
        }
        if (s.equals("label-base")) {
            labelBase = bits.str2num(cmd.word());
            restartDiscovery(true);
            return false;
        }
        if (s.equals("dataplanes")) {
            int ned = bits.str2num(cmd.word());
            if (neg) {
                ned = 1;
            }
            if (ned < 1) {
                ned = 1;
            }
            for (int i = fwds.size(); i < ned; i++) {
                fwds.add(new servStackFwd(this));
            }
            for (int i = fwds.size() - 1; i >= ned; i--) {
                servStackFwd cur = fwds.remove(i);
            }
            for (int i = 0; i < fwds.size(); i++) {
                servStackFwd cur = fwds.get(i);
                cur.id = i;
            }
            restartDiscovery(true);
            return false;
        }
        if (!s.equals("forwarder")) {
            return true;
        }
        int i = bits.str2num(cmd.word());
        if ((i < 0) || (i >= fwds.size())) {
            cmd.error("bad forwarder number");
            return true;
        }
        servStackFwd cur = fwds.get(i);
        s = cmd.word();
        if (s.equals("remote")) {
            cur.remote.fromString(cmd.word());
            return false;
        }
        if (s.equals("p4lang")) {
            cur.of = null;
            if (neg) {
                cur.p4 = null;
                return false;
            }
            servP4lang f = cfgAll.srvrFind(new servP4lang(), cfgAll.dmnP4lang, cmd.word());
            cur.p4 = f;
            if (f == null) {
                return true;
            }
            f.parent = this;
            f.parid = cur;
            return false;
        }
        if (s.equals("openflow")) {
            cur.p4 = null;
            if (neg) {
                cur.of = null;
                return false;
            }
            servOpenflow f = cfgAll.srvrFind(new servOpenflow(), cfgAll.dmnOpenflow, cmd.word());
            cur.of = f;
            if (f == null) {
                return true;
            }
            f.parent = this;
            f.parid = cur;
            return false;
        }
        if (s.equals("backplane")) {
            cfgIfc rif = getBckIfc(cur, cmd);
            if (rif == null) {
                return false;
            }
            servStackIfc ntry = new servStackIfc(cur, rif);
            if (neg) {
                ntry = cur.ifaces.del(ntry);
                if (ntry == null) {
                    cmd.error("no such backplane");
                    return false;
                }
                ntry.stopWork();
                cur.reindex();
                return false;
            }
            ntry.ifc = rif.ethtyp;
            ntry.ifc.addET(-1, "stack", ntry);
            ntry.ifc.updateET(-1, ntry);
            ntry.parent.setFilter(true);
            ntry.metric = bits.str2num(cmd.word());
            servStackIfc old = cur.ifaces.put(ntry);
            cur.reindex();
            if (old == null) {
                return false;
            }
            old.stopWork();
            return false;
        }
        if (s.equals("backroute")) {
            cfgIfc rif = getBckIfc(cur, cmd);
            if (rif == null) {
                return false;
            }
            servStackIfc ntry = new servStackIfc(cur, rif);
            if (neg) {
                ntry = cur.ifaces.del(ntry);
                if (ntry == null) {
                    cmd.error("no such backroute");
                    return false;
                }
                ntry.stopWork();
                cur.reindex();
                return false;
            }
            ntry.ifc = rif.ethtyp;
            ntry.metric = bits.str2num(cmd.word());
            ntry.bgpAdr = new addrIP();
            if (ntry.bgpAdr.fromString(cmd.word())) {
                cmd.error("bad address");
                return false;
            }
            ntry.bgpAsn = bits.str2num(cmd.word());
            if (ntry.bgpAsn == 0) {
                cmd.error("bad asn");
                return false;
            }
            ntry.startWork();
            servStackIfc old = cur.ifaces.put(ntry);
            cur.reindex();
            if (old == null) {
                return false;
            }
            old.stopWork();
            return false;
        }
        return true;
    }

    private cfgIfc getBckIfc(servStackFwd cur, cmds cmd) {
        cfgIfc rif = cfgAll.ifcFind(cmd.word(), 0);
        if (rif == null) {
            cmd.error("no such interface");
            return null;
        }
        if (cur.findIfc(rif.ethtyp)) {
            return rif;
        }
        if (rif.vlanNum == 0) {
            cmd.error("port not exported");
            return null;
        }
        if (!cur.findIfc(rif.parent.ethtyp)) {
            cmd.error("parent not exported");
            return null;
        }
        return rif;
    }

    public void srvHelp(userHelp l) {
        l.add(null, false, 1, new int[]{2}, "buffer", "set buffer size on connection");
        l.add(null, false, 2, new int[]{-1}, "<num>", "buffer in bytes");
        l.add(null, false, 1, new int[]{2}, "label-base", "set label of forwarders");
        l.add(null, false, 2, new int[]{-1}, "<num>", "label");
        l.add(null, false, 1, new int[]{2}, "advert-base", "set advertisement of forwarders");
        l.add(null, false, 2, new int[]{-1}, "<addr>", "address");
        l.add(null, false, 1, new int[]{2}, "dataplanes", "set number of forwarders");
        l.add(null, false, 2, new int[]{-1}, "<num>", "limit");
        l.add(null, false, 1, new int[]{2}, "discovery", "specify discovery parameters");
        l.add(null, false, 2, new int[]{3}, "<num>", "keepalive in ms");
        l.add(null, false, 3, new int[]{-1}, "<num>", "timeout in ms");
        l.add(null, false, 1, new int[]{2}, "forwarder", "specify forwarder parameters");
        l.add(null, false, 2, new int[]{3}, "<num>", "keepalive in ms");
        l.add(null, false, 3, new int[]{4}, "p4lang", "use p4lang dataplane");
        l.add(cfgAll.dmnP4lang.listServers(), false, 4, new int[]{-1}, "<name:loc>", "name of server");
        l.add(null, false, 3, new int[]{4}, "openflow", "use openflow dataplane");
        l.add(cfgAll.dmnOpenflow.listServers(), false, 4, new int[]{-1}, "<name:loc>", "name of server");
        l.add(null, false, 3, new int[]{4}, "remote", "address of remote");
        l.add(null, false, 4, new int[]{-1}, "<adr>", "address");
        l.add(null, false, 3, new int[]{4}, "backplane", "interface to use");
        l.add(null, false, 4, new int[]{5}, "<name:ifc>", "name of interface");
        l.add(null, false, 5, new int[]{-1}, "<num>", "metric of port");
        l.add(null, false, 3, new int[]{4}, "backroute", "interface to use");
        l.add(null, false, 4, new int[]{5}, "<name:ifc>", "name of interface");
        l.add(null, false, 5, new int[]{6}, "<num>", "metric of port");
        l.add(null, false, 6, new int[]{7}, "<addr>", "peer address");
        l.add(null, false, 7, new int[]{-1}, "<num>", "local as number");
    }

    public String srvName() {
        return "stack";
    }

    public int srvPort() {
        return port;
    }

    public int srvProto() {
        return protoAllStrm;
    }

    public boolean srvInit() {
        restartDiscovery(true);
        return genStrmStart(this, new pipeLine(bufSiz, false), 0);
    }

    public boolean srvDeinit() {
        restartDiscovery(false);
        return genericStop(0);
    }

    public boolean srvAccept(pipeSide pipe, prtGenConn id) {
        servStackFwd cur = null;
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            if (ntry.remote.compareTo(id.peerAddr) != 0) {
                continue;
            }
            cur = ntry;
            break;
        }
        if (cur == null) {
            logger.error("dropping unknown forwarder " + id);
            return true;
        }
        if (cur.p4 != null) {
            return cur.p4.srvDoAcc(pipe, id);
        }
        if (cur.of != null) {
            return cur.of.srvDoAcc(pipe, id);
        }
        return true;
    }

    /**
     * get hardware forwarder
     *
     * @return offload info
     */
    public String getShGenOneLiner() {
        String a = "stack";
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd fwd = fwds.get(i);
            a += "," + fwd.getShGetName();
        }
        return a;
    }

    public boolean send2apiPack(int cntr, int ifcn, packHolder pck) {
        return false;
    }

    private void restartDiscovery(boolean need) {
        dscvry.need2work = false;
        dscvry = new servStackDisc(this);
        tabLabel.release(bckplnLab, tabLabelEntry.owner.stack);
        if (fwds.size() < 1) {
            return;
        }
        if (need) {
            bckplnLab = tabLabel.allocateBlock(tabLabelEntry.owner.stack, labelBase, fwds.size());
        }
        if (srvVrf != null) {
            for (int i = 0; i < bckplnLab.length; i++) {
                bckplnLab[i].setFwdCommon(tabLabelEntry.owner.stack, srvVrf.fwd6);
            }
        }
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd cur = fwds.get(i);
            cur.spf = new spfCalc<addrIP>(null);
        }
        doCalc();
        if (!need) {
            return;
        }
        dscvry.startWork();
    }

    /**
     * send keepalives and check if spf needed
     *
     * @return true if changed, false if not
     */
    protected boolean doRound() {
        long tim = bits.getTime();
        boolean chg = false;
        for (int o = 0; o < fwds.size(); o++) {
            servStackFwd cur = fwds.get(o);
            cur.usables = 0;
            for (int i = 0; i < cur.ifaces.size(); i++) {
                servStackIfc ntry = cur.ifaces.get(i);
                boolean res = ntry.getState() > tim;
                if (res) {
                    cur.usables++;
                }
                if (ntry.ready == res) {
                    continue;
                }
                ntry.changed = tim;
                ntry.ready = res;
                chg = true;
            }
        }
        return chg;
    }

    /**
     * calculate spf
     */
    protected void doCalc() {
        vers++;
        servStackFwd cur = fwds.get(0);
        spfCalc<addrIP> spf = new spfCalc<addrIP>(cur.spf);
        boolean sawNet = false;
        for (int o = 0; o < fwds.size(); o++) {
            cur = fwds.get(o);
            addrIP adr = forwarder2addr(o);
            for (int i = 0; i < cur.ifaces.size(); i++) {
                servStackIfc ntry = cur.ifaces.get(i);
                if (!ntry.ready) {
                    continue;
                }
                if (ntry.bgpAdr == null) {
                    addrIP nei = forwarder2addr(ntry.lastFwdr.id);
                    spf.addConn(adr, nei, ntry.metric, true, false, "prt" + ntry.id);
                    continue;
                }
                sawNet = true;
                addrIP nei = forwarder2addr(-2);
                spf.addConn(adr, nei, ntry.metric, true, false, "prt" + ntry.id);
                spf.addConn(nei, adr, ntry.metric, true, false, "per" + ntry.bgpAdr);
            }
            tabRouteEntry<addrIP> rou = forwarder2route(o);
            spf.addPref(adr, rou, false);
            spf.addIdent(adr, "fwd" + o);
        }
        if (sawNet) {
            addrIP adr = forwarder2addr(-2);
            tabRouteEntry<addrIP> rou = forwarder2route(-2);
            spf.addPref(adr, rou, false);
            spf.addIdent(adr, "net");
        }
        spf.bidir.set(1);
        cur = fwds.get(0);
        cur.spf = spf;
        for (int o = 1; o < fwds.size(); o++) {
            cur = fwds.get(o);
            cur.spf = spf.copyBytes();
        }
        for (int o = 0; o < fwds.size(); o++) {
            cur = fwds.get(o);
            addrIP adr = forwarder2addr(o);
            cur.spf.doWork(adr);
            for (int i = 0; i < cur.ifaces.size(); i++) {
                servStackIfc ntry = cur.ifaces.get(i);
                if (!ntry.ready) {
                    continue;
                }
                addrIP nei;
                if (ntry.bgpAdr == null) {
                    nei = forwarder2addr(ntry.lastFwdr.id);
                } else {
                    nei = forwarder2addr(-2);
                }
                ipIfcLoop ipi = new ipIfcLoop();
                ipi.myName = "" + ntry;
                ipFwdIface ifc = new ipFwdIface(ntry.id, ipi);
                ipi.setUpper(null, ifc);
                cur.spf.addNextHop(ntry.metric, nei, nei, ifc, null, null);
            }
            cur.routes = cur.spf.getRoutes(null, null, null, null);
        }
        for (int o = 0; o < fwds.size(); o++) {
            cur = fwds.get(o);
            if (cur.p4 != null) {
                cur.p4.notif.wakeup();
            }
            if (cur.of != null) {
                cur.of.notif.wakeup();
            }
        }
    }

    /**
     * merge bier forwarders
     *
     * @param who querier
     * @param fwd forwarders
     * @param src source interface
     * @return merged forwarders
     */
    public tabGen<tabLabelBierN> mergeBier(servStackFwd who, tabGen<tabLabelBierN> fwd, ipFwdIface src) {
        tabGen<tabLabelBierN> res = new tabGen<tabLabelBierN>();
        addrIP sou = new addrIP();
        servStackFwd oth = findIfc(who, src);
        if (oth != null) {
            tabRouteEntry<addrIP> oru = forwarder2route(oth.id);
            oru = who.routes.find(oru);
            if (oru != null) {
                sou = oru.best.nextHop.copyBytes();
            }
        }
        for (int i = 0; i < fwd.size(); i++) {
            tabLabelBierN ntry = fwd.get(i);
            if (ntry == null) {
                continue;
            }
            oth = findIfc(who, ntry.iface);
            if (oth == null) {
                continue;
            }
            tabRouteEntry<addrIP> oru = forwarder2route(oth.id);
            oru = who.routes.find(oru);
            if (oru == null) {
                continue;
            }
            if (sou.compareTo(oru.best.nextHop) == 0) {
                continue;
            }
            tabLabelBierN curr = new tabLabelBierN(ntry.fwd, oru.best.iface, oru.best.nextHop, 0, ntry.vpnlab);
            tabLabelBierN old = res.find(curr);
            if (old != null) {
                old.mergeNed(ntry.ned);
                continue;
            }
            curr.mergeNed(ntry.ned);
            res.add(curr);
        }
        return res;
    }

    /**
     * merge bier forwarders
     *
     * @param who querier
     * @param fwd forwarders
     * @param src source interface
     * @return merged forwarders
     */
    public tabGen<addrIP> mergeMcast(servStackFwd who, tabGen<ipFwdIface> fwd, ipFwdIface src) {
        tabGen<addrIP> res = new tabGen<addrIP>();
        addrIP sou = new addrIP();
        servStackFwd oth = findIfc(who, src);
        if (oth != null) {
            tabRouteEntry<addrIP> oru = forwarder2route(oth.id);
            oru = who.routes.find(oru);
            if (oru != null) {
                sou = oru.best.nextHop.copyBytes();
            }
        }
        for (int i = 0; i < fwd.size(); i++) {
            ipFwdIface ntry = fwd.get(i);
            if (ntry == null) {
                continue;
            }
            oth = findIfc(who, ntry);
            if (oth == null) {
                continue;
            }
            tabRouteEntry<addrIP> oru = forwarder2route(oth.id);
            oru = who.routes.find(oru);
            if (oru == null) {
                continue;
            }
            if (sou.compareTo(oru.best.nextHop) == 0) {
                continue;
            }
            res.add(oru.best.nextHop);
        }
        return res;
    }

    /**
     * find interface
     *
     * @param who querier
     * @param ifc interface
     * @return owner, null if error
     */
    protected servStackFwd findIfc(servStackFwd who, cfgBrdg ifc) {
        if (ifc == null) {
            return null;
        }
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            if (ntry.id == who.id) {
                continue;
            }
            if (ntry.findIfc(ifc)) {
                return ntry;
            }
        }
        return null;
    }

    /**
     * find interface
     *
     * @param who querier
     * @param ifc interface
     * @return owner, null if error
     */
    protected servStackFwd findIfc(servStackFwd who, ifcBridgeIfc ifc) {
        if (ifc == null) {
            return null;
        }
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            if (ntry.id == who.id) {
                continue;
            }
            if (ntry.findIfc(ifc)) {
                return ntry;
            }
        }
        return null;
    }

    /**
     * find interface
     *
     * @param who querier
     * @param ifc interface
     * @return owner, null if error
     */
    protected servStackFwd findIfc(servStackFwd who, tabRouteIface ifc) {
        if (ifc == null) {
            return null;
        }
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            if (ntry.id == who.id) {
                continue;
            }
            if (ntry.findIfc(ifc)) {
                return ntry;
            }
        }
        return null;
    }

    /**
     * find interface
     *
     * @param who querier
     * @param ifc interface
     * @return owner, null if error
     */
    protected servStackFwd findIfc(servStackFwd who, ifcEthTyp ifc) {
        if (ifc == null) {
            return null;
        }
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            if (ntry.id == who.id) {
                continue;
            }
            if (ntry.findIfc(ifc)) {
                return ntry;
            }
        }
        return null;
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @return show
     */
    public userFormat getShowPorts(int fwd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return null;
        }
        servStackFwd cur = fwds.get(fwd);
        userFormat res = new userFormat("|", "id|port|metric|ready|remote|peering|neighbor|trgmac|changed");
        for (int i = 0; i < cur.ifaces.size(); i++) {
            servStackIfc ntry = cur.ifaces.get(i);
            res.add(ntry.getShPorts());
        }
        return res;
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @param prt port id
     * @return show
     */
    public tabRoute<addrIP> getShowAdvert(int fwd, int prt) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return new tabRoute<addrIP>("bp");
        }
        servStackFwd cur = fwds.get(fwd);
        servStackIfc ntry = cur.ifaces.get(prt);
        if (ntry == null) {
            return new tabRoute<addrIP>("bp");
        }
        if (ntry.bgpDon == null) {
            return new tabRoute<addrIP>("bp");
        }
        return ntry.bgpDon;
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @return show
     */
    public userFormat getShowSpf(int fwd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return null;
        }
        servStackFwd cur = fwds.get(fwd);
        return cur.spf.listStatistics();
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @param cmd masks
     * @return show
     */
    public userFormat getShowTopo(int fwd, cmds cmd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return null;
        }
        servStackFwd cur = fwds.get(fwd);
        return cur.spf.listTopology(new addrIP(), cmd);
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @param cmd masks
     * @return show
     */
    public List<String> getShowTree(int fwd, cmds cmd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return null;
        }
        servStackFwd cur = fwds.get(fwd);
        return cur.spf.listTree(cmd);
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @param cmd masks
     * @return show
     */
    public List<String> getShowGraph(int fwd, cmds cmd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return null;
        }
        servStackFwd cur = fwds.get(fwd);
        return cur.spf.listGraph(cmd);
    }

    /**
     * get backplane show
     *
     * @param fwd forwarder
     * @return show
     */
    public tabRoute<addrIP> getShowRoute(int fwd) {
        if ((fwd < 0) || (fwd >= fwds.size())) {
            return new tabRoute<addrIP>("bp");
        }
        servStackFwd cur = fwds.get(fwd);
        return cur.routes;
    }

    /**
     * get generic show
     *
     * @return show
     */
    public userFormat getShowBcks() {
        userFormat res = new userFormat("|", "fwd|name|addr|iface|usable|routes|oneliner");
        for (int i = 0; i < fwds.size(); i++) {
            servStackFwd ntry = fwds.get(i);
            res.add(i + "|" + ntry.getShGetName() + "|" + ntry.remote + "|" + ntry.ifaces.size() + "|" + ntry.usables + "|" + ntry.routes.size() + "|" + ntry.getShGet1liner());
        }
        return res;
    }

}

class servStackDisc implements Runnable {

    public boolean need2work = true;

    private final servStack lower;

    public servStackDisc(servStack parent) {
        lower = parent;
    }

    public void startWork() {
        lower.randId = bits.randomD();
        logger.startThread(this);
    }

    public void run() {
        for (;;) {
            if (!need2work) {
                break;
            }
            try {
                if (lower.doRound()) {
                    lower.doCalc();
                    logger.info("recalculated backplane");
                }
            } catch (Exception e) {
                logger.traceback(e);
            }
            bits.sleep(lower.discoInt);
        }
    }

}
