fe44abcbd274be434bb9843f398985e7b14cbbf8
[portage.git] / pym / _emerge / EbuildPhase.py
1 # Copyright 1999-2011 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3
4 import gzip
5 import io
6 import sys
7 import tempfile
8
9 from _emerge.AsynchronousLock import AsynchronousLock
10 from _emerge.BinpkgEnvExtractor import BinpkgEnvExtractor
11 from _emerge.MiscFunctionsProcess import MiscFunctionsProcess
12 from _emerge.EbuildProcess import EbuildProcess
13 from _emerge.CompositeTask import CompositeTask
14 from portage.util import writemsg
15
16 try:
17         from portage.xml.metadata import MetaDataXML
18 except (SystemExit, KeyboardInterrupt):
19         raise
20 except (ImportError, SystemError, RuntimeError, Exception):
21         # broken or missing xml support
22         # http://bugs.python.org/issue14988
23         MetaDataXML = None
24
25 import portage
26 portage.proxy.lazyimport.lazyimport(globals(),
27         'portage.elog:messages@elog_messages',
28         'portage.package.ebuild.doebuild:_check_build_log,' + \
29                 '_post_phase_cmds,_post_phase_userpriv_perms,' + \
30                 '_post_src_install_soname_symlinks,' + \
31                 '_post_src_install_uid_fix,_postinst_bsdflags,' + \
32                 '_post_src_install_write_metadata,' + \
33                 '_preinst_bsdflags'
34 )
35 from portage import os
36 from portage import _encodings
37 from portage import _unicode_encode
38
39 class EbuildPhase(CompositeTask):
40
41         __slots__ = ("actionmap", "phase", "settings") + \
42                 ("_ebuild_lock",)
43
44         # FEATURES displayed prior to setup phase
45         _features_display = (
46                 "ccache", "compressdebug", "distcc", "distcc-pump", "fakeroot",
47                 "installsources", "keeptemp", "keepwork", "nostrip",
48                 "preserve-libs", "sandbox", "selinux", "sesandbox",
49                 "splitdebug", "suidctl", "test", "userpriv",
50                 "usersandbox"
51         )
52
53         # Locked phases
54         _locked_phases = ("setup", "preinst", "postinst", "prerm", "postrm")
55
56         def _start(self):
57
58                 need_builddir = self.phase not in EbuildProcess._phases_without_builddir
59
60                 if need_builddir:
61                         phase_completed_file = os.path.join(
62                                 self.settings['PORTAGE_BUILDDIR'],
63                                 ".%sed" % self.phase.rstrip('e'))
64                         if not os.path.exists(phase_completed_file):
65                                 # If the phase is really going to run then we want
66                                 # to eliminate any stale elog messages that may
67                                 # exist from a previous run.
68                                 try:
69                                         os.unlink(os.path.join(self.settings['T'],
70                                                 'logging', self.phase))
71                                 except OSError:
72                                         pass
73
74                 if self.phase in ('nofetch', 'pretend', 'setup'):
75
76                         use = self.settings.get('PORTAGE_BUILT_USE')
77                         if use is None:
78                                 use = self.settings['PORTAGE_USE']
79
80                         maint_str = ""
81                         upstr_str = ""
82                         metadata_xml_path = os.path.join(os.path.dirname(self.settings['EBUILD']), "metadata.xml")
83                         if MetaDataXML is not None and os.path.isfile(metadata_xml_path):
84                                 herds_path = os.path.join(self.settings['PORTDIR'],
85                                         'metadata/herds.xml')
86                                 try:
87                                         metadata_xml = MetaDataXML(metadata_xml_path, herds_path)
88                                         maint_str = metadata_xml.format_maintainer_string()
89                                         upstr_str = metadata_xml.format_upstream_string()
90                                 except SyntaxError:
91                                         maint_str = "<invalid metadata.xml>"
92
93                         msg = []
94                         msg.append("Package:    %s" % self.settings.mycpv)
95                         if self.settings.get('PORTAGE_REPO_NAME'):
96                                 msg.append("Repository: %s" % self.settings['PORTAGE_REPO_NAME'])
97                         if maint_str:
98                                 msg.append("Maintainer: %s" % maint_str)
99                         if upstr_str:
100                                 msg.append("Upstream:   %s" % upstr_str)
101
102                         msg.append("USE:        %s" % use)
103                         relevant_features = []
104                         enabled_features = self.settings.features
105                         for x in self._features_display:
106                                 if x in enabled_features:
107                                         relevant_features.append(x)
108                         if relevant_features:
109                                 msg.append("FEATURES:   %s" % " ".join(relevant_features))
110
111                         # Force background=True for this header since it's intended
112                         # for the log and it doesn't necessarily need to be visible
113                         # elsewhere.
114                         self._elog('einfo', msg, background=True)
115
116                 if self.phase == 'package':
117                         if 'PORTAGE_BINPKG_TMPFILE' not in self.settings:
118                                 self.settings['PORTAGE_BINPKG_TMPFILE'] = \
119                                         os.path.join(self.settings['PKGDIR'],
120                                         self.settings['CATEGORY'], self.settings['PF']) + '.tbz2'
121
122                 if self.phase in ("pretend", "prerm"):
123                         env_extractor = BinpkgEnvExtractor(background=self.background,
124                                 scheduler=self.scheduler, settings=self.settings)
125                         if env_extractor.saved_env_exists():
126                                 self._start_task(env_extractor, self._env_extractor_exit)
127                                 return
128                         # If the environment.bz2 doesn't exist, then ebuild.sh will
129                         # source the ebuild as a fallback.
130
131                 self._start_lock()
132
133         def _env_extractor_exit(self, env_extractor):
134                 if self._default_exit(env_extractor) != os.EX_OK:
135                         self.wait()
136                         return
137
138                 self._start_lock()
139
140         def _start_lock(self):
141                 if (self.phase in self._locked_phases and
142                         "ebuild-locks" in self.settings.features):
143                         eroot = self.settings["EROOT"]
144                         lock_path = os.path.join(eroot, portage.VDB_PATH + "-ebuild")
145                         if os.access(os.path.dirname(lock_path), os.W_OK):
146                                 self._ebuild_lock = AsynchronousLock(path=lock_path,
147                                         scheduler=self.scheduler)
148                                 self._start_task(self._ebuild_lock, self._lock_exit)
149                                 return
150
151                 self._start_ebuild()
152
153         def _lock_exit(self, ebuild_lock):
154                 if self._default_exit(ebuild_lock) != os.EX_OK:
155                         self.wait()
156                         return
157                 self._start_ebuild()
158
159         def _start_ebuild(self):
160
161                 # Don't open the log file during the clean phase since the
162                 # open file can result in an nfs lock on $T/build.log which
163                 # prevents the clean phase from removing $T.
164                 logfile = None
165                 if self.phase not in ("clean", "cleanrm") and \
166                         self.settings.get("PORTAGE_BACKGROUND") != "subprocess":
167                         logfile = self.settings.get("PORTAGE_LOG_FILE")
168
169                 fd_pipes = None
170                 if not self.background and self.phase == 'nofetch':
171                         # All the pkg_nofetch output goes to stderr since
172                         # it's considered to be an error message.
173                         fd_pipes = {1 : sys.stderr.fileno()}
174
175                 ebuild_process = EbuildProcess(actionmap=self.actionmap,
176                         background=self.background, fd_pipes=fd_pipes, logfile=logfile,
177                         phase=self.phase, scheduler=self.scheduler,
178                         settings=self.settings)
179
180                 self._start_task(ebuild_process, self._ebuild_exit)
181
182         def _ebuild_exit(self, ebuild_process):
183
184                 if self._ebuild_lock is not None:
185                         self._ebuild_lock.unlock()
186                         self._ebuild_lock = None
187
188                 fail = False
189                 if self._default_exit(ebuild_process) != os.EX_OK:
190                         if self.phase == "test" and \
191                                 "test-fail-continue" in self.settings.features:
192                                 pass
193                         else:
194                                 fail = True
195
196                 if not fail:
197                         self.returncode = None
198
199                 logfile = None
200                 if self.settings.get("PORTAGE_BACKGROUND") != "subprocess":
201                         logfile = self.settings.get("PORTAGE_LOG_FILE")
202
203                 if self.phase == "install":
204                         out = io.StringIO()
205                         _check_build_log(self.settings, out=out)
206                         msg = out.getvalue()
207                         self.scheduler.output(msg, log_path=logfile)
208
209                 if fail:
210                         self._die_hooks()
211                         return
212
213                 settings = self.settings
214                 _post_phase_userpriv_perms(settings)
215
216                 if self.phase == "install":
217                         out = io.StringIO()
218                         _post_src_install_write_metadata(settings)
219                         _post_src_install_uid_fix(settings, out)
220                         msg = out.getvalue()
221                         if msg:
222                                 self.scheduler.output(msg, log_path=logfile)
223                 elif self.phase == "preinst":
224                         _preinst_bsdflags(settings)
225                 elif self.phase == "postinst":
226                         _postinst_bsdflags(settings)
227
228                 post_phase_cmds = _post_phase_cmds.get(self.phase)
229                 if post_phase_cmds is not None:
230                         if logfile is not None and self.phase in ("install",):
231                                 # Log to a temporary file, since the code we are running
232                                 # reads PORTAGE_LOG_FILE for QA checks, and we want to
233                                 # avoid annoying "gzip: unexpected end of file" messages
234                                 # when FEATURES=compress-build-logs is enabled.
235                                 fd, logfile = tempfile.mkstemp()
236                                 os.close(fd)
237                         post_phase = MiscFunctionsProcess(background=self.background,
238                                 commands=post_phase_cmds, logfile=logfile, phase=self.phase,
239                                 scheduler=self.scheduler, settings=settings)
240                         self._start_task(post_phase, self._post_phase_exit)
241                         return
242
243                 # this point is not reachable if there was a failure and
244                 # we returned for die_hooks above, so returncode must
245                 # indicate success (especially if ebuild_process.returncode
246                 # is unsuccessful and test-fail-continue came into play)
247                 self.returncode = os.EX_OK
248                 self._current_task = None
249                 self.wait()
250
251         def _post_phase_exit(self, post_phase):
252
253                 self._assert_current(post_phase)
254
255                 log_path = None
256                 if self.settings.get("PORTAGE_BACKGROUND") != "subprocess":
257                         log_path = self.settings.get("PORTAGE_LOG_FILE")
258
259                 if post_phase.logfile is not None and \
260                         post_phase.logfile != log_path:
261                         # We were logging to a temp file (see above), so append
262                         # temp file to main log and remove temp file.
263                         self._append_temp_log(post_phase.logfile, log_path)
264
265                 if self._final_exit(post_phase) != os.EX_OK:
266                         writemsg("!!! post %s failed; exiting.\n" % self.phase,
267                                 noiselevel=-1)
268                         self._die_hooks()
269                         return
270
271                 if self.phase == "install":
272                         out = io.StringIO()
273                         _post_src_install_soname_symlinks(self.settings, out)
274                         msg = out.getvalue()
275                         if msg:
276                                 self.scheduler.output(msg, log_path=log_path)
277
278                 self._current_task = None
279                 self.wait()
280                 return
281
282         def _append_temp_log(self, temp_log, log_path):
283
284                 temp_file = open(_unicode_encode(temp_log,
285                         encoding=_encodings['fs'], errors='strict'), 'rb')
286
287                 log_file, log_file_real = self._open_log(log_path)
288
289                 for line in temp_file:
290                         log_file.write(line)
291
292                 temp_file.close()
293                 log_file.close()
294                 if log_file_real is not log_file:
295                         log_file_real.close()
296                 os.unlink(temp_log)
297
298         def _open_log(self, log_path):
299
300                 f = open(_unicode_encode(log_path,
301                         encoding=_encodings['fs'], errors='strict'),
302                         mode='ab')
303                 f_real = f
304
305                 if log_path.endswith('.gz'):
306                         f =  gzip.GzipFile(filename='', mode='ab', fileobj=f)
307
308                 return (f, f_real)
309
310         def _die_hooks(self):
311                 self.returncode = None
312                 phase = 'die_hooks'
313                 die_hooks = MiscFunctionsProcess(background=self.background,
314                         commands=[phase], phase=phase,
315                         scheduler=self.scheduler, settings=self.settings)
316                 self._start_task(die_hooks, self._die_hooks_exit)
317
318         def _die_hooks_exit(self, die_hooks):
319                 if self.phase != 'clean' and \
320                         'noclean' not in self.settings.features and \
321                         'fail-clean' in self.settings.features:
322                         self._default_exit(die_hooks)
323                         self._fail_clean()
324                         return
325                 self._final_exit(die_hooks)
326                 self.returncode = 1
327                 self.wait()
328
329         def _fail_clean(self):
330                 self.returncode = None
331                 portage.elog.elog_process(self.settings.mycpv, self.settings)
332                 phase = "clean"
333                 clean_phase = EbuildPhase(background=self.background,
334                         phase=phase, scheduler=self.scheduler, settings=self.settings)
335                 self._start_task(clean_phase, self._fail_clean_exit)
336                 return
337
338         def _fail_clean_exit(self, clean_phase):
339                 self._final_exit(clean_phase)
340                 self.returncode = 1
341                 self.wait()
342
343         def _elog(self, elog_funcname, lines, background=None):
344                 if background is None:
345                         background = self.background
346                 out = io.StringIO()
347                 phase = self.phase
348                 elog_func = getattr(elog_messages, elog_funcname)
349                 global_havecolor = portage.output.havecolor
350                 try:
351                         portage.output.havecolor = \
352                                 self.settings.get('NOCOLOR', 'false').lower() in ('no', 'false')
353                         for line in lines:
354                                 elog_func(line, phase=phase, key=self.settings.mycpv, out=out)
355                 finally:
356                         portage.output.havecolor = global_havecolor
357                 msg = out.getvalue()
358                 if msg:
359                         log_path = None
360                         if self.settings.get("PORTAGE_BACKGROUND") != "subprocess":
361                                 log_path = self.settings.get("PORTAGE_LOG_FILE")
362                         self.scheduler.output(msg, log_path=log_path,
363                                 background=background)