depend.apache.eclass: Let APXS point to the new location of the binary.
[gentoo.git] / eclass / multiprocessing.eclass
1 # Copyright 1999-2014 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 # $Id$
4
5 # @ECLASS: multiprocessing.eclass
6 # @MAINTAINER:
7 # base-system@gentoo.org
8 # @AUTHOR:
9 # Brian Harring <ferringb@gentoo.org>
10 # Mike Frysinger <vapier@gentoo.org>
11 # @BLURB: parallelization with bash (wtf?)
12 # @DESCRIPTION:
13 # The multiprocessing eclass contains a suite of functions that allow ebuilds
14 # to quickly run things in parallel using shell code.
15 #
16 # It has two modes: pre-fork and post-fork.  If you don't want to dive into any
17 # more nuts & bolts, just use the pre-fork mode.  For main threads that mostly
18 # spawn children and then wait for them to finish, use the pre-fork mode.  For
19 # main threads that do a bit of processing themselves, use the post-fork mode.
20 # You may mix & match them for longer computation loops.
21 # @EXAMPLE:
22 #
23 # @CODE
24 # # First initialize things:
25 # multijob_init
26 #
27 # # Then hash a bunch of files in parallel:
28 # for n in {0..20} ; do
29 #       multijob_child_init md5sum data.${n} > data.${n}
30 # done
31 #
32 # # Then wait for all the children to finish:
33 # multijob_finish
34 # @CODE
35
36 if [[ -z ${_MULTIPROCESSING_ECLASS} ]]; then
37 _MULTIPROCESSING_ECLASS=1
38
39 # @FUNCTION: bashpid
40 # @DESCRIPTION:
41 # Return the process id of the current sub shell.  This is to support bash
42 # versions older than 4.0 that lack $BASHPID support natively.  Simply do:
43 # echo ${BASHPID:-$(bashpid)}
44 #
45 # Note: Using this func in any other way than the one above is not supported.
46 bashpid() {
47         # Running bashpid plainly will return incorrect results.  This func must
48         # be run in a subshell of the current subshell to get the right pid.
49         # i.e. This will show the wrong value:
50         #   bashpid
51         # But this will show the right value:
52         #   (bashpid)
53         sh -c 'echo ${PPID}'
54 }
55
56 # @FUNCTION: get_nproc
57 # @USAGE: [${fallback:-1}]
58 # @DESCRIPTION:
59 # Attempt to figure out the number of processing units available.
60 # If the value can not be determined, prints the provided fallback
61 # instead. If no fallback is provided, defaults to 1.
62 get_nproc() {
63         local nproc
64
65         # GNU
66         if type -P nproc &>/dev/null; then
67                 nproc=$(nproc)
68         fi
69
70         # BSD
71         if [[ -z ${nproc} ]] && type -P sysctl &>/dev/null; then
72                 nproc=$(sysctl -n hw.ncpu 2>/dev/null)
73         fi
74
75         # fallback to python2.6+
76         # note: this may fail (raise NotImplementedError)
77         if [[ -z ${nproc} ]] && type -P python &>/dev/null; then
78                 nproc=$(python -c 'import multiprocessing; print(multiprocessing.cpu_count());' 2>/dev/null)
79         fi
80
81         if [[ -n ${nproc} ]]; then
82                 echo "${nproc}"
83         else
84                 echo "${1:-1}"
85         fi
86 }
87
88 # @FUNCTION: makeopts_jobs
89 # @USAGE: [${MAKEOPTS}] [${inf:-999}]
90 # @DESCRIPTION:
91 # Searches the arguments (defaults to ${MAKEOPTS}) and extracts the jobs number
92 # specified therein.  Useful for running non-make tools in parallel too.
93 # i.e. if the user has MAKEOPTS=-j9, this will echo "9" -- we can't return the
94 # number as bash normalizes it to [0, 255].  If the flags haven't specified a
95 # -j flag, then "1" is shown as that is the default `make` uses.  Since there's
96 # no way to represent infinity, we return ${inf} (defaults to 999) if the user
97 # has -j without a number.
98 makeopts_jobs() {
99         [[ $# -eq 0 ]] && set -- ${MAKEOPTS}
100         # This assumes the first .* will be more greedy than the second .*
101         # since POSIX doesn't specify a non-greedy match (i.e. ".*?").
102         local jobs=$(echo " $* " | sed -r -n \
103                 -e 's:.*[[:space:]](-[a-z]*j|--jobs[=[:space:]])[[:space:]]*([0-9]+).*:\2:p' \
104                 -e "s:.*[[:space:]](-[a-z]*j|--jobs)[[:space:]].*:${2:-999}:p")
105         echo ${jobs:-1}
106 }
107
108 # @FUNCTION: makeopts_loadavg
109 # @USAGE: [${MAKEOPTS}] [${inf:-999}]
110 # @DESCRIPTION:
111 # Searches the arguments (defaults to ${MAKEOPTS}) and extracts the value set
112 # for load-average. For make and ninja based builds this will mean new jobs are
113 # not only limited by the jobs-value, but also by the current load - which might
114 # get excessive due to I/O and not just due to CPU load.
115 # Be aware that the returned number might be a floating-point number. Test
116 # whether your software supports that.
117 # If no limit is specified or --load-average is used without a number, ${inf}
118 # (defaults to 999) is returned.
119 makeopts_loadavg() {
120         [[ $# -eq 0 ]] && set -- ${MAKEOPTS}
121         # This assumes the first .* will be more greedy than the second .*
122         # since POSIX doesn't specify a non-greedy match (i.e. ".*?").
123         local lavg=$(echo " $* " | sed -r -n \
124                 -e 's:.*[[:space:]](-[a-z]*l|--(load-average|max-load)[=[:space:]])[[:space:]]*([0-9]+|[0-9]+\.[0-9]+).*:\3:p' \
125                 -e "s:.*[[:space:]](-[a-z]*l|--(load-average|max-load))[[:space:]].*:${2:-999}:p")
126         # Default to ${inf} since the default is to not use a load limit.
127         echo ${lavg:-${2:-999}}
128 }
129
130 # @FUNCTION: multijob_init
131 # @USAGE: [${MAKEOPTS}]
132 # @DESCRIPTION:
133 # Setup the environment for executing code in parallel.
134 # You must call this before any other multijob function.
135 multijob_init() {
136         # When something goes wrong, try to wait for all the children so we
137         # don't leave any zombies around.
138         has wait ${EBUILD_DEATH_HOOKS} || EBUILD_DEATH_HOOKS+=" wait "
139
140         # Setup a pipe for children to write their pids to when they finish.
141         # We have to allocate two fd's because POSIX has undefined behavior
142         # when you open a FIFO for simultaneous read/write. #487056
143         local pipe="${T}/multijob.pipe"
144         mkfifo -m 600 "${pipe}"
145         redirect_alloc_fd mj_write_fd "${pipe}"
146         redirect_alloc_fd mj_read_fd "${pipe}"
147         rm -f "${pipe}"
148
149         # See how many children we can fork based on the user's settings.
150         mj_max_jobs=$(makeopts_jobs "$@")
151         mj_num_jobs=0
152 }
153
154 # @FUNCTION: multijob_child_init
155 # @USAGE: [--pre|--post] [command to run in background]
156 # @DESCRIPTION:
157 # This function has two forms.  You can use it to execute a simple command
158 # in the background (and it takes care of everything else), or you must
159 # call this first thing in your forked child process.
160 #
161 # The --pre/--post options allow you to select the child generation mode.
162 #
163 # @CODE
164 # # 1st form: pass the command line as arguments:
165 # multijob_child_init ls /dev
166 # # Or if you want to use pre/post fork modes:
167 # multijob_child_init --pre ls /dev
168 # multijob_child_init --post ls /dev
169 #
170 # # 2nd form: execute multiple stuff in the background (post fork):
171 # (
172 # multijob_child_init
173 # out=`ls`
174 # if echo "${out}" | grep foo ; then
175 #       echo "YEAH"
176 # fi
177 # ) &
178 # multijob_post_fork
179 #
180 # # 2nd form: execute multiple stuff in the background (pre fork):
181 # multijob_pre_fork
182 # (
183 # multijob_child_init
184 # out=`ls`
185 # if echo "${out}" | grep foo ; then
186 #       echo "YEAH"
187 # fi
188 # ) &
189 # @CODE
190 multijob_child_init() {
191         local mode="pre"
192         case $1 in
193         --pre)  mode="pre" ; shift ;;
194         --post) mode="post"; shift ;;
195         esac
196
197         if [[ $# -eq 0 ]] ; then
198                 trap 'echo ${BASHPID:-$(bashpid)} $? >&'${mj_write_fd} EXIT
199                 trap 'exit 1' INT TERM
200         else
201                 local ret
202                 [[ ${mode} == "pre" ]] && { multijob_pre_fork; ret=$?; }
203                 ( multijob_child_init ; "$@" ) &
204                 [[ ${mode} == "post" ]] && { multijob_post_fork; ret=$?; }
205                 return ${ret}
206         fi
207 }
208
209 # @FUNCTION: _multijob_fork
210 # @INTERNAL
211 # @DESCRIPTION:
212 # Do the actual book keeping.
213 _multijob_fork() {
214         [[ $# -eq 1 ]] || die "incorrect number of arguments"
215
216         local ret=0
217         [[ $1 == "post" ]] && : $(( ++mj_num_jobs ))
218         if [[ ${mj_num_jobs} -ge ${mj_max_jobs} ]] ; then
219                 multijob_finish_one
220                 ret=$?
221         fi
222         [[ $1 == "pre" ]] && : $(( ++mj_num_jobs ))
223         return ${ret}
224 }
225
226 # @FUNCTION: multijob_pre_fork
227 # @DESCRIPTION:
228 # You must call this in the parent process before forking a child process.
229 # If the parallel limit has been hit, it will wait for one child to finish
230 # and return its exit status.
231 multijob_pre_fork() { _multijob_fork pre "$@" ; }
232
233 # @FUNCTION: multijob_post_fork
234 # @DESCRIPTION:
235 # You must call this in the parent process after forking a child process.
236 # If the parallel limit has been hit, it will wait for one child to finish
237 # and return its exit status.
238 multijob_post_fork() { _multijob_fork post "$@" ; }
239
240 # @FUNCTION: multijob_finish_one
241 # @DESCRIPTION:
242 # Wait for a single process to exit and return its exit code.
243 multijob_finish_one() {
244         [[ $# -eq 0 ]] || die "${FUNCNAME} takes no arguments"
245
246         local pid ret
247         read -r -u ${mj_read_fd} pid ret || die
248         : $(( --mj_num_jobs ))
249         return ${ret}
250 }
251
252 # @FUNCTION: multijob_finish
253 # @DESCRIPTION:
254 # Wait for all pending processes to exit and return the bitwise or
255 # of all their exit codes.
256 multijob_finish() {
257         local ret=0
258         while [[ ${mj_num_jobs} -gt 0 ]] ; do
259                 multijob_finish_one
260                 : $(( ret |= $? ))
261         done
262         # Let bash clean up its internal child tracking state.
263         wait
264
265         # Do this after reaping all the children.
266         [[ $# -eq 0 ]] || die "${FUNCNAME} takes no arguments"
267
268         # No need to hook anymore.
269         EBUILD_DEATH_HOOKS=${EBUILD_DEATH_HOOKS/ wait / }
270
271         return ${ret}
272 }
273
274 # @FUNCTION: redirect_alloc_fd
275 # @USAGE: <var> <file> [redirection]
276 # @DESCRIPTION:
277 # Find a free fd and redirect the specified file via it.  Store the new
278 # fd in the specified variable.  Useful for the cases where we don't care
279 # about the exact fd #.
280 redirect_alloc_fd() {
281         local var=$1 file=$2 redir=${3:-"<>"}
282
283         # Make sure /dev/fd is sane on Linux hosts. #479656
284         if [[ ! -L /dev/fd && ${CBUILD} == *linux* ]] ; then
285                 eerror "You're missing a /dev/fd symlink to /proc/self/fd."
286                 eerror "Please fix the symlink and check your boot scripts (udev/etc...)."
287                 die "/dev/fd is broken"
288         fi
289
290         if [[ $(( (BASH_VERSINFO[0] << 8) + BASH_VERSINFO[1] )) -ge $(( (4 << 8) + 1 )) ]] ; then
291                 # Newer bash provides this functionality.
292                 eval "exec {${var}}${redir}'${file}'"
293         else
294                 # Need to provide the functionality ourselves.
295                 local fd=10
296                 while :; do
297                         # Make sure the fd isn't open.  It could be a char device,
298                         # or a symlink (possibly broken) to something else.
299                         if [[ ! -e /dev/fd/${fd} ]] && [[ ! -L /dev/fd/${fd} ]] ; then
300                                 eval "exec ${fd}${redir}'${file}'" && break
301                         fi
302                         [[ ${fd} -gt 1024 ]] && die 'could not locate a free temp fd !?'
303                         : $(( ++fd ))
304                 done
305                 : $(( ${var} = fd ))
306         fi
307 }
308
309 fi