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