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 from future import standard_library
20 standard_library.install_aliases()
21 from builtins import map
22 from builtins import str
23 from builtins import object
24 import configparser
25 import logging
26 import os , sys
27 sys.path.extend(list(map(os.path.abspath, ['../../'])))
28 from smolt_config import get_config_attr
29 from request import Request
30 
31 _SECTION = 'MAIN'
32 
33 
34 def _get_option_name(hw_uuid, host):
35  return '%s__%s' % (hw_uuid, host)
36 
37 class UUIDError(Exception):
38  def __init__(self, message):
39  self.msg = message
40 
41  def __str__(self):
42  return str(self.msg)
43 
44 class PubUUIDError(Exception):
45  def __init__(self, message):
46  self.msg = message
47 
48  def __str__(self):
49  return str(self.msg)
50 
51 class _UuidDb(object):
52  hw_uuid = None
53 
54  def __init__(self, database_filename):
55  self._database_filename = database_filename
56  self._config = configparser.RawConfigParser()
58  if not self._config.has_section(_SECTION):
59  self._config.add_section(_SECTION)
60  self.hw_uuid_file = get_config_attr('HW_UUID', '/etc/smolt/hw-uuid')
61 
62  def _flush(self):
63  try:
64  smolt_user_config_dir = os.path.expanduser('~/.smolt/')
65  if not os.path.exists(smolt_user_config_dir):
66  os.mkdir(smolt_user_config_dir, 0o700)
67  f = open(self._database_filename, 'w')
68  self._config.write(f)
69  f.close()
70  except:
71  logging.error('Flushing UUID database failed')
72 
73  def get_pub_uuid(self, hw_uuid, host):
74  try:
75  pub_uuid = self._config.get(_SECTION, _get_option_name(hw_uuid, host))
76  logging.info('Public UUID "%s" read from database' % pub_uuid)
77  return pub_uuid
78  except configparser.NoOptionError:
79  try:
80  req = Request('/client/pub_uuid/%s' % self.get_priv_uuid())
81  pudict = json.loads(req.open().read())
82  self.set_pub_uuid(self.hw_uuid, Request(), pudict['pub_uuid'])
83  return pudict['pub_uuid']
84  except Exception as e:
85  error(_('Error determining public UUID: %s') % e)
86  sys.stderr.write(_("Unable to determine Public UUID! This could be a network error or you've\n"))
87  sys.stderr.write(_("not submitted your profile yet.\n"))
88  raise PubUUIDError('Could not determine Public UUID!\n')
89 
90  def set_pub_uuid(self, hw_uuid, host, pub_uuid):
91  for i in (hw_uuid, host, pub_uuid):
92  if not i:
93  raise Exception('No parameter is allowed to be None')
94  self._config.set(_SECTION, _get_option_name(hw_uuid, host), pub_uuid)
95  logging.info('Public UUID "%s" written to database' % pub_uuid)
96  self._flush()
97 
98  def gen_uuid(self):
99  try:
100  with open('/proc/sys/kernel/random/uuid') as rand_uuid:
101  rand_uuid_string = rand_uuid.read().strip()
102  return rand_uuid_string
103  except IOError:
104  try:
105  import uuid
106  return uuid.uuid4()
107  except:
108  raise UUIDError('Could not generate new UUID!')
109 
110  def get_priv_uuid(self):
111  if self.hw_uuid:
112  return self.hw_uuid
113 
114  try:
115  with open(self.hw_uuid_file) as hwuuidfile:
116  self.hw_uuid = hwuuidfile.read().strip()
117  except IOError:
118  try:
119  self.hw_uuid = self.genUUID()
120  except UUIDError:
121  raise UUIDError('Unable to determine UUID of system!')
122  try:
123  # make sure directory exists, create if not
124  with open(self.hw_uuid_file, 'w') as hwuuidfile:
125  hwuuidfile.write(self.hw_uuid)
126  except Exception as e:
127  raise UUIDError('Unable to save UUID to %s. Please run once as root.' % self.hw_uuid_file)
128 
129  return self.hw_uuid
130 
131 _uuid_db_instance = None
132 def UuidDb():
133  """Simple singleton wrapper with lazy initialization"""
134  global _uuid_db_instance
135  if _uuid_db_instance == None:
136  import config
137  from smolt import get_config_attr
138  _uuid_db_instance = _UuidDb(get_config_attr("UUID_DB", os.path.expanduser('~/.smolt/uuiddb.cfg')))
139  return _uuid_db_instance
def write(text, progress=True)
Definition: mythburn.py:308
static void error(const char *str,...)
Definition: vbi.c:42
def read(device=None, features=[])
Definition: disc.py:35
def get_config_attr(attr, default="")
Definition: smolt_config.py:22