Пример #1
0
def get_messages():
    json_query = {}
    json_query['method'] = 'get_messages'
    json_query['id'] = '0'
    json_query['params'] = {'kiosk-id': Beagleboard.get_dieid()}
    json_query_str = json.dumps(json_query)
    logger.debug("Sending JSON Query: %s" % json_query_str)
    hash = MD5.new(json_query_str).digest()
    # encoding signature
    encoded_sig = Security.sign_digest(hash)
    headers = {'X-eko-signature': encoded_sig}
    
    urlreq = urllib2.Request(Constants.URLJsonAPI, json_query_str, headers)
    try:
        response = urllib2.urlopen(urlreq)
    except urllib2.URLError:
        logger.exception("Unable to open URL to fetch server messages")
        return False
    
    json_reply = response.read()
    
    try:
        response_dict = json.loads(json_reply)
    except:
        logger.exception("Unable to decode response JSON!")
        return False
    
    messages = response_dict['result']
    return messages
Пример #2
0
def get_messages(ctx):
    configpath = ctx['config']
    json_query = {}
    json_query['method'] = 'get_messages'
    json_query['id'] = '0'
    json_query['params'] = {'kiosk-id': ctx['serial']}
    json_query_str = json.dumps(json_query)
    logger.debug("Sending JSON Query: %s" % json_query_str)
    hash = MD5.new(json_query_str).digest()
    # encoding signature
    encoded_sig = Security.sign_digest(hash, join(configpath, 'privatekey.pem'))
    headers = {'X-eko-signature': encoded_sig}
    
    urlreq = urllib2.Request(ctx['json_api'], json_query_str, headers)
    try:
        response = urllib2.urlopen(urlreq)
    except urllib2.URLError:
        logger.exception("Unable to open URL to fetch server messages")
        return False
    
    json_reply = response.read()
    
    try:
        response_dict = json.loads(json_reply)
    except:
        logger.exception("Unable to decode response JSON!")
        return False
    
    messages = response_dict['result']
    return messages
Пример #3
0
def send_heartbeat(url, uptime, rwip='0.0.0.0'):
    json_msg = {}
    json_msg['method'] = 'heartbeat'
    json_msg['id'] = 0
    params = {'rwanda-ip':rwip}
    params['kiosk-id'] = Beagleboard.get_dieid()
    if uptime < 60:
        # under a minute
        uptimestr = "%.2f seconds" % uptime
    elif uptime < 60*60:
        # under a hour
        uptimestr = "%.2f minutes" % (uptime/(60.0))
    elif uptime < 60*60*24*3:
        # under 3 days
        uptimestr = "%.2f hours" % (uptime/(60.0*60.0))
    else:
        # over 3 days
        uptimestr = "%.2f days" % (uptime/(60.0*60.0*24.0))
        
    params['uptime'] = uptimestr
    params['sw-version'] = '1.0.0'
    params['time'] = datetime.utcnow()
    json_msg['params'] = params
    jsstr = json.dumps(json_msg)
    hash = MD5.new(jsstr).digest()
    logger.info("System has been up for %s." % uptime)
    
    sign_16encode = Security.sign_digest(hash)
    #print "encoded: %s" % sign_16encode
    #print "signature: %d" % key.sign(hash, "")[0]
    #print "hash: %s"  % "".join(["%02x " % ord(x) for x in hash])
    headers = {'X-eko-signature': sign_16encode}
    
    
    #test decoding
    try:
        logger.info("Transmiting heartbeat.")
        req = urllib2.Request(url, jsstr, headers)
        response = urllib2.urlopen(req)
        the_page = response.read()
    except:
        logger.exception("Transmit failed.")
        return False
    try:
        jsondict = json.loads(the_page)
    except:
        logger.exception('Could not load reply json')
        jsondict = {'error':'json not loaded'} 
    if jsondict['result'] == "success":
        logger.info("Heartbeat Success.")
        return True
    else:
        logger.debug("Response: %s." % the_page)
        logger.info("Sleeping.")
        return False
Пример #4
0
def transmit_clientmessages(ctx):
    logger.info("Transmitting client messages to server.")
    # config path from passed context
    configpath = ctx['config']
    con = sqlite3.connect(join(configpath, 'sync.db'), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    c = con.cursor()
    try:
        c.execute("SELECT message, sessionref, origin, origintime, id FROM clientmsg WHERE synctime is NULL LIMIT 15")
        rows = c.fetchall()
    except sqlite3.Error:
        logger.exception("Error fetching rows from sync.db.")
        rows = None
    finally:
        c.close()
        con.close()
    
    # bug out if execute failed
    if (rows is None) or (rows == []):
        logger.info("No messages to sync.")
        return False
    
    list = []
    for row in rows:
        data={}
        data['session-ref'] = row[1]
        data['message'] = row[0]
        data['origin'] = row[2]
        data['origin-date'] = row[3]
        list.append(data)
    
    # list contains a list of messages
    msg = {}
    msg['method'] = 'post_messages'
    msg['id'] = 0
    msg['params'] = {'kiosk-id' : ctx['serial'], 'messages' : list}
    
    jsonstr = json.dumps(msg)
    
    hash = MD5.new(jsonstr).digest()
    
    sig = Security.sign_digest(hash, join(configpath, 'privatekey.pem'))
    headers = {'X-eko-signature':  sig}

    urlreq = urllib2.Request(ctx['json_api'], jsonstr, headers)
    
    try:
        resp = urllib2.urlopen(urlreq)
    except urllib2.URLError:
        logger.exception("Unable to send client messages")
        return False
    try:
        resp_str = resp.read()
        jsonreply = json.loads(resp_str)
        logger.debug("JSON reply reads: %s" % resp_str)
    except:
        logger.exception("Could not read reply json.")
        jsonreply = {'result':'Could not load json'}
    
    if jsonreply['result'].lower().strip() != 'success':
        logger.error("Server replied with error: %s" % str(jsonreply))
        return False
    else:
        logger.info("Succesfully uploaded messages.")
        _update_clientmsg_table([row[4] for row in rows], ctx['config'])
        return True