summaryrefslogtreecommitdiffstats
path: root/src/engine/SCons/Job.py
blob: 76d856a535b6a17f7a32c4911711814e7466e397 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""SCons.Job

This module defines the Serial and Parallel classes that execute tasks to
complete a build. The Jobs class provides a higher level interface to start,
stop, and wait on jobs.

"""

#
# Copyright (c) 2001, 2002, 2003 Steven Knight
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import time

class Jobs:
    """An instance of this class initializes N jobs, and provides
    methods for starting, stopping, and waiting on all N jobs.
    """
    
    def __init__(self, num, taskmaster):
        """
        create 'num' jobs using the given taskmaster.

        If 'num' is 1 or less, then a serial job will be used,
        otherwise 'num' parallel jobs will be used.
        """

        # Keeps track of keyboard interrupts:
        self.keyboard_interrupt = 0

        if num > 1:
            self.jobs = []
            for i in range(num):
                self.jobs.append(Parallel(taskmaster, self))
        else:
            self.jobs = [Serial(taskmaster, self)]
   
        self.running = []

    def run(self):
        """run the jobs, and wait for them to finish"""

        try:
            for job in self.jobs:
                job.start()
                self.running.append(job)
            while self.running:
                self.running[-1].wait()
                self.running.pop()
        except KeyboardInterrupt:
            # mask any further keyboard interrupts so that scons
            # can shutdown cleanly:
            # (this only masks the keyboard interrupt for Python,
            #  child processes can still get the keyboard interrupt)
            import signal
            signal.signal(signal.SIGINT, signal.SIG_IGN)

            for job in self.running:
                job.keyboard_interrupt()
            else:
                self.keyboard_interrupt = 1

            # wait on any remaining jobs to finish:
            for job in self.running:
                job.wait()

        if self.keyboard_interrupt:
            raise KeyboardInterrupt
    
class Serial:
    """This class is used to execute tasks in series, and is more efficient
    than Parallel, but is only appropriate for non-parallel builds. Only
    one instance of this class should be in existence at a time.

    This class is not thread safe.
    """

    def __init__(self, taskmaster, jobs):
        """Create a new serial job given a taskmaster. 

        The taskmaster's next_task() method should return the next task
        that needs to be executed, or None if there are no more tasks. The
        taskmaster's executed() method will be called for each task when it
        is successfully executed or failed() will be called if it failed to
        execute (e.g. execute() raised an exception). The taskmaster's
        is_blocked() method will not be called.  """
        
        self.taskmaster = taskmaster
        self.jobs = jobs

    def start(self):
        
        """Start the job. This will begin pulling tasks from the taskmaster
        and executing them, and return when there are no more tasks. If a task
        fails to execute (i.e. execute() raises an exception), then the job will
        stop."""
        
        while not self.jobs.keyboard_interrupt:
            task = self.taskmaster.next_task()

            if task is None:
                break

            try:
                task.prepare()
                task.execute()
            except KeyboardInterrupt:
                raise
            except:
                # Let the failed() callback function arrange for the
                # build to stop if that's appropriate.
                task.failed()
            else:
                task.executed()

    def wait(self):
        """Serial jobs are always finished when start() returns, so there
        is nothing to do here"""
        pass
    
    def keyboard_interrupt(self):
        self.jobs.keyboard_interrupt = 1


# The will hold a condition variable once the first parallel task
# is created.
cv = None

class Parallel:
    """This class is used to execute tasks in parallel, and is less
    efficient than Serial, but is appropriate for parallel builds. Create
    an instance of this class for each job or thread you want.

    This class is thread safe.
    """


    def __init__(self, taskmaster, jobs):
        """Create a new parallel job given a taskmaster, and a Jobs instance.
        Multiple jobs will be using the taskmaster in parallel, but all
        method calls to taskmaster methods are serialized by the jobs
        themselves.

        The taskmaster's next_task() method should return the next task
        that needs to be executed, or None if there are no more tasks. The
        taskmaster's executed() method will be called for each task when it
        is successfully executed or failed() will be called if the task
        failed to execute (i.e. execute() raised an exception).  The
        taskmaster's is_blocked() method should return true iff there are
        more tasks, but they can't be executed until one or more other
        tasks have been executed. next_task() will be called iff
        is_blocked() returned false.

        Note: calls to taskmaster are serialized, but calls to execute() on
        distinct tasks are not serialized, because that is the whole point
        of parallel jobs: they can execute multiple tasks
        simultaneously. """

        global cv
        
        # import threading here so that everything in the Job module
        # but the Parallel class will work if the interpreter doesn't
        # support threads
        import threading
        
        self.taskmaster = taskmaster
        self.jobs = jobs
        self.thread = threading.Thread(None, self.__run)

        if cv is None:
            cv = threading.Condition()

    def start(self):
        """Start the job. This will spawn a thread that will begin pulling
        tasks from the task master and executing them. This method returns
        immediately and doesn't wait for the jobs to be executed.

        To wait for the job to finish, call wait().
        """
        self.thread.start()

    def wait(self):
        """Wait for the job to finish. A job is finished when there
        are no more tasks.

        This method should only be called after start() has been called.
        """

        # Sleeping in a loop like this is lame. Calling 
        # self.thread.join() would be much nicer, but
        # on Linux self.thread.join() doesn't always
        # return when a KeyboardInterrupt happens, and when
        # it does return, it causes Python to hang on shutdown.
        # In other words this is just
        # a work-around for some bugs/limitations in the
        # self.thread.join() method.
        while self.thread.isAlive():
            time.sleep(0.5)

    def keyboard_interrupt(self):
        cv.acquire()
        self.jobs.keyboard_interrupt = 1
        cv.notifyAll()
        cv.release()

    def __run(self):
        """private method that actually executes the tasks"""

        cv.acquire()

        try:

            while 1:
                while (self.taskmaster.is_blocked() and 
                       not self.jobs.keyboard_interrupt):
                    cv.wait(None)

                if self.jobs.keyboard_interrupt:
                    break
                    
                task = self.taskmaster.next_task()

                if task == None:
                    break

                try:
                    task.prepare()
                    cv.release()
                    try:
                        task.execute()
                    finally:
                        cv.acquire()
                except KeyboardInterrupt:
                    self.jobs.keyboard_interrupt = 1
                except:
                    # Let the failed() callback function arrange for
                    # calling self.jobs.stop() to to stop the build
                    # if that's appropriate.
                    task.failed()
                else:
                    task.executed()

                # signal the cv whether the task failed or not,
                # or otherwise the other Jobs might
                # remain blocked:
                if (not self.taskmaster.is_blocked() or
                    self.jobs.keyboard_interrupt):
                    cv.notifyAll()
                    
        finally:
            cv.release()