Commit 30810042 authored by Romain Courteaud's avatar Romain Courteaud

Add network reporting method

parent 00fe334b
import socket
import errno
from peewee import fn
TIMEOUT = 2
def reportNetwork(db, ip=None, transport=None, port=None):
# http://charlesleifer.com/blog/techniques-for-querying-lists-of-objects-and-determining-the-top-related-item/
NetworkChangeAlias = db.NetworkChange.alias()
subquery = (
NetworkChangeAlias.select(
NetworkChangeAlias.ip,
NetworkChangeAlias.transport,
NetworkChangeAlias.port,
fn.MAX(NetworkChangeAlias.status_id).alias("max_status_id"),
)
.group_by(
NetworkChangeAlias.ip,
NetworkChangeAlias.transport,
NetworkChangeAlias.port,
)
.alias("network_change_max_subquery")
)
StatusAlias = db.Status.alias()
query = (
db.NetworkChange.select(db.NetworkChange, StatusAlias)
.join(StatusAlias)
.switch(db.NetworkChange)
.join(
subquery,
on=(
(db.NetworkChange.status_id == subquery.c.max_status_id)
& (db.NetworkChange.ip == subquery.c.ip)
& (db.NetworkChange.transport == subquery.c.transport)
& (db.NetworkChange.port == subquery.c.port)
),
)
.order_by(
db.NetworkChange.ip.asc(),
db.NetworkChange.port.asc(),
db.NetworkChange.transport.asc(),
)
)
if transport is not None:
if type(transport) == list:
query = query.where(db.NetworkChange.transport << transport)
else:
query = query.where(db.NetworkChange.transport == transport)
if port is not None:
query = query.where(db.NetworkChange.port == port)
if ip is not None:
if type(ip) == list:
query = query.where(db.NetworkChange.ip << ip)
else:
query = query.where(db.NetworkChange.ip == ip)
return query
def logNetwork(db, ip, transport, port, state, status_id):
with db._db.atomic():
try:
# Check previous parameter value
previous_entry = (
db.NetworkChange.select()
.where(
db.NetworkChange.ip == ip,
db.NetworkChange.transport == transport,
db.NetworkChange.port == port,
)
.order_by(db.NetworkChange.status.desc())
.get()
)
previous_entry = reportNetwork(
db, ip=ip, transport=transport, port=port
).get()
except db.NetworkChange.DoesNotExist:
previous_entry = None
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment