Exemplo n.º 1
0
def IssueProbe(pkt, rules, v1, v2):
    global postCardQueue
    global Pid
    while not postCardQueue.empty():
        postCardQueue.get()
    pkt['pid'] = Pid
    Pid += 1
    #print "send: ",Pid-1,
    #print "%.16f" % time.time()
    sender.send(pkt)
    TimeLog.GetInstance().addPacket()
    try:
        card = postCardQueue.get(True, TIME_WAIT)
    except Exception:
        TimeLog.GetInstance().clock()
        return -1
    pid = card[0]
    rid = card[1]
    #print "recv: ",pid,"%.16f" % time.time()
    #print "pid,rid",pid,rid,"v1,v2",v1,v2
    return int(rid)
    if random.randint(0, 1) == 0:
        return v1
    else:
        return v2
    for rule in rules:
        return rule
Exemplo n.º 2
0
def IssueProbeSet(pkts):
    #print "#",len(pkts)
    global postCardQueue
    while not postCardQueue.empty():
        postCardQueue.get()
    hits = {}
    for pkt in pkts:
        sender.send(pkts[pkt])
        hits[pkt] = -1
    TimeLog.GetInstance().addPackets(len(pkts))
    if len(pkts) == 0:
        return hits
    while True:
        try:
            TimeLog.GetInstance().addSend()
            card = postCardQueue.get(True, TIME_WAIT)
        except Exception:
            TimeLog.GetInstance().clock()
            #pid = card[0]
            #rid = card[1]
            #hits[pid] = rid
            return hits
        pid = card[0]
        rid = card[1]
        hits[pid] = rid
Exemplo n.º 3
0
def pktGenerator(pos, rule_list, rule_dict, types, intersect, log):
    if intersect == None:
        return []

    intersect = copy.deepcopy(intersect)
    log = copy.deepcopy(log)
    ret = []

    if pos >= len(rule_list):
        #print "log = ",log
        #print "intersect",intersect
        if len(log) <= 0:
            return ret
        header_space = []
        for v in [v for v in rule_list if v not in log]:
            header_space.append(rule_dict[v])
        TimeLog.GetInstance().addTotal()
        pkt = solver.createPacket(intersect, header_space, types)
        TimeLog.GetInstance().addSolver()
        if pkt['SAT'] == 'Yes':
            ret.append((log, pkt))
        return ret
    #for i in range(pos,len(rule_list)):
    i = pos
    cur = pktGenerator(i + 1, rule_list, rule_dict, types, intersect, log)
    ret += cur

    intersect = header.intersect_molecule(intersect, rule_dict[rule_list[i]])
    #print intersect
    if intersect != None:
        log.append(rule_list[i])
        cur = pktGenerator(i + 1, rule_list, rule_dict, types, intersect, log)
        ret += cur
    return ret
