summaryrefslogtreecommitdiff
path: root/src/main/java/hudson/plugins/gearman/GearmanProxy.java
blob: 26935e87a02020164efd38bb8970e04810f17892 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 *
 * Copyright 2013 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package hudson.plugins.gearman;

import hudson.model.Computer;
import hudson.model.Node;
import hudson.model.Run;
import hudson.model.Queue;
import hudson.model.queue.CauseOfBlockage;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import jenkins.model.Jenkins;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is used to startup and shutdown the gearman workers.
 * It is also used to keep gearman plugin state info.
 *
 * @author Khai Do
 */
public class GearmanProxy {

    private static GearmanProxy gearmanProxy;

    private static final Logger logger = LoggerFactory
            .getLogger(Constants.PLUGIN_LOGGER_NAME);

    // handles to gearman workers
    private final List<ExecutorWorkerThread> gewtHandles;
    private final List<ManagementWorkerThread> gmwtHandles;
    private final String masterName;

    // Singleton instance
    public static synchronized GearmanProxy getInstance() {
        if (gearmanProxy == null) {
            gearmanProxy = new GearmanProxy();
        }
        return gearmanProxy;
    }

    // constructor
    private GearmanProxy() {
        gewtHandles = Collections.synchronizedList(new ArrayList<ExecutorWorkerThread>());
        gmwtHandles = Collections.synchronizedList(new ArrayList<ManagementWorkerThread>());

        Computer master = null;
        String hostname = Constants.GEARMAN_DEFAULT_EXECUTOR_NAME;
        // query Jenkins for master's name
        try {
            master = Jenkins.getActiveInstance().getComputer("");
            hostname = master.getHostName();
        } catch (Exception e) {
            logger.warn("Exception while getting hostname", e);
        }
        // master node may not be enabled so get masterName from system
        if (master == null) {
            try {
                hostname = java.net.InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                logger.warn("Exception while getting hostname", e);
            }
        }

        masterName = hostname;
    }

    /*
     * This method is for unit tests only.
     */
    protected void testResetHandles() {
        gmwtHandles.clear();
        gewtHandles.clear();
    }

    /*
     * This method initializes the  gearman workers.
     */
    public void initWorkers() {
        /*
         * Purpose here is to create a 1:1 mapping of 'gearman worker':'jenkins
         * executor' then use the gearman worker to execute builds on that
         * jenkins nodes
         */

        /*
         * Spawn management executor worker. This worker does not need any
         * executors. It only needs to work with gearman.
         */
        createManagementWorker();

        /*
         * Spawn executors for the jenkins master Need to treat the master
         * differently than slaves because the master is not the same as a
         * slave
         */
        // first make sure master is enabled (or has executors)
        Node masterNode = null;
        try {
            masterNode = Jenkins.getActiveInstance().getComputer("").getNode();
        } catch (NullPointerException npe) {
            logger.info("---- Master is offline");
        } catch (Exception e) {
            logger.error("Exception while finding master", e);
        }

        if (masterNode != null) {
            Computer computer = masterNode.toComputer();
            if (computer != null) {
                createExecutorWorkersOnNode(computer);
            }
        }

        /*
         * Spawn executors for the jenkins slaves
         */
        List<Node> nodes = Jenkins.getActiveInstance().getNodes();
        if (!nodes.isEmpty()) {
            for (Node node : nodes) {
                Computer computer = node.toComputer();
                if (computer != null) {
                    // create a gearman worker for every executor on the slave
                    createExecutorWorkersOnNode(computer);
                }
            }
        }

        logger.info("---- Num of executors running = " + getNumExecutors());
    }

    /*
     * Spawn management executor workers. This worker does not need any
     * executors. It only needs to connect to gearman.
     */
    public void createManagementWorker() {
        ManagementWorkerThread gwt;

        synchronized (gmwtHandles) {
            if (!gmwtHandles.isEmpty()) {
                return;
            }

            gwt = new ManagementWorkerThread(
                GearmanPluginConfig.get().getHost(),
                GearmanPluginConfig.get().getPort(),
                masterName + "_manager",
                masterName, new NoopAvailabilityMonitor());
            gmwtHandles.add(gwt);
            gwt.start();
        }

        logger.info("---- Num of executors running = " + getNumExecutors());
    }

