]> rtime.felk.cvut.cz Git - linux-conf-perf.git/blob - scripts/configurations.py
Fix problem with wrongly printed first line in CNF file
[linux-conf-perf.git] / scripts / configurations.py
1 import os
2 import sys
3 import tempfile
4 import shutil
5 import subprocess
6 import time
7 import hashlib
8
9 import utils
10 from conf import conf
11 from conf import sf
12 import exceptions
13 import database
14
15 def __buildtempcnf__(variable_count, files, strlines):
16         """ Builds temporally file for cnf formulas
17           variable_count - number of variables in formulas
18           files          - list of files with formulas
19           strlines       - list of string lines with formulas"""
20         lines = set()
21         # Copy strlines
22         for ln in strlines:
23                 lines.add(ln)
24         # Files
25         for file in files:
26                 with open(file, 'r') as f:
27                         for ln in f:
28                                 lines.add(ln.rstrip())
29
30         first_line = "p cnf " + str(variable_count) + " " + str(len(lines))
31
32         wfile = tempfile.NamedTemporaryFile(delete=False)
33         wfile.write(bytes(first_line + '\n', 'UTF-8'))
34         for ln in lines:
35                 wfile.write(bytes(ln + ' 0\n', 'UTF-8'))
36         wfile.close()
37         return wfile.name
38
39 def __exec_sat__(file, args):
40         """Executes SAT solver and returns configuration."""
41         picosat_cmd = [sf(conf.picosat), file]
42         picosat_cmd += conf.picosat_args
43         stdout = utils.callsubprocess('picosat', picosat_cmd, conf.picosat_output,
44                         True, allow_all_exit_codes = True)
45
46         rtn = []
47         solut = []
48         for line in stdout:
49                 if line[0] == 's':
50                         try:
51                                 solut.remove(0)
52                                 rtn.append(solut)
53                         except ValueError:
54                                 pass
55                         solut = []
56                         if not line.rstrip() == 's SATISFIABLE':
57                                 raise exceptions.NoSolution()
58                 elif line[0] == 'v':
59                         for sl in line[2:].split():
60                                 solut.append(int(sl))
61         try:
62                 solut.remove(0)
63                 rtn.append(solut)
64         except ValueError:
65                 pass
66         return rtn
67
68 def __write_temp_config_file__(con, conf_num):
69         # Ensure smap existence
70         utils.build_symbol_map()
71         # Write temporally file
72         wfile = tempfile.NamedTemporaryFile(delete=False)
73         for s in con:
74                 if s < 0:
75                         nt = True
76                         s *= -1
77                 else:
78                         nt = False
79                 if s > int(conf_num):
80                         break;
81                 if 'NONAMEGEN' in utils.smap[s]: # ignore generated names
82                         continue
83                 wfile.write(bytes('CONFIG_' + utils.smap[s] + '=',
84                         sys.getdefaultencoding()))
85                 if not nt:
86                         wfile.write(bytes('y', sys.getdefaultencoding()))
87                 else:
88                         wfile.write(bytes('n', sys.getdefaultencoding()))
89                 wfile.write(bytes('\n', sys.getdefaultencoding()))
90         wfile.close()
91         return wfile.name
92
93 def __load_config_file__(file):
94         rtn = dict()
95         with open(file, 'r') as f:
96                 for ln in f:
97                         if ln[0] == '#' or not '=' in ln:
98                                 continue
99                         indx = ln.index('=')
100                         if (ln[indx + 1] == 'y'):
101                                 rtn[ln[7:indx]] = True
102                         else:
103                                 rtn[ln[7:indx]] = True
104         return rtn
105
106 def __calchash__(file):
107         """Calculates hash from configuration file"""
108         # Build hashconfigsort
109         csort = []
110         try:
111                 with open(conf.hashconfigsort, 'r') as f:
112                         for ln in f:
113                                 csort.append(ln.rstrip())
114         except FileNotFoundError:
115                 pass
116
117         con = __load_config_file__(file)
118         cstr = ""
119         for c in csort:
120                 try:
121                         if con[c]:
122                                 cstr += '+'
123                         else:
124                                 cstr += '-'
125                 except ValueError:
126                         cstr += '0'
127
128         # Add missing
129         csortfile = open(sf(conf.hashconfigsort), 'a');
130         for key, val in con.items():
131                 try:
132                         csort.index(key)
133                 except ValueError:
134                         indx = len(csort)
135                         csort.append(key)
136                         csortfile.write(key + '\n')
137                         if val:
138                                 cstr += '+'
139                         else:
140                                 cstr += '-'
141         csortfile.close()
142
143         hsh = hashlib.md5(bytes(cstr, 'UTF-8'))
144         return hsh.hexdigest()
145
146 def __register_conf__(con, conf_num, generator):
147         dtb = database.database()
148         # Solution to configuration
149         wfile = __write_temp_config_file__(con, conf_num)
150         hsh = __calchash__(wfile)
151         filen = os.path.join(sf(conf.configurations_folder), hsh)
152         hshf = hsh
153         if os.path.isfile(filen):
154                 if compare(filen, wfile):
155                         print("I: Generated existing configuration.")
156                         return
157                 else:
158                         print("W: Generated configuration with collision hash.")
159                         # TODO this might have to be tweaked
160                         raise Exception()
161         shutil.move(wfile, filen)
162         dtb.add_configuration(hsh, hshf, generator)
163
164 def __generate_single__(var_num, conf_num):
165         measure_list = set()
166         if not os.path.isfile(sf(conf.single_generated_file)):
167                 with open(sf(conf.measure_file), 'r') as fi:
168                         for ln in fi:
169                                 measure_list.add(int(ln))
170         else:
171                 with open(sf(conf.single_generated_file), 'r') as f:
172                         for ln in f:
173                                 measure_list.add(int(ln))
174         if not measure_list:
175                 return False
176         tfile = __buildtempcnf__(var_num, (sf(conf.rules_file),
177                 sf(conf.fixed_file)), [str(measure_list.pop())])
178         with open(sf(conf.single_generated_file), 'w') as fo:
179                 for ln in measure_list:
180                         fo.write(str(ln) + '\n')
181         try:
182                 confs = __exec_sat__(tfile, ['-i', '0'])
183                 for con in confs:
184                         __register_conf__(con, conf_num, 'single-sat')
185         except exceptions.NoSolution:
186                 __generate_single__(var_num, conf_num)
187         finally:
188                 os.remove(tfile)
189         return True
190
191 def __generate_random__(var_num, conf_num):
192         # TODO
193         #tfile = __buildtempcnf__(var_num, (sf(conf.rules_file), sf(conf.fixed_file)), ())
194         #try:
195                 #confs = __exec_sat__(tfile, [])
196                 #for con in confs:
197                         #__register_conf__(con, conf_num)
198         #finally:
199                 #os.remove(tfile)
200         return False
201
202 def generate():
203         """Collect boolean equations from files rules and required
204         And get solution with picosat
205         """
206         # Check if rules_file exist. If it was generated.
207         if not os.path.isfile(sf(conf.rules_file)):
208                 raise exceptions.MissingFile(conf.rules_file,"Run parse_kconfig.")
209         if not os.path.isfile(sf(conf.fixed_file)):
210                 raise exceptions.MissingFile(conf.required_file,"Run allconfig and initialization process.")
211
212         # Load variable count
213         with open(sf(conf.variable_count_file)) as f:
214                 var_num = f.readline().rstrip()
215                 conf_num = f.readline().rstrip()
216
217         if __generate_single__(var_num, conf_num):
218                 return
219         elif __generate_random__(var_num, conf_num):
220                 return
221
222         raise exceptions.NoNewConfiguration()
223
224 def compare(file1, file2):
225         """Compared two configuration"""
226         conf1 = __load_config_file__(file1)
227         conf2 = __load_config_file__(file2)
228
229         # This is not exactly best comparison method
230         for key, val in conf1.items():
231                 try:
232                         if conf2[key] != val:
233                                 return False
234                 except ValueError:
235                         return False
236         for key, val in conf2.items():
237                 try:
238                         if conf1[key] != val:
239                                 return False
240                 except ValueError:
241                         return False
242         return True