Exemplo n.º 4
0
def dagCompare(edge_dict, rule_list, VV, EE):

    TimeLog.GetInstance().addTotal()

    V = rule_list.keys()
    E = []
    for v1 in edge_dict:
        for v2 in edge_dict[v1]:
            E.append([v2, v1])

    #print V
    #print E

    #print VV
    #print EE

    if len(VV) != len(V):
        return False
    if len([val for val in V if val not in VV]) > 0:
        return False

    #equality for two graph.
    h = {}
    for i, k in enumerate(V):
        h[k] = i
    G1 = [[0] * len(V) for i in range(len(V))]
    for edge in E:
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G1[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G1[i][k] == 1 and G1[k][j] == 1:
                    G1[i][j] = 1
    G2 = [[0] * len(V) for i in range(len(V))]
    for edge in EE:
        #print h
        #print edge
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G2[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G2[i][k] == 1 and G2[k][j] == 1:
                    G2[i][j] = 1
    ret = True
    for i in range(len(V)):
        if ret == False:
            break
        for j in range(len(V)):
            if G1[i][j] != G2[i][j]:
                ret = False
                break
    TimeLog.GetInstance().clock()
    return ret
Exemplo n.º 5
0
def launcherF(dag_file, pre_file):

    #set the log mode
    #logging.basicConfig(level=logging.DEBUG)
    #logging.basicConfig(level=logging.INFO)
    #logging.basicConfig(level=logging.WARNING)
    logging.basicConfig(level=logging.WARNING)
    #logging.basicConfig(level=logging.ERROR)

    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(dag_file)
    pcg.start()

    #collect postcard
    #post = PostCardProcessor('s1-eth4')
    #post.start()
    PostCardProcessor.Start()
    time.sleep(1)
    #logging.info("1# start to collect %.8f" %time.time())

    #start to generate packets
    from timelog import TimeLog
    TimeLog.GetInstance().reset()

    import parser, IncrFullAdap
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file);
    rule_lists,edge_dicts = parser.DAGLoader(pre_file)

    table = []
    for i in rule_list.keys():
        for j in rule_lists.keys():
            ret = cmp(rule_list[i], rule_lists[j])
            if ret == 0:
                #print rule_list[i]
                #print rule_lists[j]
                table.append(i)
    #print len(table),table

    TimeLog.GetInstance().clock()
    flag = IncrFullAdap.packetGenerator(edge_dict, rule_list, types, postCardQueue, table)
    TimeLog.GetInstance().addTotal()
    if flag == False:
        print "Failed!",TimeLog.GetInstance().getCost()
    elif flag == True:
        print "Success!",TimeLog.GetInstance().getCost()
    else:
        print "Unexpected!",TimeLog.GetInstance().getCost()
    Flag = False
    time.sleep(0.1)
    return flag,TimeLog.GetInstance().getCost()
Exemplo n.º 6
0
def launcherG(dag_file, pre_file):
    logging.basicConfig(level=logging.WARNING)

    from timelog import TimeLog
    TimeLog.GetInstance().reset()
    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(dag_file)
    pcg.start()

    PostCardProcessor.Start()
    time.sleep(1)

    #start to generate packets

    import parser, IncrSemiAdap
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file);
    rule_lists,edge_dicts = parser.DAGLoader(pre_file)

    table = []
    tbN = []
    hs = {}
    for i in rule_list.keys():
        for j in rule_lists.keys():
            ret = cmp(rule_list[i], rule_lists[j])
            if ret == 0:
                #print rule_list[i]
                #print rule_lists[j]
                table.append(i)
                if not j in tbN:
                    tbN.append(j)
                    hs[j] = i
    #print table
    edges_pre = []
    for i in edge_dicts.keys():
        if not i in tbN:
            continue
        for j in edge_dicts[i]:
            if not j in tbN:
                continue
            edges_pre.append([hs[i], hs[j]])

    TimeLog.GetInstance().clock()
    flag = IncrSemiAdap.packetGenerator(edge_dict, rule_list, types, postCardQueue, table, edges_pre)
    if flag == False:
        print "Failed!",TimeLog.GetInstance().getCost()
    elif flag == True:
        print "Success!",TimeLog.GetInstance().getCost()
    else:
        print "Unexpected!",TimeLog.GetInstance().getCost()
    Flag = False
    time.sleep(0.1)
    return flag,TimeLog.GetInstance().getCost()
Exemplo n.º 7
0
def launcherC(dag_file):

    #set the log mode
    #logging.basicConfig(level=logging.DEBUG)
    #logging.basicConfig(level=logging.INFO)
    #logging.basicConfig(level=logging.WARNING)
    logging.basicConfig(level=logging.WARNING)
    #logging.basicConfig(level=logging.ERROR)

    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(dag_file)
    pcg.start()

    #collect postcard
    #post = PostCardProcessor('s1-eth4')
    #post.start()
    PostCardProcessor.Start()
    time.sleep(1)
    #logging.info("1# start to collect %.8f" %time.time())

    #start to generate packets
    from timelog import TimeLog
    TimeLog.GetInstance().reset()
    TimeLog.GetInstance().clock()

    import parser, FullAdap
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file);
    flag = FullAdap.packetGenerator(edge_dict, rule_list, types, postCardQueue)
    TimeLog.GetInstance().addTotal()
    if flag == False:
        print "Failed!",TimeLog.GetInstance().getCost()
    elif flag == True:
        print "Success!",TimeLog.GetInstance().getCost()
    else:
        print "Unexpected!",TimeLog.GetInstance().getCost()
    Flag = False
    time.sleep(0.1)
    return flag,TimeLog.GetInstance().getCost()
