MythTV  master
distros/mythtv_data/uuiddb.py
Go to the documentation of this file.
1 # smolt - Fedora hardware profiler
2 #
3 # Copyright (C) 2009 Sebastian Pipping <sebastian@pipping.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 import ConfigParser
20 import logging
21 import os , sys
22 sys.path.extend(map(os.path.abspath, ['../../']))
23 from smolt_config import get_config_attr
24 from request import Request
25 
26 _SECTION = 'MAIN'
27 
28 
29 def _get_option_name(hw_uuid, host):
30  return '%s__%s' % (hw_uuid, host)
31 
32 class UUIDError(Exception):
33  def __init__(self, message):
34  self.msg = message
35 
36  def __str__(self):
37  return str(self.msg)
38 
39 class PubUUIDError(Exception):
40  def __init__(self, message):
41  self.msg = message
42 
43  def __str__(self):
44  return str(self.msg)
45 
46 class _UuidDb:
47  hw_uuid = None
48 
49  def __init__(self, database_filename):
50  self._database_filename = database_filename
51  self._config = ConfigParser.RawConfigParser()
53  if not self._config.has_section(_SECTION):
54  self._config.add_section(_SECTION)
55  self.hw_uuid_file = get_config_attr('HW_UUID', '/etc/smolt/hw-uuid')
56 
57  def _flush(self):
58  try:
59  smolt_user_config_dir = os.path.expanduser('~/.smolt/')
60  if not os.path.exists(smolt_user_config_dir):
61  os.mkdir(smolt_user_config_dir, 0700)
62  f = open(self._database_filename, 'w')
63  self._config.write(f)
64  f.close()
65  except:
66  logging.error('Flushing UUID database failed')
67 
68  def get_pub_uuid(self, hw_uuid, host):
69  try:
70  pub_uuid = self._config.get(_SECTION, _get_option_name(hw_uuid, host))
71  logging.info('Public UUID "%s" read from database' % pub_uuid)
72  return pub_uuid
73  except ConfigParser.NoOptionError:
74  try:
75  req = Request('/client/pub_uuid/%s' % self.get_priv_uuid())
76  pudict = json.loads(req.open().read())
77  self.set_pub_uuid(self.hw_uuid, Request(), pudict['pub_uuid'])
78  return pudict['pub_uuid']
79  except Exception, e:
80  error(_('Error determining public UUID: %s') % e)
81  sys.stderr.write(_("Unable to determine Public UUID! This could be a network error or you've\n"))
82  sys.stderr.write(_("not submitted your profile yet.\n"))
83  raise PubUUIDError, 'Could not determine Public UUID!\n'
84 
85  def set_pub_uuid(self, hw_uuid, host, pub_uuid):
86  for i in (hw_uuid, host, pub_uuid):
87  if not i:
88  raise Exception('No paramater allowed to be None.')
89  self._config.set(_SECTION, _get_option_name(hw_uuid, host), pub_uuid)
90  logging.info('Public UUID "%s" written to database' % pub_uuid)
91  self._flush()
92 
93  def gen_uuid(self):
94  try:
95  return file('/proc/sys/kernel/random/uuid').read().strip()
96  except IOError:
97  try:
98  import uuid
99  return uuid.uuid4()
100  except:
101  raise UUIDError('Could not generate new UUID!')
102 
103  def get_priv_uuid(self):
104  if self.hw_uuid:
105  return self.hw_uuid
106 
107  try:
108  self.hw_uuid = file(self.hw_uuid_file).read().strip()
109  except IOError:
110  try:
111  self.hw_uuid = self.genUUID()
112  except UUIDError:
113  raise UUIDError('Unable to determine UUID of system!')
114  try:
115  # make sure directory exists, create if not
116  file(self.hw_uuid_file).write(self.hw_uuid)
117  except Exception, e:
118  raise UUIDError('Unable to save UUID to %s. Please run once as root.' % self.hw_uuid_file)
119 
120  return self.hw_uuid
121 
122 _uuid_db_instance = None
123 def UuidDb():
124  """Simple singleton wrapper with lazy initialization"""
125  global _uuid_db_instance
126  if _uuid_db_instance == None:
127  import config
128  from smolt import get_config_attr
129  _uuid_db_instance = _UuidDb(get_config_attr("UUID_DB", os.path.expanduser('~/.smolt/uuiddb.cfg')))
130  return _uuid_db_instance
def write(text, progress=True)
Definition: mythburn.py:279
static void error(const char *str,...)
Definition: vbi.c:41
def read(device=None, features=[])
Definition: disc.py:35
def get_config_attr(attr, default="")
Definition: smolt_config.py:22