bdc4dfda4ec33efa66c10a4ae74deaf6551220fa
[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 - '
30                               '%(levelname)s: %(message)s')
31
32 # Add formatter to console handler.
33 ch.setFormatter(formatter)
34
35 # Add console handler to logger.
36 logger.addHandler(ch)
37
38
39 class SwarmDescription(object):
40
41     """Swarm Description class based on ConfigParser."""
42
43     def __init__(self):
44         """Initialize the data field as an instance of ConfigParser()."""
45         self.data = ConfigParser.ConfigParser()
46
47     def load(self, swarm_config_file):
48         """Load configuration file.
49
50         Expect configuration file without first section for swarm information.
51         Ignore tabs in configuration file.
52         """
53
54         NOSECTION = 'swarm'
55         try:
56             text = open(swarm_config_file).read()
57         except IOError:
58             logger.error("No such file: %s" %swarm_config_file)
59         text = ''.join(text.split('\t'))
60         f = StringIO("[%s]\n" % NOSECTION + text)
61         self.data.readfp(f)
62
63     def store(self, ini_file):
64         """Write configuration information to file."""
65         f = open(ini_file, 'w')
66         self.data.write(f)
67         f.close()
68
69     def get_swarm(self):
70         """Return Swarm object containing information from config file."""
71         swarm_data = dict(self.data.items('swarm'))
72         swarm = storage.Swarm(swarm_data['torrent_filename'],
73                               swarm_data['data_size'],
74                               swarm_data['description'])
75         return swarm
76
77     def get_session_entries(self):
78         """Return list of SessionEntry instances."""
79         session_names = self.data.sections()
80         session_names.remove('swarm')
81         session_list = []
82         for session in session_names:
83             entry = SessionEntry(session)
84             session_items = dict(self.data.items(session))
85             for key in session_items:
86                 entry.data.set(session, key, session_items[key])
87             session_list.append(entry)
88         return session_list
89
90     def update_session_entry_id(self, session_entry, cs_id, swarm_id = None):
91         """Add or modify client session id in self and session_entry."""
92         session_name = session_entry.data.sections()[0]
93         self.data.set(session_name, 'client_session_id', str(cs_id))
94         session_entry.data.set(session_name, 'client_session_id', str(cs_id))
95         if swarm_id is not None:
96             self.data.set(session_name, 'swarm_id', str(swarm_id))
97             session_entry.data.set(session_name, 'swarm_id', str(swarm_id))
98             self.data.set('swarm', 'swarm_id', str(swarm_id))
99
100     def get_file_archives(self):
101         """Return a list containing all archives from swarm."""
102         archives = []
103         for section in self.data.sections():
104             try:
105                 archives.append(self.data.get(section, 'log_file'))
106             except ConfigParser.NoOptionError:
107                 pass
108         return archives
109
110
111 class SessionEntry(object):
112
113     """Session Description class based on ConfigParser."""
114
115     def __init__(self, session):
116         """Initialize the data field as an instance of ConfigParser()."""
117         self.data = ConfigParser.ConfigParser()
118         self.data.add_section(session)
119
120     def get_session(self):
121         """Return name of the session."""
122         session = self.data.sections()[0]
123         cs_data = dict(self.data.items(session))
124         cs = storage.ClientSession(
125                             btclient = cs_data['bittorrent_client'],
126                             system_os = cs_data['system_os'],
127                             system_os_version = cs_data['system_os_version'],
128                             system_ram = cs_data['system_ram'],
129                             system_cpu = cs_data['system_cpu'],
130                             public_ip = cs_data['public_ip'],
131                             public_port = cs_data['public_port'],
132                             ds_limit = cs_data['ds_limit'],
133                             us_limit = cs_data['us_limit'],
134                             start_time = cs_data['start_time'],
135                             dht_enabled = cs_data['dht_enabled'],
136                             pxe_enabled = cs_data['pxe_enabled'],
137                             streaming_enabled = cs_data['streaming_enabled'],
138                             description = cs_data['description'])
139         return cs
140
141     def get_session_id(self):
142         """Return client session id corresponding to the entry.
143
144         If the session entry hasn't been asigned a session id raise error.
145         """
146
147         section = self.data.sections()[0]
148         try:
149             cs_id = self.data.get(section, 'client_session_id')
150             return cs_id
151         except ConfigParser.NoOptionError:
152             logger.debug("No client session id for entry: %s" %section)
153             return None
154
155
156 class AccessConfig(object):
157
158     """Access Configuration class based on ConfigParser."""
159
160     def __init__(self):
161         """Initialize the data field as an instance of ConfigParser()."""
162         self.data = ConfigParser.ConfigParser()
163
164     def load(self, access_config_file):
165         """Load configuration file."""
166         try:
167             text = open(access_config_file).read()
168         except IOError:
169             logger.error("No such file: %s" %swarm_config_file)
170         text = ''.join(text.split('\t'))
171         f = StringIO(text)
172         self.data.readfp(f)
173
174     def store(self, ini_file):
175         """Write configuration information to file."""
176         f = open(ini_file, 'w')
177         self.data.write(f)
178         f.close()
179
180     def get_swarm_writer(self):
181         """Return storage.SwarmWriter instance.
182
183         For each section create coresponding storage.*Access instance
184         and add it to SwarmWriter.handlers list.
185         """
186
187         sw = storage.SwarmWriter()
188         for section in self.data.sections():
189             if section == 'mysql':
190                 config = dict(self.data.items('mysql'))
191
192                 # If host and port options are not defined, use defaults.
193                 if 'host' not in config:
194                     config['host'] = 'localhost'
195                 if 'port' not in config:
196                     config['port'] = 3305
197                 mysql = storage.MySQLDatabaseAccess(config)
198                 mysql.connect()
199                 sw.add_access_handle(mysql)
200
201             elif section == "sqlite":
202                 database = dict(self.data.items('sqlite'))['database']
203                 sqlite = storage.SQLiteDatabaseAccess(database)
204                 sqlite.connect()
205                 sw.add_access_handle(sqlite)
206
207             elif section == "treetextfile":
208                 path = dict(self.data.items('treetextfile'))['path']
209                 treetextfile = storage.TreeTextFileAccess(path)
210                 sw.add_access_handle(treetextfile)
211         return sw