/usr/lib/python2.7/dist-packages/chempy/dictdb.py is in pymol 1.7.0.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific.
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove this copyright notice.
#F* -------------------------------------------------------------------
#G* Please see the accompanying LICENSE file for further information.
#H* -------------------------------------------------------------------
#I* Additional authors of this source file include:
#-*
#-*
#-*
#Z* -------------------------------------------------------------------
import threading
import socket
import cPickle
import socket # For gethostbyaddr()
import SocketServer
import sys
import traceback
import copy
import os
# Dictionary Emulator Object Database
#
# After being constructed, DictDBLocal and DictDBClient objects
# work like dictionary objects, but with the following additional methods:
#
# standby() optimizes index file to incorporate changes and purges
# indexes from memory (indexes will be reread upon next call, if any)
#
# purge() repacks the database and index files to eliminate wasted space
#
# get_info() returns DictDBInfo object containing database statistics
#
# shutdown() terminates the database server (only useful for remote clients)
#
# reset() clears database
# PART 1
# Database Engine, with a thread-safe API
class DictDBInfo:
def __init__(self):
self.used = 0 # bytes containing data
self.wasted = 0 # bytes wasted (from deleted/overwitten records)
class DictDBLocal:
__magic__ = r'*8#~' # 32-bit record stamp for record
__delete_magic__ = '*8#@' # 32-bit record stamp for deleted record
def __init__(self,prefix,bin=1,read_only=0):
# store important information
self.index_file = prefix + ".dbi" # database information (can be reconstructed from .dbf)
self.data_file = prefix + ".dbf" # database data
self.bin = bin
self.changed = 0
self.read_only = read_only
# create lock
self.lock = threading.RLock() # NOTE: recursive for convenience
# restore indexed into memory
self._restore()
def get_info(self):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
# generate independent copy for calling thread
result = copy.deepcopy(self.info)
finally:
self.lock.release()
return result
def has_key(self,key):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
result = self.rec.has_key(key)
finally:
self.lock.release()
return result
def keys(self):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
# get list of keys (thread safe...result is a new object)
result = self.rec.keys()
finally:
self.lock.release()
return result
def __delitem__(self,key):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
if self.rec.has_key(key):
# account for space
if self.rec.has_key(key):
self.info.wasted = self.info.wasted + self.rec[key][1]
# delete record
del self.rec[key]
if not self.read_only:
# write delete magic to data file for recovery
f=open(self.data_file,'ab')
f.write(self.__delete_magic__)
cPickle.dump(key,f,self.bin)
f.close()
# write blank index to index file
f=open(self.index_file,'ab')
cPickle.dump((key,None),f,self.bin)
f.close()
# note change
self.changed = 1
else:
raise KeyError(key)
finally:
self.lock.release()
return result
def standby(self):
result = None
# only do something if dictionary is already in RAM
if hasattr(self,'rec') and not self.read_only:
try:
self.lock.acquire()
# write index file
f=open(self.index_file,'wb')
cPickle.dump(self.info,f,self.bin)
cPickle.dump(self.rec,f,self.bin)
f.close()
# free memory
del self.rec
del self.info
finally:
self.lock.release()
return result
def reset(self):
result = None
try:
self.lock.acquire()
if not self.read_only:
# make sure files exist and are writable
f = open(self.index_file,'wb')
f.close()
f = open(self.data_file,'wb')
f.close()
# new database information
self.info = DictDBInfo()
self.rec = {}
self.changed = 1
self.standby() # write out blank indexes (important)
finally:
self.lock.release()
return result
def purge(self):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
if not self.read_only:
# open source and temporary data files
tmp_data = self.data_file + '_tmp'
f = open(self.data_file,'rb')
g = open(tmp_data,'wb')
rec = self.rec
used = 0
# iterate through records, copying only those which are extant
for key in self.rec.keys():
f.seek(rec[key][0])
g.write(self.__magic__)
cPickle.dump(key,g,self.bin);
start = g.tell()
g.write(f.read(rec[key][1]))
used = used + rec[key][1]
rec[key]=(start,rec[key][1]) # generate new record entry
f.close()
g.close()
# now perform the switch-over
os.unlink(self.index_file) # delete old index file...
os.unlink(self.data_file) # delete old data file
os.rename(tmp_data,self.data_file) # move new data file over old
# update database information
self.info.used = used
self.info.wasted = 0
# write new index and information file
f=open(self.index_file,'wb')
cPickle.dump(self.info,f,self.bin)
cPickle.dump(self.rec,f,self.bin)
f.close()
finally:
self.lock.release()
return result
def shutdown(self): # dummy
return None
def __getitem__(self,key): # get with object
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
if self.rec.has_key(key):
# locate and retrieve object
f=open(self.data_file,'rb')
f.seek(self.rec[key][0])
result = cPickle.load(f)
f.close()
else:
raise KeyError(key)
finally:
self.lock.release()
return result
def _get(self,key): # get with string (for remote connections)
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
if self.rec.has_key(key):
# locate and retrieve string
f=open(self.data_file,'rb')
f.seek(self.rec[key][0])
result = f.read(self.rec[key][1])
f.close()
finally:
self.lock.release()
return result
def __setitem__(self,key,object):
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
# append data onto data file
f=open(self.data_file,'ab')
f.write(self.__magic__) # for recovery
cPickle.dump(key,f,self.bin) # for recovery
start = f.tell()
cPickle.dump(object,f,self.bin)
record_info = (start,f.tell()-start)
f.close()
# account for space (if replacing)
if self.rec.has_key(key):
self.info.wasted = self.info.wasted + self.rec[key][1]
# update record info
self.rec[key] = record_info
# account for space
self.info.used = self.info.used + record_info[1]
# append new record onto index file
f=open(self.index_file,'ab')
cPickle.dump((key,record_info),f,self.bin)
f.close()
# note change
self.changed = 1
finally:
self.lock.release()
return result
def _set(self,key,data_string): # set with string (for remote connections)
result = None
# restore dictionary (if nec.)
if not hasattr(self,'rec'):
self._restore()
try:
self.lock.acquire()
self.changed = 1
if not self.read_only:
# append data onto data file
f=open(self.data_file,'ab')
f.write(self.__magic__) # for recovery
cPickle.dump(key,f,self.bin) # for recovery
start = f.tell()
f.write(data_string)
record_info = (start,f.tell()-start)
f.close()
# account for space (if replacing)
if self.rec.has_key(key):
self.info.wasted = self.info.wasted + self.rec[key][1]
# update record info
self.rec[key] = record_info
# account for space
self.info.used = self.info.used + record_info[1]
if not self.read_only:
# append new record onto index file
f=open(self.index_file,'ab')
cPickle.dump((key,record_info),f,self.bin)
f.close()
finally:
self.lock.release()
return result
def _recover(self): # rebuild index from data file
result = None
# need to write recovery routine...
self.info = DictDBInfo()
self.rec = {}
try:
try:
self.lock.acquire()
f=open(self.data_file,'rb')
# find length of file
f.seek(0,2)
eof = f.tell()
f.seek(0,0)
# create locals for better performance
rec = self.rec
self_info = self.info
while f.tell()!=eof:
chk = f.read(4)
if chk==self.__magic__: # recover extant record
key = cPickle.load(f)
start = f.tell()
data = cPickle.load(f)
record_info = (start,f.tell()-start)
# account for space (if replacing)
if rec.has_key(key):
self_info.wasted = self_info.wasted + rec[key][1]
rec[key] = record_info
# account for psace
self_info.used = self_info.used + record_info[1]
elif chk==self.__delete_magic__: # delete already recovered record
key = cPickle.load(f)
if rec.has_key(key):
# account for space
self_info.wasted = self_info.wasted + rec[key][1]
del rec[key]
else:
raise RuntimeError('Bad Magic')
except:
print " dictdb error: database recovery failed."
traceback.print_exc()
sys.exit(1)
if not self.read_only:
# write recovered indexes to a new index file
f = open(self.index_file,'wb')
cPickle.dump(self.info,f,self.bin)
cPickle.dump(self.rec,f,self.bin)
f.close()
finally:
self.lock.release()
return result
def _restore(self):
result = None
try:
self.lock.acquire()
# make sure files exist and are writable
f = open(self.index_file,'ab')
f.close()
f = open(self.data_file,'ab')
f.close()
# read current indexes
f = open(self.index_file,'rb')
# find length of file
f.seek(0,2)
eof = f.tell()
f.seek(0,0)
# start reading and appending recent changes (if any)
try:
self.info = cPickle.load(f)
self.rec = cPickle.load(f)
# use locals for better performance
rec = self.rec
cPickle_load = cPickle.load
self_info = self.info
while f.tell()!=eof:
key, info = cPickle_load(f)
if info!=None:
# account for space (if replacing)
if rec.has_key(key):
self_info.wasted = self_info.wasted + rec[key][1]
# set record infor
rec[key] = info
# account for space
self_info.used = self_info.used + info[1]
else:
# account for space (if deleting object)
self_info.wasted = self_info.wasted + rec[key][1]
del rec[key]
f.close()
except EOFError:
# if error occurs when reading indexes, then do a datafile-based recovery
f.close()
self._recover()
finally:
self.lock.release()
return result
# PART 2
# Database client
class DictDBClient:
def __init__(self,host='localhost',port=8000):
self.host=host
self.port=port
self.sock = None
def _remote_call(self,meth,args,kwds):
result = None
if self.sock == None:
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.connect((self.host,self.port))
self.send = self.sock.makefile('w')
self.recv = self.sock.makefile('r')
cPickle.dump(meth,self.send,1) # binary by default
cPickle.dump(args,self.send,1)
cPickle.dump(kwds,self.send,1)
self.send.flush()
result = cPickle.load(self.recv)
return result
def __getitem__(self,key):
if self._remote_call('has_key',(key,),{}):
return cPickle.loads(self._remote_call('_get',(key,),{}))
else:
raise KeyError(key)
def __setitem__(self,key,object):
self.changed = 1
return self._remote_call('_set',(key,cPickle.dumps(object)),{})
def __delitem__(self,key):
if self._remote_call('has_key',(key,),{}):
return self._remote_call('__delitem__',(key,),{})
else:
raise KeyError(key)
def standby(self):
return self._remote_call('standby',(),{})
def shutdown(self):
try:
# multiple connections are sometimes required...
self._remote_call('shutdown',(),{})
self.sock=None
self._remote_call('shutdown',(),{})
self.sock=None
self._remote_call('shutdown',(),{})
self.sock=None
self._remote_call('shutdown',(),{})
except:
pass
return None
def purge(self):
return self._remote_call('purge',(),{})
def reset(self):
return self._remote_call('reset',(),{})
def keys(self):
return self._remote_call('keys',(),{})
def has_key(self,key):
return self._remote_call('has_key',(key,),{})
def get_info(self):
return self._remote_call('get_info',(),{})
# PART 3
# Database Socket Server
class DictDBServer:
def __init__(self,prefix,port=''):
sys.setcheckinterval(0)
server_address = ('', port)
ddbs = _DictDBServer(server_address, DictDBRequestHandler)
# assign dict database to this server
ddbs.dictdb = DictDBLocal(prefix)
# now serve requests forever
ddbs.keep_alive = 1
while ddbs.keep_alive:
ddbs.handle_request()
class _DictDBServer(SocketServer.ThreadingTCPServer):
def server_bind(self):
"""Override server_bind to store the server name."""
SocketServer.ThreadingTCPServer.server_bind(self)
host, port = self.socket.getsockname()
if not host or host == '0.0.0.0':
host = socket.gethostname()
hostname, hostnames, hostaddrs = socket.gethostbyaddr(host)
if '.' not in hostname:
for host in hostnames:
if '.' in host:
hostname = host
break
self.server_name = hostname
self.server_port = port
class DictDBRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
while self.server.keep_alive:
# get method name from client
try:
method = cPickle.load(self.rfile)
except EOFError,socket.error:
break
if method == 'shutdown':
self.server.keep_alive = 0
# get arguments from client
args = cPickle.load(self.rfile)
kw = cPickle.load(self.rfile)
# get method pointer
meth_obj = getattr(self.server.dictdb,method)
# print method,args,kw
# call method and return result
cPickle.dump(apply(meth_obj,args,kw),self.wfile,1) # binary by default
self.wfile.flush()
def server_test(port = 8000,prefix='test_dictdb'):
print 'Testing DictDBServer on port',str(port)
fp = DictDBServer(prefix,port=port) # socket servers don't terminate
def client_test(host,port=8000):
print 'Testing Client with Server on port',str(port)
tdb = DictDBClient(port=port)
tdb['test']='hello'
print tdb['test']
try:
print tdb['nonexistent']
except KeyError:
print " key error 1 as expected"
try:
del tdb['nonexistent']
except KeyError:
print " key error 2 as expected"
tdb['extra'] = 'hi'
print tdb.has_key('extra')
print tdb.keys()
if __name__=='__main__':
import os
print '***Testing DictDB***:'
ddb = DictDBLocal('test_dictdb')
print ddb.keys()
ddb['test']='some data object'
print ddb['test']
ddb['another']='another data object'
print ddb['another']
ddb['test']='some updated data object'
print ddb['test']
del ddb
ddb = DictDBLocal('test_dictdb')
ddb['whoa']='whoa data object'
print ddb['test']
ddb['dude']='dude data object'
print ddb['dude']
ddb['number'] = 9999
print ddb['number']
ddb.standby()
del ddb
ddb = DictDBLocal('test_dictdb')
print 'Current keys:'+str(ddb.keys())
print ddb['test']
print ddb['another']
print '***Testing raw string methods:'
print cPickle.loads(ddb._get('test'))
print cPickle.loads(ddb._get('another'))
ddb._set('some_key',cPickle.dumps("raw test1"))
print ddb['some_key']
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
del ddb
os.unlink("test_dictdb.dbi")
ddb = DictDBLocal('test_dictdb')
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
del ddb
os.unlink("test_dictdb.dbi")
ddb = DictDBLocal('test_dictdb')
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
ddb.standby()
del ddb
ddb = DictDBLocal('test_dictdb')
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
del ddb
ddb = DictDBLocal('test_dictdb')
ddb.standby()
ddb['reactivated'] = 1234
print ddb.has_key('reactivated')
ddb.standby()
ddb['reactivated'] = 495
print ddb['reactivated']
try:
print ddb['nonexistent']
except KeyError:
print " key error 1 as expected"
try:
del ddb['nonexistent']
except KeyError:
print " key error 2 as expected"
print "purge test:"
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
ddb.purge()
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
del ddb
ddb = DictDBLocal('test_dictdb')
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
ddb['hello']=10
ddb[123] = 'bacon'
ddb['green']= 'color'
print ddb['hello']
print ddb.keys()
print ddb.has_key('green')
print ddb.has_key('blue')
del ddb['hello']
try:
print ddb['hello']
except KeyError:
print ' got expected key error 1'
try:
del ddb['hello']
except KeyError:
print ' got expected key error 2'
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
ddb.purge()
info = ddb.get_info()
print info.used,info.wasted,info.used-info.wasted
print ddb['green']
import random
ddc=DictDBLocal('test_dictdb')
print "loading..."
lst = []
for a in xrange(1,250):
ddc[a]=str(a)
lst.append([random.random(),a])
ddc[str(a)] = a
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print 'verifying...'
for a in xrange(1,250):
if ddc[a]!=str(a):
raise RuntimeError
for a in xrange(1,250):
del ddc[str(a)]
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print 'verifying...'
for a in xrange(1,250):
if ddc[a]!=str(a):
raise RuntimeError
del ddc
ddc=DictDBLocal('test_dictdb')
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print 'verifying...'
for a in xrange(1,250):
if ddc[a]!=str(a):
raise RuntimeError
ddc.standby()
del ddc
os.unlink("test_dictdb.dbi")
print "unlink test"
ddc=DictDBLocal('test_dictdb')
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print 'verifying...'
for a in xrange(1,250):
if ddc[a]!=str(a):
raise RuntimeError
ddc.purge()
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print 'verifying...'
for a in xrange(1,250):
if ddc[a]!=str(a):
raise RuntimeError
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
lst.sort()
for a in lst:
del ddc[a[1]]
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
del ddc
ddc=DictDBLocal('test_dictdb')
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
ddc.purge()
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
del ddc
ddc=DictDBLocal('test_dictdb')
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
print ddc.keys()
ddc.reset()
del ddc
ddc=DictDBLocal('test_dictdb')
info = ddc.get_info()
print 'used:',info.used,'wasted:',info.wasted,'extant:',info.used-info.wasted
|