001/*
002 * #%L
003 * Netarchivesuite - harvester
004 * %%
005 * Copyright (C) 2005 - 2014 The Royal Danish Library, the Danish State and University Library,
006 *             the National Library of France and the Austrian National Library.
007 * %%
008 * This program is free software: you can redistribute it and/or modify
009 * it under the terms of the GNU Lesser General Public License as
010 * published by the Free Software Foundation, either version 2.1 of the
011 * License, or (at your option) any later version.
012 * 
013 * This program is distributed in the hope that it will be useful,
014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016 * GNU General Lesser Public License for more details.
017 * 
018 * You should have received a copy of the GNU General Lesser Public
019 * License along with this program.  If not, see
020 * <http://www.gnu.org/licenses/lgpl-2.1.html>.
021 * #L%
022 */
023package dk.netarkivet.harvester.heritrix3;
024
025import java.io.File;
026import java.util.List;
027
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030
031import dk.netarkivet.common.CommonSettings;
032import dk.netarkivet.common.distribute.ChannelID;
033import dk.netarkivet.common.distribute.JMSConnection;
034import dk.netarkivet.common.distribute.JMSConnectionFactory;
035import dk.netarkivet.common.exceptions.ArgumentNotValid;
036import dk.netarkivet.common.exceptions.IOFailure;
037import dk.netarkivet.common.exceptions.PermissionDenied;
038import dk.netarkivet.common.exceptions.UnknownID;
039import dk.netarkivet.common.lifecycle.PeriodicTaskExecutor;
040import dk.netarkivet.common.utils.ApplicationUtils;
041import dk.netarkivet.common.utils.CleanupIF;
042import dk.netarkivet.common.utils.DomainUtils;
043import dk.netarkivet.common.utils.FileUtils;
044import dk.netarkivet.common.utils.NotificationType;
045import dk.netarkivet.common.utils.NotificationsFactory;
046import dk.netarkivet.common.utils.Settings;
047import dk.netarkivet.common.utils.SystemUtils;
048import dk.netarkivet.common.utils.TimeUtils;
049import dk.netarkivet.harvester.HarvesterSettings;
050import dk.netarkivet.harvester.datamodel.HarvestDefinitionInfo;
051import dk.netarkivet.harvester.datamodel.Job;
052import dk.netarkivet.harvester.datamodel.JobStatus;
053import dk.netarkivet.harvester.distribute.HarvesterChannels;
054import dk.netarkivet.harvester.distribute.HarvesterMessageHandler;
055import dk.netarkivet.harvester.harvesting.distribute.CrawlStatusMessage;
056import dk.netarkivet.harvester.harvesting.distribute.DoOneCrawlMessage;
057import dk.netarkivet.harvester.harvesting.distribute.HarvesterReadyMessage;
058import dk.netarkivet.harvester.harvesting.distribute.HarvesterRegistrationRequest;
059import dk.netarkivet.harvester.harvesting.distribute.HarvesterRegistrationResponse;
060import dk.netarkivet.harvester.harvesting.metadata.MetadataEntry;
061
062/**
063 * This class responds to JMS doOneCrawl messages from the HarvestScheduler and launches a Heritrix crawl with the
064 * received job description. The generated ARC files are uploaded to the bitarchives once a harvest job has been
065 * completed.
066 * <p>
067 * During its operation CrawlStatus messages are sent to the HarvestSchedulerMonitorServer. When starting the actual
068 * harvesting a message is sent with status 'STARTED'. When the harvesting has finished a message is sent with either
069 * status 'DONE' or 'FAILED'. Either a 'DONE' or 'FAILED' message with result should ALWAYS be sent if at all possible,
070 * but only ever one such message per job.
071 * <p>
072 * It is necessary to be able to run the Heritrix harvester on several machines and several processes on each machine.
073 * Each instance of Heritrix is started and monitored by a HarvestControllerServer.
074 * <p>
075 * Initially, all directories under serverdir are scanned for harvestinfo files. If any are found, they are parsed for
076 * information, and all remaining files are attempted uploaded to the bitarchive. It will then send back a
077 * CrawlStatusMessage with status failed.
078 * <p>
079 * A new thread is started for each actual crawl, in which the JMS listener is removed. Threading is required since JMS
080 * will not let the called thread remove the listener that's being handled.
081 * <p>
082 * After a harvestjob has been terminated, either successfully or unsuccessfully, the serverdir is again scanned for
083 * harvestInfo files to attempt upload of files not yet uploaded. Then it begins to listen again after new jobs, if
084 * there is enough room available on the machine. If not, it logs a warning about this, which is also sent as a
085 * notification.
086 */
087public class HarvestControllerServer extends HarvesterMessageHandler implements CleanupIF {
088
089    /** The logger to use. */
090    private static final Logger log = LoggerFactory.getLogger(HarvestControllerServer.class);
091
092    /** The unique instance of this class. */
093    private static HarvestControllerServer instance;
094
095    /** The configured application instance id. @see CommonSettings#APPLICATION_INSTANCE_ID */
096    private final String applicationInstanceId = Settings.get(CommonSettings.APPLICATION_INSTANCE_ID);
097
098    /** The name of the server this <code>HarvestControllerServer</code> is running on. */
099    private final String physicalServerName = DomainUtils.reduceHostname(SystemUtils.getLocalHostName());
100
101    /** Min. space required to start a job. */
102    private final long minSpaceRequired;
103
104    /** The JMSConnection to use. */
105    private JMSConnection jmsConnection;
106
107    /** The JMS channel on which to listen for {@link HarvesterRegistrationResponse}s. */
108    public static final ChannelID HARVEST_CHAN_VALID_RESP_ID = HarvesterChannels
109            .getHarvesterRegistrationResponseChannel();
110
111    private final PostProcessing postProcessing;
112
113    /** The CHANNEL of jobs processed by this instance. */
114    private static final String CHANNEL = Settings.get(HarvesterSettings.HARVEST_CONTROLLER_CHANNEL);
115
116    /** Jobs are fetched from this queue. */
117    private ChannelID jobChannel;
118
119    /** the serverdir, where the harvesting takes place. */
120    private final File serverDir;
121
122    /** This is true while a doOneCrawl is running. No jobs are accepted while this is running. */
123    private CrawlStatus status;
124
125    /**
126     * Returns or creates the unique instance of this singleton The server creates an instance of the HarvestController,
127     * uploads arc-files from unfinished harvests, and starts to listen to JMS messages on the incoming jms queues.
128     * @return The instance
129     * @throws PermissionDenied If the serverdir or oldjobsdir can't be created
130     * @throws IOFailure if data from old harvests exist, but contain illegal data
131     */
132    public static synchronized HarvestControllerServer getInstance() throws IOFailure {
133        if (instance == null) {
134            instance = new HarvestControllerServer();
135        }
136        return instance;
137    }
138
139    /**
140     * In this constructor, the server creates an instance of the HarvestController, uploads any arc-files from
141     * incomplete harvests. Then it starts listening for new doOneCrawl messages, unless there is no available space. In
142     * that case, it sends a notification to the administrator and pauses.
143     * @throws PermissionDenied If the serverdir or oldjobsdir can't be created.
144     * @throws IOFailure If harvestInfoFile contains invalid data.
145     * @throws UnknownID if the settings file does not specify a valid queue priority.
146     */
147    private HarvestControllerServer() throws IOFailure {
148        log.info("Starting HarvestControllerServer.");
149        log.info("Bound to harvest channel '{}'", CHANNEL);
150
151        // Make sure serverdir (where active crawl-dirs live) and oldJobsDir
152        // (where old crawl dirs are stored) exist.
153        serverDir = new File(Settings.get(HarvesterSettings.HARVEST_CONTROLLER_SERVERDIR));
154        ApplicationUtils.dirMustExist(serverDir);
155        log.info("Serverdir: '{}'", serverDir);
156        minSpaceRequired = Settings.getLong(HarvesterSettings.HARVEST_SERVERDIR_MINSPACE);
157        if (minSpaceRequired <= 0L) {
158            log.warn("Wrong setting of minSpaceLeft read from Settings: {}", minSpaceRequired);
159            throw new ArgumentNotValid("Wrong setting of minSpaceLeft read from Settings: " + minSpaceRequired);
160        }
161        log.info("Harvesting requires at least {} bytes free.", minSpaceRequired);
162
163        // Get JMS-connection
164        // Channel THIS_CLIENT is only used for replies to store messages so
165        // do not set as listener here. It is registered in the arcrepository
166        // client.
167        // Channel ANY_xxxPRIORIRY_HACO is used for listening for jobs, and
168        // registered below.
169
170        jmsConnection = JMSConnectionFactory.getInstance();
171        postProcessing = PostProcessing.getInstance(jmsConnection);
172        log.debug("Obtained JMS connection.");
173
174        status = new CrawlStatus();
175
176        // If any unprocessed jobs are left on the server, process them now
177        postProcessing.processOldJobs();
178
179        // Register for listening to harvest channel validity responses
180        JMSConnectionFactory.getInstance().setListener(HARVEST_CHAN_VALID_RESP_ID, this);
181
182        // Ask if the channel this harvester is assigned to is valid
183        jmsConnection.send(new HarvesterRegistrationRequest(HarvestControllerServer.CHANNEL, applicationInstanceId));
184        log.info("Requested to check the validity of harvest channel '{}'", HarvestControllerServer.CHANNEL);
185    }
186
187    /**
188     * Release all jms connections. Close the Controller
189     */
190    public synchronized void close() {
191        log.info("Closing HarvestControllerServer.");
192        cleanup();
193        log.info("Closed down HarvestControllerServer");
194    }
195
196    /**
197     * Will be called on shutdown.
198     *
199     * @see CleanupIF#cleanup()
200     */
201    public void cleanup() {
202        if (jmsConnection != null) {
203            jmsConnection.removeListener(HARVEST_CHAN_VALID_RESP_ID, this);
204            if (jobChannel != null) {
205                jmsConnection.removeListener(jobChannel, this);
206            }
207        }
208        // Stop the sending of status messages
209        status.stopSending();
210        instance = null;
211    }
212
213    @Override
214    public void visit(HarvesterRegistrationResponse msg) {
215        // If we have already started or the message notifies for another channel, resend it.
216        String channelName = msg.getHarvestChannelName();
217        if (status.isChannelValid() || !CHANNEL.equals(channelName)) {
218            // Controller has already started
219            jmsConnection.resend(msg, msg.getTo());
220            if (log.isTraceEnabled()) {
221                log.trace("Resending harvest channel validity message for channel '{}'", channelName);
222            }
223            return;
224        }
225
226        if (!msg.isValid()) {
227            log.error("Received message stating that channel '{}' is invalid. Will stop. "
228                        + "Probable cause: the channel is not one of the known channels stored in the channels table", channelName);
229            close();
230            return;
231        }
232
233        log.info("Received message stating that channel '{}' is valid.", channelName);
234        // Environment and connections are now ready for processing of messages
235        jobChannel = HarvesterChannels.getHarvestJobChannelId(channelName, msg.isSnapshot());
236
237        // Only listen for harvester jobs if enough available space
238        beginListeningIfSpaceAvailable();
239
240        // Notify the harvest dispatcher that we are ready
241        startAcceptingJobs();
242        status.startSending();
243    }
244
245    /** Start listening for crawls, if space available. */
246    private void beginListeningIfSpaceAvailable() {
247        long availableSpace = FileUtils.getBytesFree(serverDir);
248        if (availableSpace > minSpaceRequired) {
249            log.info("Starts to listen to new jobs on queue '{}'", jobChannel);
250            jmsConnection.setListener(jobChannel, this);
251        } else {
252            String pausedMessage = "Not enough available diskspace. Only " + availableSpace + " bytes available."
253                    + " Harvester is paused.";
254            log.error(pausedMessage);
255            NotificationsFactory.getInstance().notify(pausedMessage, NotificationType.ERROR);
256        }
257    }
258
259    /**
260     * Start listening for new crawl requests again. This actually doesn't re-add a listener, but the listener only gets
261     * removed when we're so far committed that we're going to exit at the end. So to start accepting jobs again, we
262     * stop resending messages we get.
263     */
264    private synchronized void startAcceptingJobs() {
265        // allow this harvestControllerServer to receive messages again
266        status.setRunning(false);
267    }
268
269    /**
270     * Stop accepting more jobs. After this is called, all crawl messages received will be resent to the queue. A bit
271     * further down, we will stop listening altogether, but that requires another thread.
272     */
273    private synchronized void stopAcceptingJobs() {
274        status.setRunning(true);
275        log.debug("No longer accepting jobs.");
276    }
277
278    /**
279     * Stop listening for new crawl requests.
280     */
281    private void removeListener() {
282        log.debug("Removing listener on CHANNEL '{}'", jobChannel);
283        jmsConnection.removeListener(jobChannel, this);
284    }
285
286    /**
287     * Checks that we're available to do a crawl, and if so, marks us as unavailable, checks that the job message is
288     * well-formed, and starts the thread that the crawl happens in. If an error occurs starting the crawl, we will
289     * start listening for messages again.
290     * <p>
291     * The sequence of actions involved in a crawl are:</br> 1. If we are already running, resend the job to the queue
292     * and return</br> 2. Check the job for validity</br> 3. Send a CrawlStatus message that crawl has STARTED</br> In a
293     * separate thread:</br> 4. Unregister this HACO as listener</br> 5. Create a new crawldir (based on the JobID and a
294     * timestamp)</br> 6. Write a harvestInfoFile (using JobID and crawldir) and metadata</br> 7. Instantiate a new
295     * HeritrixLauncher</br> 8. Start a crawl</br> 9. Store the generated arc-files and metadata in the known
296     * bit-archives </br>10. _Always_ send CrawlStatus DONE or FAILED</br> 11. Move crawldir into oldJobs dir</br>
297     *
298     * @param msg The crawl job
299     * @throws IOFailure On trouble harvesting, uploading or processing harvestInfo
300     * @throws UnknownID if jobID is null in the message
301     * @throws ArgumentNotValid if the status of the job is not valid - must be SUBMITTED
302     * @throws PermissionDenied if the crawldir can't be created
303     * @see #visit(DoOneCrawlMessage) for more details
304     */
305    public void visit(DoOneCrawlMessage msg) throws IOFailure, UnknownID, ArgumentNotValid, PermissionDenied {
306        // Only one doOneCrawl at a time. Returning should almost never happen,
307        // since we deregister the listener, but we may receive another message
308        // before the listener is removed. Also, if the job message is
309        // malformed or starting the crawl fails, we re-add the listener.
310        synchronized (this) {
311            if (status.isRunning()) {
312                log.warn(
313                        "Received crawl request, but sent it back to queue, as another crawl is already running: '{}'",
314                        msg);
315                jmsConnection.resend(msg, jobChannel);
316                try {
317                    // Wait a second before listening again, so the message has
318                    // a chance of getting snatched by another harvester.
319                    Thread.sleep(TimeUtils.SECOND_IN_MILLIS);
320                } catch (InterruptedException e) {
321                    // Since we're not waiting for anything critical, we can
322                    // ignore this exception.
323                }
324                return;
325            }
326            stopAcceptingJobs();
327        }
328
329        Thread t = null;
330
331        // This 'try' matches a finally that restores running=false if we don't
332        // start a crawl after all
333        try {
334            final Job job = msg.getJob();
335
336            // Every job must have an ID or we can do nothing with it, not even
337            // send a proper failure message back.
338            Long jobID = job.getJobID();
339            if (jobID == null) {
340                log.warn("DoOneCrawlMessage arrived without JobID: '{}'", msg.toString());
341                throw new UnknownID("DoOneCrawlMessage arrived without JobID");
342            }
343
344            log.info("Received crawlrequest for job {}: '{}'", jobID, msg);
345
346            // Send message to scheduler that job is started
347            CrawlStatusMessage csmStarted = new CrawlStatusMessage(jobID, JobStatus.STARTED);
348            jmsConnection.send(csmStarted);
349
350            // Jobs should arrive with status "submitted". If this is not the
351            // case, log the error and send a job-failed message back.
352            // HarvestScheduler likes getting a STARTED message before
353            // FAILED, so we oblige it here.
354            if (job.getStatus() != JobStatus.SUBMITTED) {
355                String message = "Message '" + msg.toString() + "' arrived with" + " status " + job.getStatus()
356                        + " for job " + jobID + ", should have been STATUS_SUBMITTED";
357                log.warn(message);
358                sendErrorMessage(jobID, message, message);
359                throw new ArgumentNotValid(message);
360            }
361
362            final List<MetadataEntry> metadataEntries = msg.getMetadata();
363
364            Thread t1;
365            // Create thread in which harvesting will occur
366            t1 = new HarvesterThread(job, msg.getOrigHarvestInfo(), metadataEntries);
367            // start thread which will remove this listener, harvest, store, and
368            // exit the VM
369            t1.start();
370            log.info("Started harvester thread for job {}", jobID);
371            // We delay assigning the thread variable until start() has
372            // succeeded. Thus, if start() fails, we will resume accepting
373            // jobs.
374            t = t1;
375        } finally {
376            // If we didn't start a thread for crawling after all, accept more
377            // messages
378            if (t == null) {
379                startAcceptingJobs();
380            }
381        }
382        // Now return from this method letting the thread do the work.
383        // This is important as it allows us to receive upload-replies from
384        // THIS_CLIENT in the crawl thread.
385    }
386
387    /**
388     * Sends a CrawlStatusMessage for a failed job with the given short message and detailed message.
389     *
390     * @param jobID ID of the job that failed
391     * @param message A short message indicating what went wrong
392     * @param detailedMessage A more detailed message detailing why it went wrong.
393     */
394    public void sendErrorMessage(long jobID, String message, String detailedMessage) {
395        CrawlStatusMessage csm = new CrawlStatusMessage(jobID, JobStatus.FAILED, null);
396        csm.setHarvestErrors(message);
397        csm.setHarvestErrorDetails(detailedMessage);
398        jmsConnection.send(csm);
399    }
400
401    /**
402     * A Thread class for the actual harvesting. This is required in order to stop listening while we're busy
403     * harvesting, since JMS doesn't allow the called thread to remove the listener that was called.
404     */
405    private class HarvesterThread extends Thread {
406
407        /** The harvester Job in this thread. */
408        private final Job job;
409
410        /** Stores documentary information about the harvest. */
411        private final HarvestDefinitionInfo origHarvestInfo;
412
413        /** The list of metadata associated with this Job. */
414        private final List<MetadataEntry> metadataEntries;
415
416        /**
417         * Constructor for the HarvesterThread class.
418         *
419         * @param job a harvesting job
420         * @param origHarvestInfo Info about the harvestdefinition that scheduled this job
421         * @param metadataEntries metadata associated with the given job
422         */
423        public HarvesterThread(Job job, HarvestDefinitionInfo origHarvestInfo, List<MetadataEntry> metadataEntries) {
424            this.job = job;
425            this.origHarvestInfo = origHarvestInfo;
426            this.metadataEntries = metadataEntries;
427        }
428
429        /**
430         * The thread body for the harvester thread. Removes the JMS listener, sets up the files for Heritrix, then
431         * passes control to the HarvestController to perform the actual harvest.
432         * <p>
433         *
434         * @throws PermissionDenied if we cannot create the crawl directory.
435         * @throws IOFailure if there are problems preparing or running the crawl.
436         */
437        public void run() {
438            try {
439                // We must remove the listener inside a thread,
440                // as JMS doesn't allow us to remove it within the
441                // call it made.
442                removeListener();
443
444                HarvestJob harvestJob = new HarvestJob(instance);
445                harvestJob.init(job, origHarvestInfo, metadataEntries);
446                Heritrix3Files files = harvestJob.getHeritrix3Files();
447
448                Throwable crawlException = null;
449                try {
450                    harvestJob.runHarvest();
451                } catch (Throwable e) {
452                    String msg = "Error during crawling. The crawl may have been only partially completed.";
453                    log.warn(msg, e);
454                    crawlException = e;
455                    throw new IOFailure(msg, e);
456                } finally {
457                        postProcessing.doPostProcessing(files.getCrawlDir(), crawlException);
458                }
459            } catch (Throwable t) {
460                String msg = "Fatal error while operating job '" + job + "'";
461                log.error(msg, t);
462                NotificationsFactory.getInstance().notify(msg, NotificationType.ERROR, t);
463            } finally {
464                log.info("Ending crawl of job : {}", job.getJobID());
465                // process serverdir for files not yet uploaded.
466                postProcessing.processOldJobs();
467                shutdownNowOrContinue();
468                startAcceptingJobs();
469                beginListeningIfSpaceAvailable();
470            }
471        }
472
473        /**
474         * Does the operator want us to shutdown now. TODO In a later implementation, the harvestControllerServer could
475         * be notified over JMX. Now we just look for a "shutdown.txt" file in the HARVEST_CONTROLLER_SERVERDIR
476         */
477        private void shutdownNowOrContinue() {
478            File shutdownFile = new File(serverDir, "shutdown.txt");
479            if (shutdownFile.exists()) {
480                log.info("Found shutdown-file in serverdir - " + "shutting down the application");
481                instance.cleanup();
482                System.exit(0);
483            }
484        }
485    }
486
487    /**
488     * Used for maintaining the running status of the crawling, is it running or not. Will also take care of notifying
489     * the HarvestJobManager of the status.
490     */
491    private class CrawlStatus implements Runnable {
492
493        /** The status. */
494        private Boolean running = false;
495
496        private boolean channelIsValid = false;
497
498        /** Handles the periodic sending of status messages. */
499        private PeriodicTaskExecutor statusTransmitter;
500
501        private final int SEND_READY_DELAY = Settings.getInt(HarvesterSettings.SEND_READY_DELAY);
502
503        /**
504         * Starts the sending of status messages.
505         */
506        public void startSending() {
507            this.channelIsValid = true;
508            statusTransmitter = new PeriodicTaskExecutor("HarvesterStatus", this, 0,
509                        Settings.getInt(HarvesterSettings.SEND_READY_INTERVAL));
510        }
511
512        /**
513         * Stops the sending of status messages.
514         */
515        public void stopSending() {
516            if (statusTransmitter != null) {
517                statusTransmitter.shutdown();
518                statusTransmitter = null;
519            }
520        }
521
522        /**
523         * Returns <code>true</code> if the a doOneCrawl is running, else <code>false</code>.
524         * @return Whether a crawl running.
525         */
526        public boolean isRunning() {
527            return running;
528        }
529
530        /**
531         * Use for changing the running state.
532         * @param running The new status
533         */
534        public void setRunning(boolean running) {
535            this.running = running;
536        }
537
538        /**
539         * @return the channelIsValid
540         */
541        protected final boolean isChannelValid() {
542            return channelIsValid;
543        }
544
545        @Override
546        public void run() {
547            try {
548                Thread.sleep(SEND_READY_DELAY);
549            } catch (Exception e) {
550                log.error("Unable to sleep", e);
551            }
552            if (!running) {
553                jmsConnection.send(new HarvesterReadyMessage(applicationInstanceId + " on " + physicalServerName,
554                        HarvestControllerServer.CHANNEL));
555            }
556        }
557
558    }
559
560}