Exemplo n.º 8
0
def packetGenerator(edge_dict, rule_list, types, q, table):
    global postCardQueue
    postCardQueue = q

    global Pid
    Pid = 0

    TimeLog.GetInstance().addTotal()

    V = rule_list.keys()
    E = []
    for v1 in edge_dict:
        for v2 in edge_dict[v1]:
            E.append([v2, v1])

    S = []
    VV = []
    EE = []

    #for v1 in edge_dict:
    #    vset = edge_dict[v1]
    #    for v2 in vset:
    #        S.append([v1,v2])
    rules = rule_list.keys()
    #print len(rules)
    for r1 in range(0, len(rules)):
        for r2 in range(r1 + 1, len(rules)):
            if r1 in table and r2 in table:
                continue
            intersection = header.intersect_molecule(rule_list[rules[r1]],
                                                     rule_list[rules[r2]])
            if intersection != None:
                S.append([rules[r1], rules[r2]])
    while len(S) > 0:
        #index = random.randint(0,len(S)-1)
        index = 0
        v1 = S[index][0]
        v2 = S[index][1]
        #print len(S),index,v1,v2
        #print "S=",S
        #print VV,EE
        header_space = []
        for edge in EE:
            if edge[0] == v1 or edge[0] == v2:
                header_space.append(rule_list[edge[1]])
        intersection = header.intersect_molecule(rule_list[v1], rule_list[v2])
        T = (intersection, header_space)
        while True:
            subtraction = header.subtraction_wrapper(intersection,
                                                     header_space)
            if subtraction == None:
                del S[index]
                break

            TimeLog.GetInstance().addCalc()
            pkt = solver.createPacket(intersection, header_space, types)
            TimeLog.GetInstance().addSolver()
            if pkt['SAT'] == 'No':
                del S[index]
                break

            #print "packet: ",
            types_tmp = {
                "src-port": 16,
                "dst-port": 16,
                "src-ip": 0,
                "dst-ip": 0
            }
            for typ in types_tmp:
                if pkt.has_key(typ):
                    #print typ,pkt[typ],
                    pass  #print typ,pkt[typ],
            #print ""

            TimeLog.GetInstance().addCalc()
            vhit = IssueProbe(pkt, rule_list, v1, v2)
            TimeLog.GetInstance().addSend()
            if vhit == -1:
                del S[index]
                break

            #solver.printpkt(pkt,types)
            if vhit >= 0 and not vhit in VV:
                VV.append(vhit)
            if vhit == v1:
                EE.append([v2, v1])
                del S[index]
                break
            if vhit == v2:
                EE.append([v1, v2])
                del S[index]
                break
            EE.append([v2, vhit])
            EE.append([v1, vhit])
            header_space.append(rule_list[vhit])
            if [v1, vhit] in S:
                S.remove([v1, vhit])
            if [v2, vhit] in S:
                S.remove([v2, vhit])
    #print "VV:",VV
    #print "EE:",EE
    #print "stage 2:"
    VVV = [val for val in V if val not in VV]
    while len(VVV) > 0:
        index = random.randint(0, len(VVV) - 1)
        v = VVV[index]
        T = rule_list[v]
        TT = []
        header_space = []
        #for vv in VV:
        #intersection = header.intersect_molecule(rule_list[vv],rule_list[vv])
        #if intersection != None:
        #header_space.append(intersection)
        #TT.append(vv)
        while True:
            #len(T) > 0 and len(header_space) > 0:
            TimeLog.GetInstance().addCalc()
            #print "solver: ",len(header_space)
            pkt = solver.createPacket(T, header_space, types)
            TimeLog.GetInstance().addSolver()
            if pkt['SAT'] == 'No':
                break
            TimeLog.GetInstance().addCalc()
            vhit = IssueProbe(pkt, rule_list, v, v)
            TimeLog.GetInstance().addSend()
            if vhit == -1:
                break
            if (not vhit in VV) and (vhit in V):
                VV.append(vhit)
            if vhit in VVV:
                VVV.remove(vhit)
            if vhit == v:
                break
            if vhit in TT:
                break
            TT.append(vhit)
            header_space.append(rule_list[vhit])
        if v in VVV:
            VVV.remove(v)
    #print "After leafs' detection:"
    #print "Original Graph"
    #print "V:",V
    #print "E:",E
    #print "Actual Graph"
    #print "VV:",VV
    #print "EE:",EE
    TimeLog.GetInstance().addCalc()
    if len(VV) != len(V):
        return False
    if len([val for val in V if val not in VV]) > 0:
        return False

    #equality for two graph.
    h = {}
    for i, k in enumerate(V):
        h[k] = i
    G1 = [[0] * len(V) for i in range(len(V))]
    for edge in E:
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G1[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G1[i][k] == 1 and G1[k][j] == 1:
                    G1[i][j] = 1
    G2 = [[0] * len(V) for i in range(len(V))]
    for edge in EE:
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G2[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G2[i][k] == 1 and G2[k][j] == 1:
                    G2[i][j] = 1
    ret = True
    for i in range(len(V)):
        if ret == False:
            break
        for j in range(len(V)):
            if G1[i][j] != G2[i][j]:
                ret = False
                break
    #print "Original DAG:",G1
    #print "Actual DAG:",G2
    TimeLog.GetInstance().clock()
    return ret
    import networkx as nx
    G = nx.DiGraph()
    for v in V:
        G.add_node(v)
    for edge in E:
        G.add_edge(edge[1], edge[0])
    GG = nx.DiGraph()
    for v in VV:
        GG.add_node(v)
    for edge in EE:
        GG.add_edge(edge[1], edge[0])
    ret = nx.is_isomorphic(G, GG)

    return ret
Exemplo n.º 9
0
def launcherE(dag_file, pre_file):
    #set the log mode
    logging.basicConfig(level=logging.WARNING)

    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(dag_file)
    pcg.start()

    PostCardProcessor.Start()
    time.sleep(0.1)

    from timelog import TimeLog

    import parser, IncrFaulDete
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file)
    rule_lists,edge_dicts = parser.DAGLoader(pre_file)

    table = []
    for i in rule_list.keys():
        for j in rule_lists.keys():
            ret = cmp(rule_list[i], rule_lists[j])
            if ret == 0:
                #print rule_list[i]
                #print rule_lists[j]
                table.append(i)
    #print table

    TimeLog.GetInstance().reset()
    pairs = IncrFaulDete.packetGenerator(edge_dict, rule_list, types, table)
    if pairs == False:
        flag = False
        return flag, TimeLog.GetInstance().getCost()

    TimeLog.GetInstance().addCalc()
    sender = Sender()
    pid2rid = {}
    for i,pair in enumerate(pairs):
        rid = pair[0]
        pkt = pair[1]
        pkt['pid'] = i
        pid2rid[i] = rid
        sender.send(pkt)
    TimeLog.GetInstance().addSend()
    TimeLog.GetInstance().addPackets(len(pairs))

    matched = 0
    unmatch = 0
    flag = True
    while True:
        try:
            TimeLog.GetInstance().addTotal()
            card = postCardQueue.get(True,TIME_WAIT)
        except Exception:
            TimeLog.GetInstance().clock()
            if len(pid2rid) > 0:
                print "Failed!",TimeLog.GetInstance().getCost()
                flag = False
                return flag, TimeLog.GetInstance().getCost()
            else:
                print "Success!",TimeLog.GetInstance().getCost()
                flag = True
                return flag, TimeLog.GetInstance().getCost()
            break
        pid = card[0]
        rid = card[1]
        if pid in pid2rid:
            rrid = pid2rid[pid]
            if rid == pid2rid[pid]:
                matched += 1
                pid2rid.pop(pid)
            else:
                unmatch += 1
                pkt = pairs[pid][1]
                warn = ""
                for typ in ['src-ip','dst-ip','src-port','dst-port']:
                    warn += typ+":"+str(pkt[typ])+";"
                TimeLog.GetInstance().addFirst()
    print "Finally, %d packets matched right, %d packets mismatched." %(matched,unmatch)
    print "57#time count: %.6f seconds" % (time.time() - delta - TIME_WAIT)
    Flag = False
    return flag,time.time()-delta-TIME_WAIT
Exemplo n.º 10
0
def launcherBWithWrongTable(dag_file, wrong_dag):

    #set the log mode
    #logging.basicConfig(level=logging.DEBUG)
    #logging.basicConfig(level=logging.INFO)
    #logging.basicConfig(level=logging.WARNING)
    logging.basicConfig(level=logging.WARNING)
    #logging.basicConfig(level=logging.ERROR)

    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(wrong_dag)
    pcg.start()

    #collect postcard
    #post = PostCardProcessor('s1-eth4')
    #post.start()
    PostCardProcessor.Start()
    time.sleep(0.1)
    #logging.info("1# start to collect %.8f" %time.time())

    #start to generate packets
    from timelog import TimeLog
    TimeLog.GetInstance().reset()

    import parser, NonaTrou
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file);
    pairs = NonaTrou.packetGenerator(edge_dict, rule_list, types)
    #logging.info("2# packets generated %.8f" %time.time())

    #send the packets
    #logging.info("3# packets flushed to datapath %.8f" %time.time())
    TimeLog.GetInstance().addCalc()
    sender = Sender()
    pid2rid = {}
    for i,pair in enumerate(pairs):
        rid = pair[0]
        pkt = pair[1]
        pkt['pid'] = i
        pid2rid[i] = rid
        #logging.debug("10# pid to rid: %d - %d." % (i,rid))
        sender.send(pkt)
    TimeLog.GetInstance().addSend()


    #process with the postcard
    matched = 0
    unmatch = 0
    flag = True
    VV = []
    EE = []
    while True:
        #print postCardQueue.qsize()
        try:
            TimeLog.GetInstance().addTotal()
            card = postCardQueue.get(True,TIME_WAIT)
            #print card
        except Exception:
            TimeLog.GetInstance().clock()
            #logging.warn("Post Card Queue is empty.")
            flag = NonaTrou.dagCompare(edge_dict, rule_list, VV, EE)
            if flag == False:
                #logging.info("55#Failed!")
                print "Failed!",TimeLog.GetInstance().getCost()
                flag = False
                return flag, TimeLog.GetInstance().getCost()
            else:
                #logging.info("56#Success!")
                print "Success!",TimeLog.GetInstance().getCost()
                flag = True
                return flag, TimeLog.GetInstance().getCost()
            break
        pid = card[0]
        rid = card[1]
        if pid in pid2rid:
            if not rid in VV:
                VV.append(rid)
            rrid = pid2rid[pid]
            for r in rrid:
                if r != rid:
                    EE.append([r,rid])
