-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_machine.py
More file actions
100 lines (80 loc) · 2.78 KB
/
Copy pathstate_machine.py
File metadata and controls
100 lines (80 loc) · 2.78 KB
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
""" This is the state machine class for broker to maintain peering state
This is not a general state machine implementation for all protocols
TODO: Revise this into a different name
"""
import sys
import peer_manager
from twisted.python import log
from util import Log
import time
class State:
def __init__(self, connection):
self.connection = connection
@staticmethod
def Create(state, connection):
dispatcher = state + 'State'
thismodule = sys.modules[__name__]
try:
c = getattr(thismodule, dispatcher)
except AttributeError:
#print 'return init state'
return InitState(connection)
else:
return c(connection)
def Transition(self, data):
if not ',' in data:
command, input = data, None
else:
command, input = data.split(',', 1)
handler = 'Handle' + command
try:
h = getattr(self, handler)
except AttributeError:
Log.Msg('Calling HandleDefault')
return self.HandleDefault(data)
else:
Log.Msg('Calling ' + handler)
return h(input)
def HandleDefault(self, data):
self.connection.Send('Unknown request')
self.connection.CloseConnection('Unkown request')
return None, self
def HandleTERM(self, data):
self.connection.CloseConnection('Terminated by remote host')
return None, self
def HandelHELLO(self, data):
self.connection.Alive(time.time())
self.connection.Send('HELLOACK')
return None, self
INIT = 'Init'
READY = 'Ready'
class InitState(State):
def HandleNAME(self, data):
self.connection.factory.peerManager.Register(data, self.connection)
return None, State.Create(READY, self.connection)
def HandleNREQ(self, data):
self.connection.Send('NAME,' + self.connection.factory.localDomainName)
return None, self
class ReadyState(InitState):
def HandleSUB(self, data):
self.connection.peerManager.RecvSUB(self.connection.remoteDomainName, data)
return None, self
def HandleMSG(self, data):
self.connection.peerManager.RecvMSG(data, self.connection.remoteDomainName)
return None, self
class StateMachine:
def __init__(self, connection):
self.connection = connection
self.state = State.Create(INIT, connection)
def Accept(self, data):
out, newstate = self.state.Transition(data)
self.state = newstate
return out
def Set(self, state):
Log.Msg('Setting state to ' + state)
self.state = State.Create(state, self.connection)
if __name__ == '__main__':
Log.StartLogging(sys.stdout)
m = StateMachine(None)
m.Accept('DEFAULT')
m.Set(READY)