Package ZenUtils :: Module guid
[hide private]
[frames] | no frames]

Source Code for Module ZenUtils.guid

 1  ########################################################################### 
 2  # 
 3  # This program is part of Zenoss Core, an open source monitoring platform. 
 4  # Copyright (C) 2007, Zenoss Inc. 
 5  # 
 6  # This program is free software; you can redistribute it and/or modify it 
 7  # under the terms of the GNU General Public License version 2 as published by 
 8  # the Free Software Foundation. 
 9  # 
10  # For complete information please visit: http://www.zenoss.com/oss/ 
11  # 
12  ########################################################################### 
13  import math, sys, time, random, threading, socket, os 
14   
15  make_hexip = lambda ip: ''.join(["%02x" % long(i) for i in ip.split('.')]) 
16   
17  _pid = '%04x' % os.getpid() 
18  _pid = _pid[-3:] 
19     
20  ip = '' 
21  lock = threading.RLock() 
22  try:  # only need to get the IP addresss once 
23    ip = socket.getaddrinfo(socket.gethostname(),0)[-1][-1][0] 
24    hexip = make_hexip(ip) 
25  except:  
26      # if we don't have an ip, default to someting in the 10.x.x.x private range 
27      ip = '10' 
28      rand = random.Random() 
29      for i in range(3): 
30          ip += '.' + str(rand.randrange(1, 0xff))   
31          # might as well use IPv6 range if we're making it up 
32      hexip = make_hexip(ip) 
33   
34   
35 -def _unique_sequencer():
36 _XUnit_sequence = sys.maxint 37 38 while 1: 39 yield _XUnit_sequence 40 _XUnit_sequence -= 1 41 if _XUnit_sequence <= 0: 42 _XUnit_sequence = sys.maxint
43 _uniqueid = _unique_sequencer() 44
45 -def generate():
46 lock.acquire() 47 try: 48 frac, secs = math.modf(time.time()) 49 days, remain = divmod(secs, 86400) 50 id = _uniqueid.next() 51 return "%s%s%s%s%s" % (hexip, 52 hex(int(days))[2:], 53 hex(int(remain))[2:], 54 hex(id)[-4:], 55 _pid) 56 finally: 57 lock.release()
58