ppf/new: Initialize 'data' field in constructor for config.py classes. Remove super...
[cs-p2p-next.git] / ppf / new / config.py
1 """
2 Configuration class for P2P logging information.
3
4 2011, Mariana Marasoiu, mariana.marasoiu@gmail.com
5 """
6
7 import os
8 import os.path
9 import logging
10 import ConfigParser
11 from StringIO import StringIO
12
13 import storage
14
15 #
16 # Logging code heavily inspired by Logging HOWTO documentation:
17 #     http://docs.python.org/dev/howto/logging.html#configuring-logging
18 #
19
20 # Create logger; default logging level is DEBUG.
21 logger = logging.getLogger(__name__)
22 logger.setLevel(logging.DEBUG)
23
24 # Create console handler and set level to ERROR.
25 ch = logging.StreamHandler()
26 ch.setLevel(logging.DEBUG)
27
28 # Create formatter.
29 formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s: %(message)s')
30
31 # Add formatter to console handler.
32 ch.setFormatter(formatter)
33
34 # Add console handler to logger.
35 logger.addHandler(ch)
36
37 class SwarmDescription(object):
38     def __init__(self):
39         self.data = ConfigParser.ConfigParser()
40
41     def load(self, swarm_config_file):
42         """ Load configuration file and use ConfigParser.
43         Expect configuration file without first section for swarm information.
44
45         """
46         NOSECTION = 'swarm'
47         try:
48             text = open(swarm_config_file).read()
49         except IOError:
50             logger.error("No such file: %s" %swarm_config_file)
51         text = ''.join(text.split('\t'))
52         f = StringIO("[%s]\n" % NOSECTION + text)
53         self.data.readfp(f)
54
55     def store(self, ini_file):
56         """ Write configuration information to file. """
57         f = open(ini_file, 'w')
58         self.data.write(f)
59         f.close()
60
61     def get_swarm(self):
62         """ Return Swarm object containing information from config file. """
63         swarm_data = dict(self.data.items('swarm'))
64         swarm = storage.Swarm(swarm_data['torrent_filename'],
65                               swarm_data['data_size'],
66                               swarm_data['description'])
67         return swarm
68
69     def get_session_entries(self):
70         """ Return list of SessionEntry instances. """
71         session_names = self.data.sections()
72         session_names.remove('swarm')
73         session_list = []
74         for session in session_names:
75             entry = SessionEntry(session)
76             session_items = dict(self.data.items(session))
77             for key in session_items:
78                 entry.data.set(session, key, session_items[key])
79             session_list.append(entry)
80         return session_list
81
82     def update_session_entry_id(self, session_entry, cs_id):
83         """ Add or modify client session id. """
84         session_name = session_entry.data.sections()[0]
85         self.data.set(session_name, 'client_session_id', str(cs_id))
86         session_entry.data.set(session_name, 'client_session_id', str(cs_id))
87
88     def get_file_archives(self):
89         """ Return a list containing all archives from swarm. """
90         archives = []
91         for section in self.data.sections():
92             try:
93                 archives.append(self.data.get(section, 'log_file'))
94             except ConfigParser.NoOptionError:
95                 pass
96         return archives
97
98 class SessionEntry(object):
99     def __init__(self, session):
100         self.data = ConfigParser.ConfigParser()
101         self.data.add_section(session)
102
103     def get_session(self):
104         """ Return name of the session. """
105         session = self.data.sections()[0]
106         cs_data = dict(self.data.items(session))
107         cs = storage.ClientSession(
108                             btclient = cs_data['bittorrent_client'],
109                             system_os = cs_data['system_os'],
110                             system_os_version = cs_data['system_os_version'],
111                             system_ram = cs_data['system_ram'],
112                             system_cpu = cs_data['system_cpu'],
113                             public_ip = cs_data['public_ip'],
114                             public_port = cs_data['public_port'],
115                             ds_limit = cs_data['ds_limit'],
116                             us_limit = cs_data['us_limit'],
117                             start_time = cs_data['start_time'],
118                             dht_enabled = cs_data['dht_enabled'],
119                             pxe_enabled = cs_data['pxe_enabled'],
120                             streaming_enabled = cs_data['streaming_enabled'],
121                             description = cs_data['description'])
122         return cs
123
124     def get_session_id(self):
125         """ Return client session id corresponding to the entry.
126         If the session entry hasn't been asigned a session id raise error.
127
128         """
129         section = self.data.sections()[0]
130         try:
131             cs_id = self.data.get(section, 'client_session_id')
132             return cs_id
133         except ConfigParser.NoOptionError:
134             logger.debug("No client session id for entry: %s" %section)
135             return None
136
137 class AccessConfig(object):
138     def __init__(self):
139         self.data = ConfigParser.ConfigParser()
140
141     def load(self, access_config_file):
142         """ Load configuration file and use ConfigParser. """
143         try:
144             text = open(access_config_file).read()
145         except IOError:
146             logger.error("No such file: %s" %swarm_config_file)
147         text = ''.join(text.split('\t'))
148         f = StringIO(text)
149         self.data.readfp(f)
150
151     def store(self, ini_file):
152         """ Write configuration information to file. """
153         f = open(ini_file, 'w')
154         self.data.write(f)
155         f.close()
156
157     def get_swarm_writer(self):
158         """ Return storage.SwarmWriter instance.
159         For each section create coresponding storage.*Access instance
160         and add to SwarmWriter.handlers list.
161
162         """
163         sw = storage.SwarmWriter()
164         for section in self.data.sections():
165             if section == 'mysql':
166                 config = dict(self.data.items('mysql'))
167
168                 # If host and port options are not defined, use defaults.
169                 if 'host' not in config:
170                     config['host'] = 'localhost'
171                 if 'port' not in config:
172                     config['port'] = 3305
173                 mysql = storage.MySQLDatabaseAccess(config)
174                 mysql.connect()
175                 sw.add_access_handle(mysql)
176
177             elif section == "sqlite":
178                 database = dict(self.data.items('sqlite'))['database']
179                 sqlite = storage.SQLiteDatabaseAccess(database)
180                 sqlite.connect()
181                 sw.add_access_handle(sqlite)
182
183             elif section == "treetextfile":
184                 path = dict(self.data.items('treetextfile'))['path']
185                 treetextfile = storage.TreeTextFileAccess(path)
186                 sw.add_access_handle(treetextfile)
187         return sw