xref: /illumos-gate/usr/src/tools/onbld/Checks/ProcessCheck.py (revision e86372a01d2d16a5dd4a64e144ed978ba17fe7dd)
1#
2# CDDL HEADER START
3#
4# The contents of this file are subject to the terms of the
5# Common Development and Distribution License (the "License").
6# You may not use this file except in compliance with the License.
7#
8# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9# or http://www.opensolaris.org/os/licensing.
10# See the License for the specific language governing permissions
11# and limitations under the License.
12#
13# When distributing Covered Code, include this CDDL HEADER in each
14# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15# If applicable, add the following below this CDDL HEADER, with the
16# fields enclosed by brackets "[]" replaced with your own identifying
17# information: Portions Copyright [yyyy] [name of copyright owner]
18#
19# CDDL HEADER END
20#
21
22#
23# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24# Use is subject to license terms.
25#
26
27# Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
28
29#
30# Wrap a command-line check tool in a pythonic API
31#
32
33import subprocess
34import tempfile
35
36def processcheck(command, args, inpt, output):
37	'''Run a checking command, command, with arguments as args.
38	Input is provided by inpt (an iterable), error output is
39	written to output (a stream-like entity).
40
41	Return a tuple (error, handle), where handle is a file handle
42	(you must close it), containing output from the command.'''
43
44	#
45	# We use a tempfile for output, rather than a pipe, so we
46	# don't deadlock with the child if both pipes fill.
47	#
48	try:
49		tmpfile = tempfile.TemporaryFile(prefix=command, mode="w+")
50	except EnvironmentError as e:
51		output.write("Could not create temporary file: %s\n" % e)
52		return (3, None)
53
54	try:
55		p = subprocess.Popen([command] + args,
56				     stdin=subprocess.PIPE, stdout=tmpfile,
57				     stderr=subprocess.STDOUT, close_fds=False)
58	except OSError as e:
59		output.write("Could not execute %s: %s\n" % (command, e))
60		return (3, None)
61
62	for line in inpt:
63		p.stdin.write(line)
64
65	p.stdin.close()
66
67	ret = p.wait()
68	tmpfile.seek(0)
69
70	return (ret < 0 and 1 or ret, tmpfile)
71