simul.py 20.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#! /usr/bin/env python
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Cache simulation.

17
Usage: simul.py [-bflz] [-s size] tracefile
18

19 20 21 22 23 24 25
Use one of -b, -f, -l or -z select the cache simulator:
-b: buddy system allocator
-f: simple free list allocator 
-l: idealized LRU (no allocator)
-z: existing ZEO cache (default)

Options:
26
-s size: cache size in MB (default 20 MB)
27 28

Note: the buddy system allocator rounds the cache size up to a power of 2
29 30 31 32 33 34 35 36 37 38 39 40 41
"""

import sys
import time
import getopt
import struct

def usage(msg):
    print >>sys.stderr, msg
    print >>sys.stderr, __doc__

def main():
    # Parse options
42 43
    MB = 1024*1024
    cachelimit = 20*MB
44
    simclass = ZEOCacheSimulation
45
    try:
46
        opts, args = getopt.getopt(sys.argv[1:], "bflzs:")
47 48 49 50
    except getopt.error, msg:
        usage(msg)
        return 2
    for o, a in opts:
51 52
        if o == '-b':
            simclass = BuddyCacheSimulation
53 54
        if o == '-f':
            simclass = SimpleCacheSimulation
55 56
        if o == '-l':
            simclass = LRUCacheSimulation
57 58
        if o == '-z':
            simclass = ZEOCacheSimulation
59
        if o == '-s':
60
            cachelimit = int(float(a)*MB)
61 62 63 64 65 66
    if len(args) != 1:
        usage("exactly one file argument required")
        return 2
    filename = args[0]

    # Open file
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    if filename.endswith(".gz"):
        # Open gzipped file
        try:
            import gzip
        except ImportError:
            print >>sys.stderr,  "can't read gzipped files (no module gzip)"
            return 1
        try:
            f = gzip.open(filename, "rb")
        except IOError, msg:
            print >>sys.stderr,  "can't open %s: %s" % (filename, msg)
            return 1
    elif filename == "-":
        # Read from stdin
        f = sys.stdin
    else:
        # Open regular file
        try:
            f = open(filename, "rb")
        except IOError, msg:
            print >>sys.stderr,  "can't open %s: %s" % (filename, msg)
            return 1
89

90
    # Create simulation object
91
    sim = simclass(cachelimit)
92 93 94

    # Print output header
    sim.printheader()
95 96 97

    # Read trace file, simulating cache behavior
    while 1:
98
        # Read a record
99 100 101 102 103
        r = f.read(24)
        if len(r) < 24:
            break
        # Decode it
        ts, code, oid, serial = struct.unpack(">ii8s8s", r)
104
        dlen, version, code, current = (code & 0x7fffff00,
105 106 107
                                        code & 0x80,
                                        code & 0x7e,
                                        code & 0x01)
108 109 110 111 112 113 114 115 116 117 118
        # And pass it to the simulation
        sim.event(ts, dlen, version, code, current, oid, serial)

    # Finish simulation
    sim.finish()

    # Exit code from main()
    return 0

class Simulation:

119
    """Base class for simulations.
120

121
    The driver program calls: event(), printheader(), finish().
122

123 124 125
    The standard event() method calls these additional methods:
    write(), load(), inval(), report(), restart(); the standard
    finish() method also calls report().