Exemplo n.º 11
0
def launcherA(dag_file):

    #set the log mode
    #logging.basicConfig(level=logging.DEBUG)
    #logging.basicConfig(level=logging.INFO)
    #logging.basicConfig(level=logging.WARNING)
    logging.basicConfig(level=logging.WARNING)
    #logging.basicConfig(level=logging.ERROR)

    #generate rules and install them on switch 1
    pcg = PostcardGernerator.PostcardGernerator(dag_file)
    pcg.start()

    #collect postcard
    #post = PostCardProcessor('s1-eth4')
    #post.start()
    PostCardProcessor.Start()
    time.sleep(0.1)
    #logging.info("1# start to collect %.8f" %time.time())

    #start to generate packets
    from timelog import TimeLog
    TimeLog.GetInstance().reset()

    import parser, FaulDete
    types = parser.type_parse("typename.txt")
    rule_list,edge_dict = parser.DAGLoader(dag_file);
    pairs = FaulDete.packetGenerator(edge_dict, rule_list, types)
    #logging.info("2# packets generated %.8f" %time.time())
    if pairs == False:
        flag = False
        return flag, TimeLog.GetInstance().getCost()
    #print pairs

    #send the packets
    #logging.info("3# packets flushed to datapath %.8f" %time.time())
    TimeLog.GetInstance().addCalc()
    sender = Sender()
    pid2rid = {}
    for i,pair in enumerate(pairs):
        rid = pair[0]
        pkt = pair[1]
        pkt['pid'] = i
        pid2rid[i] = rid
        #logging.debug("10# pid to rid: %d - %d." % (i,rid))
        sender.send(pkt)
    TimeLog.GetInstance().addSend()
    TimeLog.GetInstance().addPackets(len(pairs))


    #process with the postcard
    matched = 0
    unmatch = 0
    flag = True
    while True:
        #print postCardQueue.qsize()
        try:
            TimeLog.GetInstance().addTotal()
            card = postCardQueue.get(True,TIME_WAIT)
            #print card
        except Exception:
            TimeLog.GetInstance().clock()
            #logging.warn("Post Card Queue is empty.")
            if len(pid2rid) > 0:
                #logging.info("55#Failed!")
                print "Failed!",TimeLog.GetInstance().getCost()
                flag = False
                return flag, TimeLog.GetInstance().getCost()
            else:
                #logging.info("56#Success!")
                print "Success!",TimeLog.GetInstance().getCost()
                flag = True
                return flag, TimeLog.GetInstance().getCost()
            break
        pid = card[0]
        rid = card[1]
        if pid in pid2rid:
            rrid = pid2rid[pid]
            if rid == pid2rid[pid]:
                matched += 1
                pid2rid.pop(pid)
                #logging.debug("11# actually, Y pid to rid, should match: %d - %d - %d." %(pid,rid,rrid))
            else:
                unmatch += 1
                #logging.info("55#Unfinished!")
                #logging.warn("11# actually, N pid to rid, should match: %d - %d - %d." %(pid,rid,rrid))
                #print "11# actually, N pid to rid, should match: %d - %d - %d." %(pid,rid,rrid)
                pkt = pairs[pid][1]
                warn = ""
                for typ in ['src-ip','dst-ip','src-port','dst-port']:
                    warn += typ+":"+str(pkt[typ])+";"
                #logging.warn("12#"+warn)
                #break
                #print "Failed!",TimeLog.GetInstance().getCost()
                TimeLog.GetInstance().addFirst()
                #return flag, TimeLog.GetInstance().getCost()
                #return flag,time.time()-delta-TIME_WAIT
    #logging.info("56# Finally, %d packets matched right, %d packets mismatched." %(matched,unmatch) )
    #logging.info("57#time count: %.6f seconds" % (time.time() - delta - TIME_WAIT))
    print "Finally, %d packets matched right, %d packets mismatched." %(matched,unmatch)
    print "57#time count: %.6f seconds" % (time.time() - delta - TIME_WAIT)
    Flag = False
    return flag,time.time()-delta-TIME_WAIT
