tweaked LeaseFilter to allow lists instead of tuples for clip and alive
[plcapi.git] / PLC / LeaseFilter.py
index b66d6a4..c7e31bc 100644 (file)
@@ -2,10 +2,13 @@
 # Thierry Parmentelat -- INRIA
 #
 # Utilities for filtering on leases
-#
 
-from types import StringTypes
-from PLC.Faults import *
+# w0622: we keep on using 'filter' as a variable name
+# pylint: disable=c0111, c0103, w0622
+
+import time
+
+from PLC.Faults import *                         # pylint: disable=w0401, w0614
 from PLC.Filter import Filter
 from PLC.Parameter import Parameter, Mixed
 from PLC.Timestamp import Timestamp
@@ -13,7 +16,7 @@ from PLC.Timestamp import Timestamp
 # supersede the generic Filter class to support time intersection
 
 
-class LeaseFilter (Filter):
+class LeaseFilter(Filter):
 
     # general notes on input parameters
     # int_timestamp: number of seconds since the epoch
@@ -23,38 +26,50 @@ class LeaseFilter (Filter):
 
     local_fields = {
         'alive': Mixed(
-            Parameter(
-                int,  "int_timestamp: leases alive at that time"),
-            Parameter(
-                str,  "str_timestamp: leases alive at that time"),
-            Parameter(
-                tuple, "timeslot: the leases alive during this timeslot")),
-        'clip':  Mixed(
-            Parameter(
-                int,  "int_timestamp: leases alive after that time"),
-            Parameter(
-                str,  "str_timestamp: leases alive after at that time"),
-            Parameter(
-                tuple, "timeslot: the leases alive during this timeslot")),
+            Parameter(int, "int_timestamp: leases alive at that time"),
+            Parameter(str, "str_timestamp: leases alive at that time"),
+            Parameter(list, "timeslot: the leases alive during this timeslot"),
+            ),
+        'clip': Mixed(
+            Parameter(int, "int_timestamp: leases alive after that time"),
+            Parameter(str, "str_timestamp: leases alive after that time"),
+            Parameter(list, "timeslot: the leases alive during this timeslot"),
+            ),
+        ########## macros
+        # {'day' : 0} : all leases from today and on
+        # {'day' : 1} : all leases today (localtime at the myplc)
+        # {'day' : 2} : all leases today and tomorrow (localtime at the myplc)
+        # etc..
+        'day': Parameter(
+            int,
+            "clip on a number of days from today and on;"
+            " 0 means no limit in the future"),
     }
 
-    def __init__(self, fields={}, filter={},
+    def __init__(self, fields=None, filter=None,
                  doc="Lease filter -- adds the 'alive' and 'clip'"
                  "capabilities for filtering on leases"):
+        if fields is None:
+            fields = {}
+        if filter is None:
+            filter = {}
         Filter.__init__(self, fields, filter, doc)
         self.fields.update(LeaseFilter.local_fields)
 
     # canonical type
     @staticmethod
-    def quote(timestamp): return Timestamp.cast_long(timestamp)
+    def quote(timestamp):
+        return Timestamp.cast_long(timestamp)
 
     # basic SQL utilities
     @staticmethod
     def sql_time_intersect(f1, u1, f2, u2):
         # either f2 is in [f1,u1], or u2 is in [f1,u1], or f2<=f1<=u1<=u2
-        return ("(({f1} <= {f2}) AND ({f2} <= {u1})) " +
-                "OR (({f1} <= {u2}) AND ({u2} <= {u1})) " +
-                "OR (({f2}<={f1}) AND ({u1}<={u2}))").format(**locals())
+        return (
+            "(({f1} <= {f2}) AND ({f2} <= {u1})) "
+            "OR (({f1} <= {u2}) AND ({u2} <= {u1})) "
+            "OR (({f2}<={f1}) AND ({u1}<={u2}))"
+            .format(f1=f1, u1=u1, f2=f2, u2=u2))
 
     @staticmethod
     def time_in_range(timestamp, f1, u1):
@@ -64,21 +79,22 @@ class LeaseFilter (Filter):
     @staticmethod
     def sql_time_in_range(timestamp, f1, u1):
         # is timestamp in [f1, u1]
-        return "(({f1} <= {timestamp}) AND ({timestamp} <= {u1}))"\
-            .format(**locals())
+        return (
+            "(({f1} <= {timestamp}) AND ({timestamp} <= {u1}))"
+            .format(timestamp=timestamp, f1=f1, u1=u1))
 
     @staticmethod
     def sql_timeslot_after(f1, u1, mark):
         # is the lease alive after mark, i.e. u1 >= mark
-        return "({u1} >= {mark})".format(**locals())
+        return "({u1} >= {mark})".format(u1=u1, mark=mark)
 
     # hooks for the local fields
     def sql_alive(self, alive):
-        if isinstance(alive, int) or isinstance(alive, StringTypes):
+        if isinstance(alive, (int, str)):
             # the lease is alive at that time if from <= alive <= until
             alive = LeaseFilter.quote(alive)
             return LeaseFilter.sql_time_in_range(alive, 't_from', 't_until')
-        elif isinstance(alive, tuple):
+        elif isinstance(alive, (tuple, list)):
             (f, u) = alive
             f = LeaseFilter.quote(f)
             u = LeaseFilter.quote(u)
@@ -88,10 +104,10 @@ class LeaseFilter (Filter):
                                      .format(alive))
 
     def sql_clip(self, clip):
