ia64/xen-unstable

view tools/python/xen/xend/uuid.py @ 6552:a9873d384da4

Merge.
author adsharma@los-vmm.sc.intel.com
date Thu Aug 25 12:24:48 2005 -0700 (2005-08-25)
parents 112d44270733 fa0754a9f64f
children dfaf788ab18c
line source
1 #============================================================================
2 # This library is free software; you can redistribute it and/or
3 # modify it under the terms of version 2.1 of the GNU Lesser General Public
4 # License as published by the Free Software Foundation.
5 #
6 # This library is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 # Lesser General Public License for more details.
10 #
11 # You should have received a copy of the GNU Lesser General Public
12 # License along with this library; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14 #============================================================================
15 # Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
16 #============================================================================
18 """Universal(ly) Unique Identifiers (UUIDs).
19 """
20 import commands
21 import random
23 def uuidgen(random=True):
24 """Generate a UUID using the command uuidgen.
26 If random is true (default) generates a random uuid.
27 If random is false generates a time-based uuid.
28 """
29 cmd = "uuidgen"
30 if random:
31 cmd += " -r"
32 else:
33 cmd += " -t"
34 return commands.getoutput(cmd)
36 class UuidFactoryUuidgen:
38 """A uuid factory using uuidgen."""
40 def __init__(self):
41 pass
43 def getUuid(self):
44 return uuidgen()
46 class UuidFactoryRandom:
48 """A random uuid factory."""
50 def __init__(self):
51 f = file("/dev/urandom", "r")
52 seed = f.read(16)
53 f.close()
54 self.rand = random.Random(seed)
56 def randBytes(self, n):
57 return [ self.rand.randint(0, 255) for i in range(0, n) ]
59 def getUuid(self):
60 bytes = self.randBytes(16)
61 # Encode the variant.
62 bytes[6] = (bytes[6] & 0x0f) | 0x40
63 bytes[8] = (bytes[8] & 0x3f) | 0x80
64 f = "%02x"
65 return ( "-".join([f*4, f*2, f*2, f*2, f*6]) % tuple(bytes) )
67 def getFactory():
68 """Get the factory to use for creating uuids.
69 This is so it's easy to change the uuid factory.
70 For example, for testing we might want repeatable uuids
71 rather than the random ones we normally use.
72 """
73 global uuidFactory
74 try:
75 uuidFactory
76 except:
77 #uuidFactory = UuidFactoryUuidgen()
78 uuidFactory = UuidFactoryRandom()
79 return uuidFactory
81 def getUuid():
82 return getFactory().getUuid()