summaryrefslogtreecommitdiffstats
path: root/statemachine.py
blob: 133fd173a2e96a7012d62e471e0bbbc1b888df35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
__docformat__ = 'restructuredtext'

from category import Category
from pattern import Pattern
import setcross

class StateMachine:
    """
    The state machine contains a list of dependencies between states, and a list
    of states which are "up."
    """

    def __init__(self):
        """
        Create a new state machine
        """
        self.up = set()
        self.wanted = set()
        self.deps = []
        self.event_triggers = []

    def emit(self, event):
        """
        Emit an event.
        """
        retval = False
        for evpat, cat in self.event_triggers:
            if event.subset_of(evpat):
                retval |= self.bring_up(cat.intersect_args(**event.args))
        return retval

    def bring_up(self, cat, wanted=True):
        """
        Move states in the given Category `cat` from down to up.
        """
        found = None
        for (match, dependency) in self.get_applicable_deps(cat):
            res = self.get_satisfied_states(match, dependency)
            if len(res) == 0:
                return False
            if found == None:
                found = [res]
            else:
                found.append(res)
        if found == None:
            self.add_hold(cat, wanted)
            sm.emit(Category("ε"))
            return True
        to_add = self.cat_cross(found)
        for x in to_add:
            self.add_hold(x, wanted)
        sm.emit(Category("ε"))
        return True

    def cat_cross(self, found):
        """
        Given a list of sets, where each set contains Category objects, return a
        set of all categories that can be made by intersecting one element from
        each set.
        """
        to_add = set()
        for tup in setcross.cross(*found):
            orig = tup
            while len(tup) > 1:
                newtup = (tup[0].intersect(tup[1]),)
                if newtup[0] == None:
                    tup = ()
                    break
                tup = newtup + tup[2:len(tup)]
            if len(tup) == 0 or tup[0] == None:
                continue
            to_add.add(tup[0])
        return to_add

    def add_hold(self, cat, wanted):
        """
        Add a hold to a state. Does not check dependencies.
        """
        for x in self.up:
            if cat.subset_of(x):
                return
            if x.subset_of(cat):
                self.up.remove(x)
                self.up.add(cat)
                return
        self.up.add(cat)
        if wanted: self.wanted.add(cat)

    def bring_down(self, cat, rec=False):
        """
        Bring a currently "up" state down.
        """
        to_drop = set([ x for x in self.up if x.subset_of(cat) ])
        if None in to_drop: to_drop.remove(None)
        if len(to_drop) == 0: return False
        for (dependent, dependency) in self.deps:
            match = set([dependency.intersect(x) for x in to_drop])
            if None in match: match.remove(None)
            if match != None:
                for item in match:
                    self.bring_down(dependent.fill(item.args), rec=True)
        self.up -= to_drop
        self.wanted -= to_drop
        if not rec: self.cleanup_states()

    def cleanup_states(self):
        """
        Remove unwanted states
        """
        new_up = self.wanted.copy()
        addition = set([1])
        while len(addition):
            addition = set()
            for s in addition:
                for x in self.get_applicable_deps(s):
                    for y in self.up:
                        if y.subset_of(x):
                            addition.add(y)
            new_up |= addition
        self.up = new_up

    def get_satisfied_states(self, dependents, dependencies):
        """
        Given that states in `dependents` depend on states in `dependencies`,
        return a new Category that contains only the states in `dependents` that
        could match states in `dependencies`.
        """
        retval = []
        for cat in self.up:
            if dependencies.superset_of(cat):
                retval.append(dependents.intersect_args(**cat.args))
        return set(retval) | dependents.inverse_set()

    def get_applicable_deps(self, cat):
        """
        Find dependencies that might apply to members of `cat`
        """
        retval = []
        for (x, y) in self.deps:
            un = cat.intersect(x)
            if un != None:
                retval.append((un, y.fill(un.args)))
        return retval

    def __str__(self):
        return "\n".join(["%s" % k for k in self.up])

    def __repr__(self):
        return str(self)

def m(*args): return Pattern(True, *args)   # The "m" reads "match", so m("foo", "bar") reads 'match foo and bar'
def nm(*args): return Pattern(False, *args) # Reads as "don't match." See above
def any(): return nm()                      # Match anything. Implementation reads "don't match nothing"

if __name__ == "__main__":
    sm = StateMachine()
    sm.deps.append((Category("mounted", type=m("nfs")), Category("network_up")))
    sm.deps.append((Category("mounted", type=nm("nfs")), Category("found_disk")))
    sm.deps.append((Category("mounted"), Category("vol_conf")))

    sm.event_triggers.append((Category("fstab_line"), Category("vol_conf", src=m("fstabd"))))

    sm.bring_up(Category("network_up"))
    sm.bring_up(Category("found_disk", uuid=m("d3adb3ef"), devname=m("/dev/sda"), label=m("myroot")))
    sm.bring_up(Category("mounted", devname=any(), mountpoint=any()))
    print sm
    print "--"
    sm.emit(Category("fstab_line", label=m("myroot"), type=m("ext3"), mountpoint=m("/")))
    sm.emit(Category("fstab_line", devname=m("foosrv.com:/vol/home"), type=m("nfs"), mountpoint=m("/home")))
    sm.emit(Category("fstab_line", devname=m("foosrv.com:/vol/beefs"), type=m("nfs"), mountpoint=m("/beefs")))
    sm.bring_up(Category("mounted", devname=any(), mountpoint=any()))
    print sm
    print "--"
    sm.bring_down(Category("network_up"))
    print sm