Exemplo n.º 12
0
def packetGenerator(edge_dict, rule_list, types, table):
    # containg all pkt, rule paris
    pairs = []
    dag = {}
    for rule in rule_list:
        dag[rule] = []
    for rule1 in edge_dict:
        if not dag.has_key(rule1):
            dag[rule1] = []
        for rule2 in edge_dict[rule1]:
            if not dag.has_key(rule2):
                dag[rule2] = []
            dag[rule2].append(rule1)

    dep = copy.deepcopy(dag)
    #print dag

    header_space = []
    T = {}
    for rule1 in rule_list.keys():
        T[rule1] = []
    # variable rule1 and rule 2 are int.
    while True:
        rule1 = -1
        for rule in dag:
            if len(dag[rule]) == 0:
                rule1 = rule
                break
        #print rule1
        if rule1 == -1:
            break
        for rule in dep[rule1]:
            if len(T[rule]) > 0:
                T[rule1] += T[rule]

        T[rule1].sort()
        T[rule1] = [
            x for i, x in enumerate(T[rule1])
            if not i or T[rule1][i] != T[rule1][i - 1]
        ]

        if edge_dict.has_key(rule1):
            #print "rule has other rule to depend on"
            adj_list = edge_dict[rule1]

            for rule2 in adj_list:
                if rule1 in table and rule2 in table:
                    #print rule1, rule2
                    continue
                intersection = header.intersect_molecule(
                    rule_list[rule1], rule_list[rule2])
                if intersection == None:
                    #print rule1,rule_list[rule1]
                    #print rule2,rule_list[rule2]
                    continue
                #print rule1,rule2
                TimeLog.GetInstance().addCalc()
                packet = solver.createPacket(intersection, T[rule1], types)
                TimeLog.GetInstance().addSolver()
                #print packet
                if packet['SAT'] == 'No':
                    print "1. Dependency Error"
                    #print rule2
                    return False
                # include the packet and its rule pair
                T[rule2].append(intersection)
                #T[rule2].append(rule_list[rule1])

                tu = (rule1, packet)
                if tu not in pairs:
                    pairs.append(tu)

        elif len(dep[rule1]) > 0:
            if rule1 in table:
                del dag[rule1]
                for rule in dag:
                    if rule1 in dag[rule]:
                        dag[rule].remove(rule1)
                continue
            #print "rule has no ther rule depend on"
            TimeLog.GetInstance().addCalc()
            packet = solver.createPacket(rule_list[rule1], T[rule1], types)
            TimeLog.GetInstance().addSolver()
            if packet['SAT'] == 'No':
                print "2. (leaf) Dependency Error"
                #print rule1
                return False

            tu = (rule1, packet)
            if tu not in pairs:
                pairs.append(tu)

        elif len(dep[rule1]) == 0:
            if rule1 in table:
                del dag[rule1]
                for rule in dag:
                    if rule1 in dag[rule]:
                        dag[rule].remove(rule1)
                continue
            #print "rule has no ther rule depend on"
            TimeLog.GetInstance().addCalc()
            packet = solver.createPacket(rule_list[rule1], T[rule1], types)
            TimeLog.GetInstance().addSolver()
            if packet['SAT'] == 'No':
                print "3. (dependent) Dependency Error"
                #print rule1
                return False

            tu = (rule1, packet)
            if tu not in pairs:
                pairs.append(tu)

        #remove visited rules in dag
        del dag[rule1]
        for rule in dag:
            if rule1 in dag[rule]:
                dag[rule].remove(rule1)
    #print pairs
    TimeLog.GetInstance().addCalc()
    return pairs
