summaryrefslogtreecommitdiff
path: root/demo2/premise.py
blob: 942bba6879d6e6ed95affaa5b1128b45aab49952 (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
# Python modules
import time
import sys
PY_MAJOR_VERSION = sys.version_info[0]
# hashlib is only available in Python >= 2.5. I still want to support 
# older Pythons so I import md5 if hashlib is not available. Fortunately
# md5 can masquerade as hashlib for my purposes.
try:
    import hashlib
except ImportError:
    import md5 as hashlib

# 3rd party modules
import sysv_ipc

# Utils for this demo
import utils
if PY_MAJOR_VERSION > 2:
    import utils_for_3 as flex_utils
else:
    import utils_for_2 as flex_utils

utils.say("Oooo 'ello, I'm Mrs. Premise!")

params = utils.read_params()

# Create the message queue.
mq = sysv_ipc.MessageQueue(params["KEY"], sysv_ipc.IPC_CREX)

# The first message is a random string (the current time).
s = time.asctime()
utils.say("Sending %s" % s)
mq.send(s)
what_i_sent = s

for i in range(0, params["ITERATIONS"]):
    utils.say("iteration %d" % i)
    
    s, _ = mq.receive()
    s = s.decode()
    utils.say("Received %s" % s)

    # If the message is what I wrote, put it back on the queue.
    while s == what_i_sent:
        # Nothing new; give Mrs. Conclusion another chance to respond.
        mq.send(s)
        
        s, _ = mq.receive()
        s = s.decode()
        utils.say("Received %s" % s)

    # What I read must be the md5 of what I wrote or something's 
    # gone wrong.
    if PY_MAJOR_VERSION > 2:
        what_i_sent = what_i_sent.encode()
    try:
        assert(s == hashlib.md5(what_i_sent).hexdigest())
    except AssertionError:
        flex_utils.raise_error(AssertionError, "Message corruption after %d iterations." % i)

    # MD5 the reply and write back to Mrs. Conclusion.
    s = hashlib.md5(s.encode()).hexdigest()
    utils.say("Sending %s" % s)
    mq.send(s)
    what_i_sent = s

utils.say("")
utils.say("%d iterations complete" % (i + 1))

utils.say("Destroying the message queue.")
mq.remove()