126 127 128

    """

129 130
    def __init__(self, cachelimit):
        self.cachelimit = cachelimit
131 132 133
        # Initialize global statistics
        self.epoch = None
        self.total_loads = 0
134
        self.total_hits = 0 # Subclass must increment
135 136
        self.total_invals = 0
        self.total_writes = 0
137
        # Reset per-run statistics and set up simulation data
138 139 140
        self.restart()

    def restart(self):
141
        # Reset per-run statistics
142
        self.loads = 0
143
        self.hits = 0 # Subclass must increment
144 145 146 147 148 149 150 151 152 153 154
        self.invals = 0
        self.writes = 0
        self.ts0 = None

    def event(self, ts, dlen, _version, code, _current, oid, _serial):
        # Record first and last timestamp seen
        if self.ts0 is None:
            self.ts0 = ts
            if self.epoch is None:
                self.epoch = ts
        self.ts1 = ts
155 156 157 158 159 160

        # Simulate cache behavior.  Use load hits, updates and stores
        # only (each load miss is followed immediately by a store
        # unless the object in fact did not exist).  Updates always write.
        if dlen and code & 0x70 in (0x20, 0x30, 0x50):
            if code == 0x3A:
161
                # Update
162 163
                self.writes += 1
                self.total_writes += 1
164
                self.write(oid, dlen)
165
            else:
166
                # Load hit or store -- these are really the load requests
167 168
                self.loads += 1
                self.total_loads += 1
169
                self.load(oid, dlen)
170 171
        elif code & 0x70 == 0x10:
            # Invalidate
172
            self.inval(oid)
173 174
        elif code == 0x00:
            # Restart
175 176 177
            self.report()
            self.restart()

178 179 180 181 182 183 184 185 186
    def write(self, oid, size):
        pass

    def load(self, oid, size):
        pass

    def inval(self, oid):
        pass

187 188 189 190 191 192 193 194 195 196 197 198 199 200
    format = "%12s %9s %8s %8s %6s %6s %6s %6s"

    # Subclass should override extraname to name known instance variables;
    # if extraname is 'foo', both self.foo and self.total_foo must exist:
    extraname = "*** please override ***"

    def printheader(self):
        print "%s, cache size %s bytes" % (self.__class__.__name__,
                                           addcommas(self.cachelimit))
        print self.format % (
            "START TIME", "DURATION", "LOADS", "HITS",
            "INVALS", "WRITES", self.extraname.upper(), "HITRATE")

    nreports = 0
201 202

    def report(self):
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        if self.loads:
            self.nreports += 1
            print self.format % (
                time.ctime(self.ts0)[4:-8],
                duration(self.ts1 - self.ts0),
                self.loads, self.hits, self.invals, self.writes,
                getattr(self, self.extraname),
                hitrate(self.loads, self.hits))

    def finish(self):
        self.report()
        if self.nreports > 1:
            print (self.format + " OVERALL") % (
                time.ctime(self.epoch)[4:-8],
                duration(self.ts1 - self.epoch),
                self.total_loads,
                self.total_hits,
                self.total_invals,
                self.total_writes,
                getattr(self, "total_" + self.extraname),
                hitrate(self.total_loads, self.total_hits))
224 225 226 227 228 229 230 231 232 233

class ZEOCacheSimulation(Simulation):

    """Simulate the current (ZEO 1.0 and 2.0) ZEO cache behavior.

    This assumes the cache is not persistent (we don't know how to
    simulate cache validation.)

    """

234 235
    extraname = "flips"

236 237
    def __init__(self, cachelimit):
        # Initialize base class
238
        Simulation.__init__(self, cachelimit)
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
        # Initialize additional global statistics
        self.total_flips = 0

    def restart(self):
        # Reset base class
        Simulation.restart(self)
        # Reset additional per-run statistics
        self.flips = 0
        # Set up simulation
        self.filesize = [4, 4] # account for magic number
        self.fileoids = [{}, {}]
        self.current = 0 # index into filesize, fileoids

    def load(self, oid, size):
        if (self.fileoids[self.current].get(oid) or
            self.fileoids[1 - self.current].get(oid)):
            self.hits += 1
            self.total_hits += 1
        else:
            self.write(oid, size)

    def write(self, oid, size):
        # Fudge because size is rounded up to multiples of 256.  (31
        # is header overhead per cache record; 127 is to compensate
        # for rounding up to multiples of 256.)
        size = size + 31 - 127
265
        if self.filesize[self.current] + size > self.cachelimit / 2:
266 267 268 269 270 271 272 273 274 275 276
            # Cache flip
            self.flips += 1
            self.total_flips += 1
            self.current = 1 - self.current
            self.filesize[self.current] = 4
            self.fileoids[self.current] = {}
        self.filesize[self.current] += size
        self.fileoids[self.current][oid] = 1

    def inval(self, oid):
        if self.fileoids[self.current].get(oid):
277 278
            self.invals += 1
            self.total_invals += 1
279 280
            del self.fileoids[self.current][oid]
        elif self.fileoids[1 - self.current].get(oid):
281 282
            self.invals += 1
            self.total_invals += 1
283 284
            del self.fileoids[1 - self.current][oid]

285 286
class LRUCacheSimulation(Simulation):

287 288
    extraname = "evicts"

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
    def __init__(self, cachelimit):
        # Initialize base class
        Simulation.__init__(self, cachelimit)
        # Initialize additional global statistics
        self.total_evicts = 0

    def restart(self):
        # Reset base class
        Simulation.restart(self)
        # Reset additional per-run statistics
        self.evicts = 0
        # Set up simulation
        self.cache = {}
        self.size = 0
        self.head = Node(None, None)
        self.head.linkbefore(self.head)

    def load(self, oid, size):
        node = self.cache.get(oid)
        if node is not None:
            self.hits += 1
            self.total_hits += 1
            node.linkbefore(self.head)
        else:
            self.write(oid, size)

    def write(self, oid, size):
        node = self.cache.get(oid)
        if node is not None:
            node.unlink()
            assert self.head.next is not None
            self.size -= node.size
        node = Node(oid, size)
        self.cache[oid] = node
        node.linkbefore(self.head)
        self.size += size
        # Evict LRU nodes
        while self.size > self.cachelimit:
            self.evicts += 1
            self.total_evicts += 1
            node = self.head.next
            assert node is not self.head
            node.unlink()
            assert self.head.next is not None
            del self.cache[node.oid]
            self.size -= node.size

    def inval(self, oid):
        node = self.cache.get(oid)
        if node is not None:
            assert node.oid == oid
            self.invals += 1
            self.total_invals += 1
            node.unlink()
            assert self.head.next is not None
            del self.cache[oid]
            self.size -= node.size
            assert self.size >= 0

class Node:

    """Node in a doubly-linked list, storing oid and size as payload.

    A node can be linked or unlinked; in the latter case, next and
    prev are None.  Initially a node is unlinked.

    """
    # Make it a new-style class in Python 2.2 and up; no effect in 2.1
    __metaclass__ = type
    __slots__ = ['prev', 'next', 'oid', 'size']

    def __init__(self, oid, size):
        self.oid = oid
        self.size = size
        self.prev = self.next = None

    def unlink(self):
        prev = self.prev
        next = self.next
        if prev is not None:
            assert next is not None
            assert prev.next is self
            assert next.prev is self
            prev.next = next
            next.prev = prev
            self.prev = self.next = None
        else:
            assert next is None

    def linkbefore(self, next):
        self.unlink()
        prev = next.prev
        if prev is None:
            assert next.next is None
            prev = next
        self.prev = prev
        self.next = next
        prev.next = next.prev = self

388 389 390 391
class BuddyCacheSimulation(LRUCacheSimulation):

    def restart(self):
        LRUCacheSimulation.restart(self)
392 393 394 395
        self.allocator = self.allocatorFactory(self.cachelimit)

    def allocatorFactory(self, size):
        return BuddyAllocator(size)
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

    # LRUCacheSimulation.load() is just fine

    def write(self, oid, size):
        node = self.cache.get(oid)
        if node is not None:
            node.unlink()
            assert self.head.next is not None
            self.size -= node.size
            self.allocator.free(node)
        while 1:
            node = self.allocator.alloc(size)
            if node is not None:
                break
            # Failure to allocate.  Evict something and try again.
            node = self.head.next
            assert node is not self.head
            self.evicts += 1
            self.total_evicts += 1
            node.unlink()
            assert self.head.next is not None
            del self.cache[node.oid]
            self.size -= node.size
            self.allocator.free(node)
        node.oid = oid
        self.cache[oid] = node
        node.linkbefore(self.head)
        self.size += node.size

    def inval(self, oid):
        node = self.cache.get(oid)
        if node is not None:
            assert node.oid == oid
            self.invals += 1
            self.total_invals += 1
            node.unlink()
            assert self.head.next is not None
            del self.cache[oid]
            self.size -= node.size
            assert self.size >= 0
            self.allocator.free(node)

438
class SimpleCacheSimulation(BuddyCacheSimulation):
439

440 441
    def allocatorFactory(self, size):
        return SimpleAllocator(size)
442

443 444 445 446
    def finish(self):
        BuddyCacheSimulation.finish(self)
        self.allocator.report()

447 448 449 450 451 452 453 454 455 456 457
MINSIZE = 256

class BuddyAllocator:

    def __init__(self, cachelimit):
        cachelimit = roundup(cachelimit)
        self.cachelimit = cachelimit
        self.avail = {} # Map rounded-up sizes to free list node heads
        self.nodes = {} # Map address to node
        k = MINSIZE
        while k <= cachelimit:
458
            self.avail[k] = n = Node(None, None) # Not BlockNode; has no addr
459 460
            n.linkbefore(n)
            k += k
461
        node = BlockNode(None, cachelimit, 0)
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        self.nodes[0] = node
        node.linkbefore(self.avail[cachelimit])

    def alloc(self, size):
        size = roundup(size)
        k = size
        while k <= self.cachelimit:
            head = self.avail[k]
            node = head.next
            if node is not head:
                break
            k += k
        else:
            return None # Store is full, or block is too large
        node.unlink()
        size2 = node.size
        while size2 > size:
            size2 = size2 / 2
            assert size2 >= size
            node.size = size2
482
            buddy = BlockNode(None, size2, node.addr + size2)
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
            self.nodes[buddy.addr] = buddy
            buddy.linkbefore(self.avail[size2])
        node.oid = 1 # Flag as in-use
        return node

    def free(self, node):
        assert node is self.nodes[node.addr]
        assert node.prev is node.next is None
        node.oid = None # Flag as free
        while node.size < self.cachelimit:
            buddy_addr = node.addr ^ node.size
            buddy = self.nodes[buddy_addr]
            assert buddy.addr == buddy_addr
            if buddy.oid is not None or buddy.size != node.size:
                break
            # Merge node with buddy
            buddy.unlink()
            if buddy.addr < node.addr: # buddy prevails
                del self.nodes[node.addr]
                node = buddy
            else: # node prevails
                del self.nodes[buddy.addr]
            node.size *= 2
        assert node is self.nodes[node.addr]
        node.linkbefore(self.avail[node.size])

    def dump(self, msg=""):
        if msg:
            print msg,
        size = MINSIZE
        blocks = bytes = 0
        while size <= self.cachelimit:
            head = self.avail[size]
            node = head.next
            count = 0
            while node is not head:
                count += 1
                node = node.next
            if count:
                print "%d:%d" % (size, count),
            blocks += count
            bytes += count*size
            size += size
        print "-- %d, %d" % (bytes, blocks)

528 529 530 531 532 533 534 535 536 537 538 539 540 541
def roundup(size):
    k = MINSIZE
    while k < size:
        k += k
    return k

class SimpleAllocator:

    def __init__(self, arenasize):
        self.arenasize = arenasize
        self.avail = BlockNode(None, 0, 0) # Weird: empty block as list head
        self.rover = self.avail
        node = BlockNode(None, arenasize, 0)
        node.linkbefore(self.avail)
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
        # Allocator statistics
        self.nallocs = 0
        self.nfrees = 0
        self.allocloops = 0
        self.freeloops = 0
        self.freebytes = arenasize
        self.freeblocks = 1
        self.allocbytes = 0
        self.allocblocks = 0

    def report(self):
        print ("NA=%d AL=%d NF=%d FL=%d ABy=%d ABl=%d FBy=%d FBl=%d" %
               (self.nallocs, self.allocloops,
                self.nfrees, self.freeloops,
                self.allocbytes, self.allocblocks,
                self.freebytes, self.freeblocks))
558 559

    def alloc(self, size):
560 561
        self.nallocs += 1
        # First fit algorithm
562 563 564
        rover = stop = self.rover
        free = None
        while 1:
565
            self.allocloops += 1
566 567 568 569
            if rover.size >= size:
                if rover.size == size:
                    self.rover = rover.next
                    rover.unlink()
570 571 572 573
                    self.freeblocks -= 1
                    self.allocblocks += 1
                    self.freebytes -= size
                    self.allocbytes += size
574 575
                    return rover
                free = rover
576
                break
577 578 579 580 581 582 583 584 585
            rover = rover.next
            if rover is stop:
                break
        if free is None: # We ran out of space
            return None
        # Take space from the end of the roving pointer
        assert free.size > size
        node = BlockNode(None, size, free.addr + free.size - size)
        free.size -= size
586 587 588 589
        #self.freeblocks += 0 # No change here
        self.allocblocks += 1
        self.freebytes -= size
        self.allocbytes += size
590 591 592
        return node

    def free(self, node):
593 594 595 596
        self.nfrees += 1
        self.freebytes += node.size
        self.allocbytes -= node.size
        self.allocblocks -= 1
597 598
        x = self.avail.next
        while x is not self.avail and x.addr < node.addr:
599
            self.freeloops += 1
600 601 602 603 604 605 606
            x = x.next
        if node.addr + node.size == x.addr: # Merge with next
            x.addr -= node.size
            x.size += node.size
            node = x
        else: # Insert new node into free list
            node.linkbefore(x)
607
            self.freeblocks += 1
608 609 610 611 612 613
        x = node.prev
        if node.addr == x.addr + x.size and x is not self.avail:
            # Merge with previous node in free list
            node.unlink()
            x.size += node.size
            node = x
614
            self.freeblocks -= 1
615 616 617
        # It's possible that either one of the merges above invalidated
        # the rover.
        # It's simplest to simply reset the rover to the newly freed block.
618 619
        # It also seems optimal; if I only move the rover when it's
        # become invalid, there performance goes way down.
620 621 622 623 624 625 626 627 628 629 630 631 632
        self.rover = node

    def dump(self, msg=""):
        if msg:
            print msg,
        count = 0
        bytes = 0
        node = self.avail.next
        while node is not self.avail:
            bytes += node.size
            count += 1
            node = node.next
        print count, "free blocks,", bytes, "free bytes"
633
        self.report()
634 635 636 637 638 639 640 641 642 643

class BlockNode(Node):

    __slots__ = ['addr']

    def __init__(self, oid, size, addr):
        Node.__init__(self, oid, size)
        self.addr = addr

def testallocator(factory=BuddyAllocator):
644
    # Run one of Knuth's experiments as a test
645 646
    import random
    import heapq # This only runs with Python 2.3, folks :-)
647 648
    reportfreq = 100
    cachelimit = 2**17
649
    cache = factory(cachelimit)
650 651
    queue = []
    T = 0
652
    blocks = 0
653 654 655 656 657
    while T < 5000:
        while queue and queue[0][0] <= T:
            time, node = heapq.heappop(queue)
            assert time == T
            cache.free(node)
658
            blocks -= 1
659 660 661 662 663
        size = random.randint(100, 2000)
        lifetime = random.randint(1, 100)
        node = cache.alloc(size)
        if node is None:
            print "out of mem"
664
            cache.dump("T=%4d: %d blocks;" % (T, blocks))
665 666
            break
        else:
667
            blocks += 1
668 669 670
            heapq.heappush(queue, (T + lifetime, node))
        T = T+1
        if T % reportfreq == 0:
671
            cache.dump("T=%4d: %d blocks;" % (T, blocks))
672

673 674 675 676 677 678 679 680 681 682 683 684
def hitrate(loads, hits):
    return "%5.1f%%" % (100.0 * hits / max(1, loads))

def duration(secs):

    mm, ss = divmod(secs, 60)
    hh, mm = divmod(mm, 60)
    if hh:
        return "%d:%02d:%02d" % (hh, mm, ss)
    if mm:
        return "%d:%02d" % (mm, ss)
    return "%d" % ss
685

686 687 688 689 690 691 692 693 694 695
def addcommas(n):
    sign, s = '', str(n)
    if s[0] == '-':
        sign, s = '-', s[1:]
    i = len(s) - 3
    while i > 0:
        s = s[:i] + ',' + s[i:]
        i -= 3
    return sign + s

696 697
if __name__ == "__main__":
    sys.exit(main())