Exemplo n.º 13
0
def packetGenerator(edge_dict, rule_list, types, q, table, Edge):
    global postCardQueue
    postCardQueue = q
    global Pid
    Pid = 0

    TimeLog.GetInstance().addTotal()

    V = rule_list.keys()
    E = []
    for v1 in edge_dict:
        for v2 in edge_dict[v1]:
            E.append([v2, v1])

    S = []
    VV = table
    EE = Edge
    rules = rule_list.keys()
    for r1 in range(0, len(rules)):
        for r2 in range(r1 + 1, len(rules)):
            if r1 in table and r2 in table:
                continue
            intersection = header.intersect_molecule(rule_list[rules[r1]],
                                                     rule_list[rules[r2]])
            if intersection != None:
                S.append([rules[r1], rules[r2]])
    while len(S) > 0:
        #print "#",len(S),S
        pset = {}
        pindex = {}
        #print len(S)
        #print VV,EE
        for s in S:
            v1 = s[0]
            v2 = s[1]
            header_space = []
            for edge in EE:
                if edge[0] == v1 or edge[0] == v2:
                    header_space.append(rule_list[edge[1]])
            intersection = header.intersect_molecule(rule_list[v1],
                                                     rule_list[v2])

            T = [intersection, header_space]
            subtraction = header.subtraction_wrapper(intersection,
                                                     header_space)
            if subtraction == None:
                S.remove(s)
                continue
            TimeLog.GetInstance().addTotal()
            pkt = solver.createPacket(intersection, header_space, types)
            TimeLog.GetInstance().addSolver()
            if pkt['SAT'] == 'No':
                S.remove(s)
                break
            pindex[Pid] = [v1, v2]
            pset[Pid] = pkt
            pkt['pid'] = Pid
            Pid += 1

        #print len(pset)
        #IssueProbeSet
        TimeLog.GetInstance().addTotal()
        pHits = IssueProbeSet(pset)
        TimeLog.GetInstance().addSend()

        for p in pHits:
            vhit = pHits[p]
            v1 = pindex[p][0]
            v2 = pindex[p][1]
            #for p in pset:
            #print len(pset)
            #pkt = pset[p]
            #v1 = pindex[p][0]
            #v2 = pindex[p][1]
            #TimeLog.GetInstance().addTotal()
            #vhit = IssueProbe(pkt,rule_list,v1,v2)
            #TimeLog.GetInstance().addSend()

            if vhit >= 0 and not vhit in VV:
                VV.append(vhit)
            if vhit == v1:
                EE.append([v2, v1])
                if [v1, v2] in S:
                    S.remove([v1, v2])
                continue
            if vhit == v2:
                EE.append([v1, v2])
                if [v1, v2] in S:
                    S.remove([v1, v2])
                continue
            if vhit >= 0:
                EE.append([v2, vhit])
                EE.append([v1, vhit])
                if [v1, vhit] in S:
                    S.remove([v1, vhit])
                if [v2, vhit] in S:
                    S.remove([v2, vhit])
            if vhit == -1:
                if [v1, v2] in S:
                    S.remove([v1, v2])
    #print "VV:",VV
    #print "EE:",EE
    #print "stage 2:"
    VVV = [val for val in V if val not in VV]
    while len(VVV) > 0:
        #print "#",len(VVV)
        index = random.randint(0, len(VVV) - 1)
        v = VVV[index]
        T = rule_list[v]
        TT = []
        header_space = []
        #for vv in VV:
        #intersection = header.intersect_molecule(rule_list[vv],rule_list[vv])
        #if intersection != None:
        #header_space.append(intersection)
        #TT.append(vv)
        while True:
            #len(T) > 0 and len(header_space) > 0:
            TimeLog.GetInstance().addCalc()
            #print "solver: ",len(header_space)
            pkt = solver.createPacket(T, header_space, types)
            TimeLog.GetInstance().addSolver()
            if pkt['SAT'] == 'No':
                break
            TimeLog.GetInstance().addCalc()
            Pid += 1
            pkt['pid'] = Pid
            vhit = IssueProbe(pkt, rule_list, v, v)
            TimeLog.GetInstance().addSend()
            if vhit == -1:
                break
            if (not vhit in VV) and (vhit in V):
                VV.append(vhit)
            if vhit in VVV:
                VVV.remove(vhit)
            if vhit == v:
                break
            if vhit in TT:
                break
            TT.append(vhit)
            header_space.append(rule_list[vhit])
        if v in VVV:
            VVV.remove(v)
    #print "After leafs' detection:"
    #print "Original Graph"
    #print "V:",V
    #print "E:",E
    #print "Actual Graph"
    #print "VV:",VV
    #print "EE:",EE
    TimeLog.GetInstance().addCalc()
    if len(VV) != len(V):
        return False
    if len([val for val in V if val not in VV]) > 0:
        return False
    #print len(V), len(VV)
    ret = True
    TimeLog.GetInstance().clock()
    return ret

    #equality for two graph.
    h = {}
    for i, k in enumerate(V):
        h[k] = i
    G1 = [[0] * len(V) for i in range(len(V))]
    for edge in E:
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G1[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G1[i][k] == 1 and G1[k][j] == 1:
                    G1[i][j] = 1
    G2 = [[0] * len(V) for i in range(len(V))]
    for edge in EE:
        v1 = h[edge[0]]
        v2 = h[edge[1]]
        G2[v1][v2] = 1
    for i in range(len(V)):
        for j in range(len(V)):
            for k in range(len(V)):
                if G2[i][k] == 1 and G2[k][j] == 1:
                    G2[i][j] = 1
    ret = True
    for i in range(len(V)):
        if ret == False:
            break
        for j in range(len(V)):
            if G1[i][j] != G2[i][j]:
                ret = False
                break
    #print "Original DAG:",G1
    #print "Actual DAG:",G2
    TimeLog.GetInstance().clock()
    return ret