def stopFlow():
    """
    Stops ongoing iperf client sessions that were previously
    orchestrated by the TG.
    """
    #Retrieve Traffic Generator Slave Object
    tgslave = app.config['TGS']

    t = time.strftime("%H:%M:%S", time.gmtime())
    log.info("%s - StopFlow command from Traffic Generator arrived\n"%t)
    
    # Get flow information
    flow = flask.request.json
    aux = Base()
    size = aux.setSizeToStr(flow['size'])
    
    # Log it
    log.info("\t* Stopping iperf client session of flow...\n")
    log.info("\t  - src: %s:%s\n"%(flow['src'], flow['sport']))                
    log.info("\t  - dst: %s:%s\n"%(flow['dst'], flow['dport']))
    log.info("\t  - size: %s\n"%size)
    log.info("\t  - duration: %s\n"%str(flow['duration']))

    # Kill ongoing flow
    flow_already_there = [(p, f) for (p, f) in tgslave.iperf_sessions.iteritems() if f == flow]
    if flow_already_there != []:
        # Get process handler
        p = flow_already_there[0][0]
        # Terminate it
        p.terminate()
        # Remove from dictionary
        tgslave.iperf_sessions.pop(p)

    else:
        log.info("\t* Error: non-existing flow\n")
def startFlow():
    """This function will be running in each of the hosts in our
    network. It essentially waits for commands from the
    TrafficGenerator in the Json-Rest interface and creates a
    subprocess for each corresponding iperf client sessions to other
    hosts.
    """
    try:
        # Retrieve Traffic Generator Slave object
        tgslave = app.config['TGS']

        t = time.strftime("%H:%M:%S", time.gmtime())
        log.info("%s - StartFlow command from Traffic Generator arrived\n"%t)
    
        # Get flow information
        flow = flask.request.json
        aux = Base()
        size = aux.setSizeToStr(flow['size'])

        # Log it
        log.info("\t* Starting iperf client command...\n")
        log.info("\t  - src: %s:%s\n"%(flow['src'], flow['sport']))                
        log.info("\t  - dst: %s:%s\n"%(flow['dst'], flow['dport']))
        log.info("\t  - size: %s\n"%size)
        log.info("\t  - duration: %s\n"%str(flow['duration']))
    
        # Add process handler to dictionary
        flow_already_there = [(p, f) for (p, f) in tgslave.iperf_sessions.iteritems() if f == flow]
        if flow_already_there != []:
            # If same flow exists already, restart it
            previous_p = flow_already_there[0][0]
            previous_p.terminate()
            tgslave.iperf_sessions.pop(p)

        # Start iperf client session
        p = Popen(["iperf", "-c", flow['dst'], "-u", "-b", size, "-t",
                   str(flow['duration']), "-p", str(flow['dport'])])
        
        tgslave.iperf_sessions[p] = flow
    except:
        log.info("ERROR:\n")
        log.info("LOG: Exception in user code:\n")
        log.info('-'*60+'\n')
        log.info(traceback.print_exc())
        log.info('-'*60+'\n')