-        if isinstance(clip, int) or isinstance(clip, StringTypes):
+        if isinstance(clip, int) or isinstance(clip, str):
             start = LeaseFilter.quote(clip)
             return LeaseFilter.sql_timeslot_after('t_from', 't_until', start)
-        elif isinstance(clip, tuple):
+        elif isinstance(clip, (tuple, list)):
             (f, u) = clip
             f = LeaseFilter.quote(f)
             u = LeaseFilter.quote(u)
@@ -100,14 +116,33 @@ class LeaseFilter (Filter):
             raise PLCInvalidArgument("LeaseFilter: clip field {}"
                                      .format(clip))
 
+    # the whole key to implementing day is to compute today's beginning
+    def today_start(self):
+        # a struct_time
+        st = time.localtime()
+        seconds_today = st.tm_hour * 3600 + st.tm_min * 60 + st.tm_sec
+        return int(time.time()) - seconds_today
+
     # supersede the generic Filter 'sql' method
     def sql(self, api, join_with="AND"):
+        # implement 'day' as a clip
+        if 'day' in self:
+            if 'clip' in self:
+                raise PLCInvalidArgument("LeaseFilter cannot have both 'clip' and 'day'")
+            today = self.today_start()
+            nb_days = self['day']
+            if nb_days == 0:
+                self['clip'] = today
+            else:
+                self['clip'] = (today, today + nb_days * 24 * 3600)
+            del self['day']
+
         # preserve locally what belongs to us, hide it from the superclass
         # self.local is a dict    local_key : user_value
         # self.negation is a dict  local_key : string
         self.local = {}
         self.negation = {}
-        for (k, v) in LeaseFilter.local_fields.items():
+        for (k, v) in list(LeaseFilter.local_fields.items()):
             if k in self:
                 self.local[k] = self[k]
                 del self[k]
@@ -118,7 +153,7 @@ class LeaseFilter (Filter):
                 self.negation[k] = "NOT "
         # run the generic filtering code
         (where_part, clip_part) = Filter.sql(self, api, join_with)
-        for (k, v) in self.local.items():
+        for (k, v) in list(self.local.items()):
             try:
                 # locate hook function associated with key
                 method = LeaseFilter.__dict__['sql_' + k]
@@ -126,7 +161,7 @@ class LeaseFilter (Filter):
                               .format(self.join_with,
                                       self.negation[k],
                                       method(self, self.local[k]))
-            except Exception, e:
+            except Exception as e:
                 raise PLCInvalidArgument(
                     "LeaseFilter: something wrong with filter"
                     "key {}, val was {} -- {}".format(k, v, e))