-
Notifications
You must be signed in to change notification settings - Fork 7
/
simian.py
executable file
·2077 lines (1784 loc) · 69.2 KB
/
simian.py
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
# © Copyright 2015-. Triad National Security, LLC. All rights reserved.
#
# This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration.
#
# All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so.
#
# This is open source software; you can redistribute it and/or modify it under the terms of the BSD 3-clause License. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Full text of the BSD 3-clause License can be found in the License file in the main development branch of the repository.
#
##############################################################################
# BSD 3-clause license:
# Copyright 2015- Triad National Security, LLC
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##############################################################################
# Author: Nandakishore Santhi
# Date: 23 November, 2014
# Copyright: Open source, must acknowledge original author
# Purpose: PDES Engine in CPython and PyPy, mirroring most of the original LuaJIT version of Simian JIT-PDES
# NOTE: If speed rivaling C/C++ PDES engines is desired, consider adopting the LuaJIT version of Simian JIT-PDES
# NOTE: SimianPie External Dependencies: Other than standard Python3/Python2 modules, we will optionally need:
# greenlet module: For Simian process functionality only
# libmpich.[so/dylib/dll] shared library: For Simian parallel DES functionality only
#
##############################################################################
# Changelog:
#
# NOTE: 11/23/2014: Author: Nandakishore Santhi
# Original version of Simian for Lua, Python-2.7, and Javascript
#
# NOTE: 4/21/2020: Changes: Stephan Eidenbenz
# Simian for Python 3.7
#
# NOTE: 5/9/2020: Changes: Nandakishore Santhi
# Combined all Simian modules into a single standalone module file
# Updated LICENSE and COPYRIGHT notices
# Version bumped to 1.55
#
# NOTE: 5/12/2020: Changes: Nandakishore Santhi
# Added ability to switch context to a historical list of older processes
# when waking up from sleep. This is done using a stack by append/pop
# Made SimianError messages less cryptic at many places. More improvements are possible for later.
# Version bumped to 1.65 to better match prior version history
# Added a simulation related header/footer for all output log files
#
##############################################################################
__SimianVersion__ = "1.65"
import os, sys, math
import hashlib, heapq
import time as timeLib
import types #Used to bind Service at runtime to specific instances
import ctypes as C #For FFI of MPICH
# If mpich library is not explicitly provided when Simian is invoked with useMPI=True, then check for libmpich in parent directory of this file
defaultMpichLibName = os.path.join(os.path.dirname(__file__), "..", "/opt/mpich/lib/libmpich.so")
#===========================================================================================
# utils.py
#===========================================================================================
class SimianError(Exception):
def __init__(self, value): self.value = str(value)
def __str__(self): return self.value
#===========================================================================================
#===========================================================================================
# process.py
#===========================================================================================
greenlet = None
# This is a base class that all derived Processes will inherit from
class Process(object):
#ent.createProcess/proc.hibernate <=> proc.wake/ent.wakeProcess
#proc.sleep/proc.compute <=> ent.wakeProcess
def __init__(self, name, fun, thisEntity, thisParent):
global greenlet #Check for greenlet only if creating a process!
if not greenlet:
try:
from greenlet import greenlet
except:
raise SimianError("process.__init__(): you have initialized a Simian process - please install greenlet before using SimianPie to run simulations")
self.name = name
self.co = greenlet(run=fun) ###
self.started = False
self.suspended = False
self.main = [greenlet.getcurrent()] #To hold the main process for to/from context-switching within sleep/wake/hibernate
self.entity = thisEntity
self.parent = thisParent #Parent is None if created by entity
self._kindSet = {} #Set of kinds that it belongs to on its entity
self._childList = {}
def wake(thisProcess, *args):
#Arguments "*args" to __call => function-body
#Arguments "*args" to wake => LHS of hibernate
co = thisProcess.co
if co != None and not co.dead:
thisProcess.main.append(greenlet.getcurrent())
thisProcess.suspended = False
return co.switch(*args)
else:
raise SimianError("process.wake(): attempt to wake a process: " + thisProcess.name + " failed")
def hibernate(thisProcess, *args):
#Arguments "*args" to hibernate => LHS of wake
#Processes to be woken explicitly by events may return values
thisProcess.suspended = True
if len(thisProcess.main) == 0:
raise SimianError("process.hibernate(): attempt to context switch out of process: " + thisProcess.name + " failed")
return thisProcess.main.pop().switch(*args)
def sleep(thisProcess, x, *args):
#Processes which are to implicitly wake at set timeouts
#All return values are passed to __call/wake
if (not isinstance(x, (int, float))) or (x < 0):
raise SimianError("process.sleep(): not given non-negative number argument!" + thisProcess.name)
entity = thisProcess.entity
#Schedule a local alarm event after x timesteps to wakeup
entity.engine.schedService(entity.engine.now + x, "_wakeProcess",
thisProcess.name, entity.name, entity.num)
thisProcess.suspended = True
if len(thisProcess.main) == 0:
raise SimianError("process.sleep(): attempt to context switch out of process: " + thisProcess.name + " failed")
return thisProcess.main.pop().switch(*args)
def categorize(thisProcess, kind, name):
entity = thisProcess.entity
entity.categorize(kind, name) #Also categorize as @kind on entity
def unCategorize(thisProcess, kind, name):
entity = thisProcess.entity
entity.unCategorize(kind, name) #Also categorize as @kind on entity
def spawn(thisProcess, name, fun, kind=None):
#Create a new named processes as child or @kind
entity = thisProcess.entity
if name in entity._procList:
raise SimianError("process.spawn(): process by name '" + name + "' already exists in entity " + entity.name + "[" + str(entity.num) + "]")
entity.createProcess(name, fun, kind) #Creates a named process of kind type
#Make this a child of thisProcess
#NOTE: This is the difference between process.spawn and entity.createProcess
entity._procList[name].parent = thisProcess
thisProcess._childList[name] = True
def _killallChildren(thisProcess): #Hidden function to kill all children
entity = thisProcess.entity
for name,_ in thisProcess._childList.items(): #So we can delete stuff in _childList
proc = entity._procList[name] #Get actual process
proc.kill() #Kill child and all its subprocesses
thisProcess._childList = {} #A new child table
def kill(thisProcess, name=None): #Kills itself, or named child-process
#name: One of None or process-name
entity = thisProcess.entity
parent = thisProcess.parent
if name == None: #Kill self
thisProcess._killallChildren() #Killall children recursively
#Parent process is guaranteed to be alive
if parent: #Remove from child-list of parent
parent._childList.pop(thisProcess.name)
#Remove references from entity category and process lists
for k in thisProcess._kindSet:
entity._category[k].pop(thisProcess.name)
entity._procList.pop(thisProcess.name) #Remove all references to this process
co = thisProcess.co
thisProcess.co = None
co.throw() #Raise greenlet.GreenletExit
elif name == "*": #Kill every chid-process
thisProcess._killallChildren()
elif thisProcess._childList[name]: #Is this a child process?
proc = entity._procList[name]
proc.kill() #Kill it
def is_a(thisProcess, kind):
name = thisProcess.name
entity = thisProcess.entity
if (kind in entity._category) and (name in entity._category[kind]) and (name in entity._procList): #Is indeed a @kind?
return True
return False
def getCategoryNames(thisProcess):
kindSet = {}
n = 1
for k in thisProcess._kindSet:
kindSet[n] = k
n = n + 1
return kindSet
def getChildNames(thisProcess):
nameSet = {}
n = 1
for k in thisProcess._childList:
nameSet[n] = k
n = n + 1
return nameSet
def status(thisProcess):
if thisProcess.started:
try:
co = thisProcess.co
if co.dead:
return "dead"
elif thisProcess.suspended:
return "suspended"
else:
return "running"
except:
return "NonExistent"
else:
return "NotStarted"
#===========================================================================================
#===========================================================================================
# entity.py
#===========================================================================================
# This is a base class that all derived Entity classes will inherit from
class Entity(object):
def __init__(self, initInfo):
#Constructor of derived entity to be called as <entityName>(name, out, engine, num, reqServiceProxy, <args>)
#Here <args> are any additional arguments needed in the derived entity-class's __init__() method
self.name = initInfo["name"]
#self.out = initInfo["out"] #Log file for this instance
self.engine = initInfo["engine"] #Engine ... this will be the loop in asyncio
self.num = initInfo["num"] #Serial Number
self._procList = {} #A separate process table for each instance
self._category = {} #A map of sets for each kind of process
# For optimistic
self.VT = 0
self.processedEvents = []
self.sentEvents = []
def __str__(self):
return self.name + "(" + str(self.num) + ")"
def reqService(self, offset, eventName, data, rx=None, rxId=None):
#Purpose: Send an event if Simian is running.
engine = self.engine #Get the engine for this entity
if rx != None and offset < engine.minDelay:
if not engine.running: raise SimianError("entity.reqService(): sending event when Simian is idle!")
#If sending to self, then do not check against min-delay
#raise SimianError("entity.reqService(): " + self.name + "[" + str(self.num) + "]" + " attempted to send with too little delay")
color = "white"
time = engine.now + offset
if engine.optimistic:
if offset == 0:
offset = 0.000000001 # event needs to be STRICTLY not the same time
time = self.VT + offset
if engine.color == "red":
color = "red"
else:
if time > engine.endTime: #No need to send this event, needed for optimism
return
if rx == None: rx = self.name
if rxId == None: rxId = self.num
e = {
"tx": self.name, #String
"txId": self.num, #Number
"rx": rx, #String
"rxId": rxId, #Number
"name": eventName, #String
"data": data, #Object
"time": time, #Number
"antimessage" : False,
"GVT" : False,
"color" : color,
}
if engine.optimistic:
ae = {
"tx": self.name, #String
"txId": self.num, #Number
"rx": rx, #String
"rxId": rxId, #Number
"name": eventName, #String
"data": data, #Object
"time": time, #Number
"antimessage" : True,
"GVT" : False,
"color" : color,
}
self.sentEvents.append(ae)
# this is a particular mechanism added by Jason Liu for
# allowing different mappings from LPs to ranks
recvRank = engine.getOffsetRank(rx, rxId)
if recvRank == engine.rank: #Send to self
self.engine.ec += 1
heapq.heappush(engine.eventQueue, (time, self.engine.ec, e))
else:
if engine.optimistic:
if engine.color == "white":
engine.whiteMsg += 1
else:
engine.t_min = min(engine.t_min, time)
engine.MPI.send(e, recvRank)
else:
#print (e)
engine.MPI.sendAndCount(e, recvRank)
def saveAntimessages(self,state):
state['antimessages'] = list(self.sentEvents)
self.sentEvents = []
return dict(state)
def recoverAntimessages(self, state, time):
engine = self.engine
if state['antimessages']:
events = state['antimessages']
#print events
for event in events:
recvRank = engine.getOffsetRank(event["rx"], event["rxId"])
if recvRank == engine.rank: #Send to self
engine.ec += 1
heapq.heappush(engine.eventQueue, (event["time"], engine.ec, event))
else:
engine.MPI.send(event, recvRank)
engine.antimsgSent += 1
def attachService(self, name, fun):
#Attaches a service at runtime to instance
setattr(self, name, types.MethodType(fun, self))
#Following code is to support coroutine processes on entities:
#Entity methods to interact with processes
def createProcess(self, name, fun, kind=None): #Creates a named process
if name == "*":
raise SimianError("entity.createProcess(): reserved name to represent all child processes: " + name)
proc = Process(name, fun, self, None) #No parent means, entity is parent
if not proc:
raise SimianError("entity.createProcess(): could not create a valid process named: " + name)
self._procList[name] = proc
if kind != None:
self.categorizeProcess(kind, name) #Categorize
def startProcess(self, name, *args): #Starts a named process
if name in self._procList:
proc = self._procList[name]
if not proc.started:
proc.started = True
#When starting, pass process instance as first arg, which can be accessed inside the "fun"
return proc.wake(proc, *args)
else:
raise SimianError("entity.startProcess(): starting an already started process: " + proc.name)
def _wakeProcess(self, name, tx=None, txId=None): #Hidden: implicit wake a named process without arguments
if name in self._procList:
proc = self._procList[name]
return proc.wake()
def wakeProcess(self, name, *args): #Wake a named process with arguments
if not (name in self._procList):
raise SimianError("entity.wakeProcess(): attempted to wake a non existant process: " + name)
else: #If existing and not been killed asynchronously
proc = self._procList[name]
return proc.wake(*args)
def killProcess(self, name): #Kills named process or all entity-processes
if name: #Kills named child-process
proc = self._procList[name]
proc.kill() #Kill itself and all subprocesses
else: #Kills all subprocesses
for _,proc in self._procList.items(): #So we can delete while iterating
proc.kill() #Kill itself and all subprocesses
self._procList = {} #A new process table
def killProcessKind(self, kind): #Kills all @kind processes on entity
if not (kind in self._category):
raise SimianError("entity.killProcessKind(): no category of processes on this entity called " + str(kind))
else:
nameSet = self._category[kind]
for name,_ in nameSet.items(): #So we can delete while iterating
proc = self._procList[name]
proc.kill() #Kill itself and all subprocesses
def statusProcess(self, name):
if not (name in self._procList):
return "NonExistent"
else:
proc = self._procList[name]
return proc.status()
def categorizeProcess(self, kind, name): #Check for existing process and then categorize
if name in self._procList:
proc = self._procList[name]
#Categorize both ways for easy lookup
proc._kindSet[kind] = True #Indicate to proc that it is of this kind to its entity
#Indicate to entity that proc is of this kind
if not kind in self._category: self._category[kind] = {name: True} #New kind
else: self._category[kind][name] = True #Existing kind
else: raise SimianError("entity.categorizeProcess(): expects a proper child to categorize")
def unCategorizeProcess(self, kind, name):
#Check for existing process and then unCategorize
if name in self._procList:
proc = self._procList[name]
#unCategorize both ways for easy lookup
proc._kindSet.pop(kind) #Indicate to proc that it is not of this kind to its entity
#Indicate to entity that proc is not of this kind
if kind in self._category:
self._category[kind].pop(name) #Existing kind deleted
else: raise SimianError("entity.unCategorizeProcess(): expects a proper child to un-categorize")
def isProcess(self, name, kind):
if name in self._procList:
proc = self._procList[name]
return proc.is_a(kind)
else:
return False
def getProcess(self, name):
#A reference to a named process is returned if it exists
#NOTE: User should delete it to free its small memory when no longer needed
if name in self._procList:
proc = self._procList[name]
return proc
else: return None
def getCategoryNames(self):
kindSet = {}
n = 1
for k in self._category:
kindSet[n] = k
n = n + 1
return kindSet
def getProcessNames(self):
nameSet = {}
n = 1
for k in self._procList:
nameSet[n] = k
n = n + 1
return nameSet
#===========================================================================================
#===========================================================================================
# umsgPack.py
# umsgpack-python-pure can be substituted with msgpack-pure or msgpack-python
# NOTE: This module is under a different licence till this message appears again
#===========================================================================================
# u-msgpack-python v2.1 - vsergeev at gmail
# https://github.com/vsergeev/u-msgpack-python
#
# u-msgpack-python is a lightweight MessagePack serializer and deserializer
# module, compatible with both Python 2 and 3, as well CPython and PyPy
# implementations of Python. u-msgpack-python is fully compliant with the
# latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
# particular, it supports the new binary, UTF-8 string, and application ext
# types.
#
# MIT License
#
# Copyright (c) 2013-2014 Ivan A. Sergeev
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
"""
u-msgpack-python v2.1 - vsergeev at gmail
https://github.com/vsergeev/u-msgpack-python
u-msgpack-python is a lightweight MessagePack serializer and deserializer
module, compatible with both Python 2 and 3, as well CPython and PyPy
implementations of Python. u-msgpack-python is fully compliant with the
latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
particular, it supports the new binary, UTF-8 string, and application ext
types.
License: MIT
"""
__version__ = "2.1"
"Module version string"
version = (2,1)
"Module version tuple"
import struct
import collections
import sys
import io
################################################################################
### Ext Class
################################################################################
# Extension type for application-defined types and data
class Ext:
"""
The Ext class facilitates creating a serializable extension object to store
an application-defined type and data byte array.
"""
def __init__(self, type, data):
"""
Construct a new Ext object.
Args:
type: application-defined type integer from 0 to 127
data: application-defined data byte array
Raises:
TypeError:
Specified ext type is outside of 0 to 127 range.
Example:
>>> foo = umsgpack.Ext(0x05, b"\x01\x02\x03")
>>> umsgpack.packb({u"special stuff": foo, u"awesome": True})
'\x82\xa7awesome\xc3\xadspecial stuff\xc7\x03\x05\x01\x02\x03'
>>> bar = umsgpack.unpackb(_)
>>> print(bar["special stuff"])
Ext Object (Type: 0x05, Data: 01 02 03)
>>>
"""
# Application ext type should be 0 <= type <= 127
if not isinstance(type, int) or not (type >= 0 and type <= 127):
raise TypeError("ext type out of range")
# Check data is type bytes
elif sys.version_info[0] == 3 and not isinstance(data, bytes):
raise TypeError("ext data is not type \'bytes\'")
elif sys.version_info[0] == 2 and not isinstance(data, str):
raise TypeError("ext data is not type \'str\'")
self.type = type
self.data = data
def __eq__(self, other):
"""
Compare this Ext object with another for equality.
"""
return (isinstance(other, self.__class__) and
self.type == other.type and
self.data == other.data)
def __ne__(self, other):
"""
Compare this Ext object with another for inequality.
"""
return not self.__eq__(other)
def __str__(self):
"""
String representation of this Ext object.
"""
s = "Ext Object (Type: 0x%02x, Data: " % self.type
for i in range(min(len(self.data), 8)):
if i > 0:
s += " "
if isinstance(self.data[i], int):
s += "%02x" % (self.data[i])
else:
s += "%02x" % ord(self.data[i])
if len(self.data) > 8:
s += " ..."
s += ")"
return s
################################################################################
### Exceptions
################################################################################
# Base Exception classes
class PackException(Exception):
"Base class for exceptions encountered during packing."
pass
class UnpackException(Exception):
"Base class for exceptions encountered during unpacking."
pass
# Packing error
class UnsupportedTypeException(PackException):
"Object type not supported for packing."
pass
# Unpacking error
class InsufficientDataException(UnpackException):
"Insufficient data to unpack the encoded object."
pass
class InvalidStringException(UnpackException):
"Invalid UTF-8 string encountered during unpacking."
pass
class ReservedCodeException(UnpackException):
"Reserved code encountered during unpacking."
pass
class UnhashableKeyException(UnpackException):
"""
Unhashable key encountered during map unpacking.
The serialized map cannot be deserialized into a Python dictionary.
"""
pass
class DuplicateKeyException(UnpackException):
"Duplicate key encountered during map unpacking."
pass
# Backwards compatibility
KeyNotPrimitiveException = UnhashableKeyException
KeyDuplicateException = DuplicateKeyException
################################################################################
### Exported Functions and Globals
################################################################################
# Exported functions and variables, set up in __init()
pack = None
packb = None
unpack = None
unpackb = None
dump = None
dumps = None
load = None
loads = None
compatibility = False
"""
Compatibility mode boolean.
When compatibility mode is enabled, u-msgpack-python will serialize both
unicode strings and bytes into the old "raw" msgpack type, and deserialize the
"raw" msgpack type into bytes. This provides backwards compatibility with the
old MessagePack specification.
Example:
>>> umsgpack.compatibility = True
>>>
>>> umsgpack.packb([u"some string", b"some bytes"])
b'\x92\xabsome string\xaasome bytes'
>>> umsgpack.unpackb(_)
[b'some string', b'some bytes']
>>>
"""
################################################################################
### Packing
################################################################################
# You may notice struct.pack("B", obj) instead of the simpler chr(obj) in the
# code below. This is to allow for seamless Python 2 and 3 compatibility, as
# chr(obj) has a str return type instead of bytes in Python 3, and
# struct.pack(...) has the right return type in both versions.
def _pack_integer(obj, fp):
if obj < 0:
if obj >= -32:
fp.write(struct.pack("b", obj))
elif obj >= -2**(8-1):
fp.write(b"\xd0" + struct.pack("b", obj))
elif obj >= -2**(16-1):
fp.write(b"\xd1" + struct.pack(">h", obj))
elif obj >= -2**(32-1):
fp.write(b"\xd2" + struct.pack(">i", obj))
elif obj >= -2**(64-1):
fp.write(b"\xd3" + struct.pack(">q", obj))
else:
raise UnsupportedTypeException("huge signed int")
else:
if obj <= 127:
fp.write(struct.pack("B", obj))
elif obj <= 2**8-1:
fp.write(b"\xcc" + struct.pack("B", obj))
elif obj <= 2**16-1:
fp.write(b"\xcd" + struct.pack(">H", obj))
elif obj <= 2**32-1:
fp.write(b"\xce" + struct.pack(">I", obj))
elif obj <= 2**64-1:
fp.write(b"\xcf" + struct.pack(">Q", obj))
else:
raise UnsupportedTypeException("huge unsigned int")
def _pack_nil(obj, fp):
fp.write(b"\xc0")
def _pack_boolean(obj, fp):
fp.write(b"\xc3" if obj else b"\xc2")
def _pack_float(obj, fp):
if _float_size == 64:
fp.write(b"\xcb" + struct.pack(">d", obj))
else:
fp.write(b"\xca" + struct.pack(">f", obj))
def _pack_string(obj, fp):
obj = obj.encode('utf-8')
if len(obj) <= 31:
fp.write(struct.pack("B", 0xa0 | len(obj)) + obj)
elif len(obj) <= 2**8-1:
fp.write(b"\xd9" + struct.pack("B", len(obj)) + obj)
elif len(obj) <= 2**16-1:
fp.write(b"\xda" + struct.pack(">H", len(obj)) + obj)
elif len(obj) <= 2**32-1:
fp.write(b"\xdb" + struct.pack(">I", len(obj)) + obj)
else:
raise UnsupportedTypeException("huge string")
def _pack_binary(obj, fp):
if len(obj) <= 2**8-1:
fp.write(b"\xc4" + struct.pack("B", len(obj)) + obj)
elif len(obj) <= 2**16-1:
fp.write(b"\xc5" + struct.pack(">H", len(obj)) + obj)
elif len(obj) <= 2**32-1:
fp.write(b"\xc6" + struct.pack(">I", len(obj)) + obj)
else:
raise UnsupportedTypeException("huge binary string")
def _pack_oldspec_raw(obj, fp):
if len(obj) <= 31:
fp.write(struct.pack("B", 0xa0 | len(obj)) + obj)
elif len(obj) <= 2**16-1:
fp.write(b"\xda" + struct.pack(">H", len(obj)) + obj)
elif len(obj) <= 2**32-1:
fp.write(b"\xdb" + struct.pack(">I", len(obj)) + obj)
else:
raise UnsupportedTypeException("huge raw string")
def _pack_ext(obj, fp):
if len(obj.data) == 1:
fp.write(b"\xd4" + struct.pack("B", obj.type & 0xff) + obj.data)
elif len(obj.data) == 2:
fp.write(b"\xd5" + struct.pack("B", obj.type & 0xff) + obj.data)
elif len(obj.data) == 4:
fp.write(b"\xd6" + struct.pack("B", obj.type & 0xff) + obj.data)
elif len(obj.data) == 8:
fp.write(b"\xd7" + struct.pack("B", obj.type & 0xff) + obj.data)
elif len(obj.data) == 16:
fp.write(b"\xd8" + struct.pack("B", obj.type & 0xff) + obj.data)
elif len(obj.data) <= 2**8-1:
fp.write(b"\xc7" + struct.pack("BB", len(obj.data), obj.type & 0xff) + obj.data)
elif len(obj.data) <= 2**16-1:
fp.write(b"\xc8" + struct.pack(">HB", len(obj.data), obj.type & 0xff) + obj.data)
elif len(obj.data) <= 2**32-1:
fp.write(b"\xc9" + struct.pack(">IB", len(obj.data), obj.type & 0xff) + obj.data)
else:
raise UnsupportedTypeException("huge ext data")
def _pack_array(obj, fp):
if len(obj) <= 15:
fp.write(struct.pack("B", 0x90 | len(obj)))
elif len(obj) <= 2**16-1:
fp.write(b"\xdc" + struct.pack(">H", len(obj)))
elif len(obj) <= 2**32-1:
fp.write(b"\xdd" + struct.pack(">I", len(obj)))
else:
raise UnsupportedTypeException("huge array")
for e in obj:
pack(e, fp)
def _pack_map(obj, fp):
if len(obj) <= 15:
fp.write(struct.pack("B", 0x80 | len(obj)))
elif len(obj) <= 2**16-1:
fp.write(b"\xde" + struct.pack(">H", len(obj)))
elif len(obj) <= 2**32-1:
fp.write(b"\xdf" + struct.pack(">I", len(obj)))
else:
raise UnsupportedTypeException("huge array")
for k,v in obj.items():
pack(k, fp)
pack(v, fp)
########################################
# Pack for Python 2, with 'unicode' type, 'str' type, and 'long' type
def _pack2(obj, fp):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
fp: a .write()-supporting file-like object
Returns:
None.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> f = open('test.bin', 'w')
>>> umsgpack.pack({u"compact": True, u"schema": 0}, f)
>>>
"""
global compatibility
if obj is None:
_pack_nil(obj, fp)
elif isinstance(obj, bool):
_pack_boolean(obj, fp)
elif isinstance(obj, int) or isinstance(obj, long):
_pack_integer(obj, fp)
elif isinstance(obj, float):
_pack_float(obj, fp)
elif compatibility and isinstance(obj, unicode):
_pack_oldspec_raw(bytes(obj), fp)
elif compatibility and isinstance(obj, bytes):
_pack_oldspec_raw(obj, fp)
elif isinstance(obj, unicode):
_pack_string(obj, fp)
elif isinstance(obj, str):
_pack_binary(obj, fp)
elif isinstance(obj, list) or isinstance(obj, tuple):
_pack_array(obj, fp)
elif isinstance(obj, dict):
_pack_map(obj, fp)
elif isinstance(obj, Ext):
_pack_ext(obj, fp)
else:
raise UnsupportedTypeException("unsupported type: %s" % str(type(obj)))
# Pack for Python 3, with unicode 'str' type, 'bytes' type, and no 'long' type
def _pack3(obj, fp):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
fp: a .write()-supporting file-like object
Returns:
None.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> f = open('test.bin', 'w')
>>> umsgpack.pack({u"compact": True, u"schema": 0}, fp)
>>>
"""
global compatibility
if obj is None:
_pack_nil(obj, fp)
elif isinstance(obj, bool):
_pack_boolean(obj, fp)
elif isinstance(obj, int):
_pack_integer(obj, fp)
elif isinstance(obj, float):
_pack_float(obj, fp)
elif compatibility and isinstance(obj, str):
_pack_oldspec_raw(obj.encode('utf-8'), fp)
elif compatibility and isinstance(obj, bytes):
_pack_oldspec_raw(obj, fp)
elif isinstance(obj, str):
_pack_string(obj, fp)
elif isinstance(obj, bytes):
_pack_binary(obj, fp)
elif isinstance(obj, list) or isinstance(obj, tuple):
_pack_array(obj, fp)
elif isinstance(obj, dict):
_pack_map(obj, fp)
elif isinstance(obj, Ext):
_pack_ext(obj, fp)
else:
raise UnsupportedTypeException("unsupported type: %s" % str(type(obj)))
def _packb2(obj):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Returns:
A 'str' containing serialized MessagePack bytes.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> umsgpack.packb({u"compact": True, u"schema": 0})
'\x82\xa7compact\xc3\xa6schema\x00'
>>>
"""
fp = io.BytesIO()
_pack2(obj, fp)
return fp.getvalue()
def _packb3(obj):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Returns:
A 'bytes' containing serialized MessagePack bytes.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> umsgpack.packb({u"compact": True, u"schema": 0})
b'\x82\xa7compact\xc3\xa6schema\x00'
>>>
"""
fp = io.BytesIO()
_pack3(obj, fp)
return fp.getvalue()
################################################################################
### Unpacking
################################################################################
def _read_except(fp, n):
data = fp.read(n)
if len(data) < n:
raise InsufficientDataException()
return data
def _unpack_integer(code, fp):
if (ord(code) & 0xe0) == 0xe0:
return struct.unpack("b", code)[0]
elif code == b'\xd0':
return struct.unpack("b", _read_except(fp, 1))[0]
elif code == b'\xd1':
return struct.unpack(">h", _read_except(fp, 2))[0]
elif code == b'\xd2':
return struct.unpack(">i", _read_except(fp, 4))[0]
elif code == b'\xd3':
return struct.unpack(">q", _read_except(fp, 8))[0]
elif (ord(code) & 0x80) == 0x00:
return struct.unpack("B", code)[0]
elif code == b'\xcc':
return struct.unpack("B", _read_except(fp, 1))[0]
elif code == b'\xcd':
return struct.unpack(">H", _read_except(fp, 2))[0]
elif code == b'\xce':
return struct.unpack(">I", _read_except(fp, 4))[0]
elif code == b'\xcf':
return struct.unpack(">Q", _read_except(fp, 8))[0]
raise Exception("logic error, not int: 0x%02x" % ord(code))
def _unpack_reserved(code, fp):
if code == b'\xc1':
raise ReservedCodeException("encountered reserved code: 0x%02x" % ord(code))
raise Exception("logic error, not reserved code: 0x%02x" % ord(code))
def _unpack_nil(code, fp):
if code == b'\xc0':
return None
raise Exception("logic error, not nil: 0x%02x" % ord(code))
def _unpack_boolean(code, fp):
if code == b'\xc2':
return False
elif code == b'\xc3':
return True
raise Exception("logic error, not boolean: 0x%02x" % ord(code))
def _unpack_float(code, fp):
if code == b'\xca':
return struct.unpack(">f", _read_except(fp, 4))[0]
elif code == b'\xcb':
return struct.unpack(">d", _read_except(fp, 8))[0]
raise Exception("logic error, not float: 0x%02x" % ord(code))