    /*
     * Spawn workers for each executor on a node.
     */
    public void createExecutorWorkersOnNode(Computer computer) {

        // find the computer in the executor workers list
        synchronized(gewtHandles) {
            for (ExecutorWorkerThread t : gewtHandles) {
                if (t.getComputer() == computer) {
                    logger.info("---- Executor thread already running for " + computer.getName());
                    return;
                }
            }

            AvailabilityMonitor availability = new NodeAvailabilityMonitor(computer);

            int executors = computer.getExecutors().size();
            for (int i = 0; i < executors; i++) {
                String nodeName = null;

                nodeName = GearmanPluginUtil.getRealName(computer);
                if (nodeName == "master") {
                    nodeName = masterName;
                }

                ExecutorWorkerThread ewt = new ExecutorWorkerThread(
                    GearmanPluginConfig.get().getHost(),
                    GearmanPluginConfig.get().getPort(),
                    nodeName+"_exec-"+Integer.toString(i),
                    computer, masterName, availability);

                ewt.start();
                gewtHandles.add(ewt);
            }
        }

        logger.info("---- Num of executors running = " + getNumExecutors());

    }

    /*
     * This method stops all gearman workers
     */
    public void stopAll() {
        // stop gearman executors
        List<AbstractWorkerThread> stopHandles;

        synchronized(gewtHandles) {
            stopHandles = new ArrayList<AbstractWorkerThread>(gewtHandles);
            gewtHandles.clear();
        }

        for (AbstractWorkerThread wt : stopHandles) { // stop executors
            wt.stop();
        }

        synchronized(gmwtHandles) {
            stopHandles = new ArrayList<AbstractWorkerThread>(gmwtHandles);
            gmwtHandles.clear();
        }

        for (AbstractWorkerThread wt : stopHandles) { // stop executors
            wt.stop();
        }

        logger.info("---- Num of executors running = " + getNumExecutors());
    }

    /*
     * This method stops all threads on the gewtHandles list that
     * is used to  service the jenkins slave/computer
     *
     *
     * @param Node
     *      The Computer to stop
     *
     */
    public void stop(Computer computer) {
        logger.info("---- Stop computer " + computer);
        List<ExecutorWorkerThread> workers = new ArrayList<ExecutorWorkerThread>();

        synchronized(gewtHandles) {
            // find the computer in the executor workers list and stop it
            for (Iterator<ExecutorWorkerThread> it = gewtHandles.iterator(); it.hasNext(); ) {
                ExecutorWorkerThread t = it.next();
                if (t.getComputer() == computer) {
                    workers.add(t);
                    it.remove();
                }
            }
        }

        for (ExecutorWorkerThread t : workers) {
            t.stop();
        }

        logger.info("---- Num of executors running = " + getNumExecutors());
    }

    /*
     * This method returns the total number of gearman executor threads
     */
    public int getNumExecutors() {
        return gmwtHandles.size() + gewtHandles.size();
    }

    public void onBuildFinalized(Run r) {
        Computer computer = r.getExecutor().getOwner();
        // A build just finished, so let the AvailabilityMonitor
        // associated with its node wake up any workers who may be
        // waiting for the lock.

        AvailabilityMonitor availability = null;
        synchronized(gewtHandles) {
            for (ExecutorWorkerThread t : gewtHandles) {
                if (t.getComputer() == computer) {
                    availability = t.getAvailability();
                }
            }
        }
        if (availability != null) {
            availability.wake();
        }
    }

    public AvailabilityMonitor getAvailabilityMonitor(Computer computer) {
        synchronized (gewtHandles) {
            for (ExecutorWorkerThread t : gewtHandles) {
                if (t.getComputer() == computer) {
                    return t.getAvailability();
                }
            }
        }
        return null;
    }

    public CauseOfBlockage canTake(Node node,
                                   Queue.BuildableItem item) {
        // Ask the AvailabilityMonitor for this node if it's okay to
        // run this build.
        ExecutorWorkerThread workerThread = null;

        synchronized(gewtHandles) {
            Computer computer = node.toComputer();
            for (ExecutorWorkerThread t : gewtHandles) {
                if (t.getComputer() == computer) {
                    workerThread = t;
                    break;
                }
            }
        }

        if (workerThread != null) {
            if (workerThread.getAvailability().canTake(item)) {
                return null;
            } else {
                return new CauseOfBlockage.BecauseNodeIsBusy(node);
            }
        }
        return null;
    }

    public void registerJobs() {
        synchronized(gewtHandles) {
            for (ExecutorWorkerThread worker : gewtHandles) {
                worker.registerJobs();
            }
        }
    }
}