1 package org.apache.archiva.scheduler.repository;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.common.ArchivaException;
23 import org.apache.archiva.configuration.ArchivaConfiguration;
24 import org.apache.archiva.configuration.ConfigurationEvent;
25 import org.apache.archiva.configuration.ConfigurationListener;
26 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
27 import org.apache.archiva.metadata.repository.MetadataRepository;
28 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
29 import org.apache.archiva.metadata.repository.RepositorySession;
30 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
31 import org.apache.archiva.metadata.repository.stats.RepositoryStatisticsManager;
32 import org.apache.archiva.redback.components.scheduler.CronExpressionValidator;
33 import org.apache.archiva.redback.components.scheduler.Scheduler;
34 import org.apache.archiva.redback.components.taskqueue.TaskQueue;
35 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
36 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
37 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
38 import org.apache.commons.lang.time.StopWatch;
39 import org.quartz.CronScheduleBuilder;
40 import org.quartz.CronTrigger;
41 import org.quartz.JobBuilder;
42 import org.quartz.JobDataMap;
43 import org.quartz.JobDetail;
44 import org.quartz.SchedulerException;
45 import org.quartz.TriggerBuilder;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.stereotype.Service;
50 import javax.annotation.PostConstruct;
51 import javax.annotation.PreDestroy;
52 import javax.inject.Inject;
53 import javax.inject.Named;
54 import java.util.ArrayList;
55 import java.util.HashSet;
56 import java.util.List;
60 * Default implementation of a scheduling component for archiva.
62 @Service( "archivaTaskScheduler#repository" )
63 public class DefaultRepositoryArchivaTaskScheduler
64 implements RepositoryArchivaTaskScheduler, ConfigurationListener
66 private Logger log = LoggerFactory.getLogger( getClass() );
69 private Scheduler scheduler;
72 private CronExpressionValidator cronValidator;
75 @Named( value = "taskQueue#repository-scanning" )
76 private TaskQueue repositoryScanningQueue;
79 private ArchivaConfiguration archivaConfiguration;
82 @Named( value = "repositoryStatisticsManager#default" )
83 private RepositoryStatisticsManager repositoryStatisticsManager;
86 * TODO: could have multiple implementations
89 private RepositorySessionFactory repositorySessionFactory;
91 private static final String REPOSITORY_SCAN_GROUP = "rg";
93 private static final String REPOSITORY_JOB = "rj";
95 private static final String REPOSITORY_JOB_TRIGGER = "rjt";
97 static final String TASK_QUEUE = "TASK_QUEUE";
99 static final String TASK_REPOSITORY = "TASK_REPOSITORY";
101 public static final String CRON_HOURLY = "0 0 * * * ?";
103 private Set<String> jobs = new HashSet<>();
105 private List<String> queuedRepos = new ArrayList<>();
108 public void startup()
109 throws ArchivaException
112 StopWatch stopWatch = new StopWatch();
115 archivaConfiguration.addListener( this );
117 List<ManagedRepositoryConfiguration> repositories =
118 archivaConfiguration.getConfiguration().getManagedRepositories();
120 RepositorySession repositorySession = repositorySessionFactory.createSession();
123 MetadataRepository metadataRepository = repositorySession.getRepository();
124 for ( ManagedRepositoryConfiguration repoConfig : repositories )
126 if ( repoConfig.isScanned() )
130 scheduleRepositoryJobs( repoConfig );
132 catch ( SchedulerException e )
134 throw new ArchivaException( "Unable to start scheduler: " + e.getMessage(), e );
139 if ( !isPreviouslyScanned( repoConfig, metadataRepository ) )
141 queueInitialRepoScan( repoConfig );
144 catch ( MetadataRepositoryException e )
146 log.warn( "Unable to determine if a repository is already scanned, skipping initial scan: {}",
154 repositorySession.close();
158 log.info( "Time to initalize DefaultRepositoryArchivaTaskScheduler: {} ms", stopWatch.getTime() );
164 throws SchedulerException
166 for ( String job : jobs )
168 scheduler.unscheduleJob( job, REPOSITORY_SCAN_GROUP );
175 @SuppressWarnings( "unchecked" )
177 public boolean isProcessingRepositoryTask( String repositoryId )
179 synchronized ( repositoryScanningQueue )
181 List<RepositoryTask> queue = null;
185 queue = repositoryScanningQueue.getQueueSnapshot();
187 catch ( TaskQueueException e )
189 // not possible with plexus-taskqueue implementation, ignore
192 for ( RepositoryTask queuedTask : queue )
194 if ( queuedTask.getRepositoryId().equals( repositoryId ) )
204 public boolean isProcessingRepositoryTask( RepositoryTask task )
206 synchronized ( repositoryScanningQueue )
208 List<RepositoryTask> queue = null;
212 queue = repositoryScanningQueue.getQueueSnapshot();
214 catch ( TaskQueueException e )
216 // not possible with plexus-taskqueue implementation, ignore
219 for ( RepositoryTask queuedTask : queue )
221 if ( task.equals( queuedTask ) )
231 public void queueTask( RepositoryTask task )
232 throws TaskQueueException
234 synchronized ( repositoryScanningQueue )
236 if ( isProcessingRepositoryTask( task ) )
238 log.debug( "Repository task '{}' is already queued. Skipping task.", task );
242 // add check if the task is already queued if it is a file scan
243 repositoryScanningQueue.put( task );
249 public boolean unQueueTask( RepositoryTask task )
250 throws TaskQueueException
252 synchronized ( repositoryScanningQueue )
254 if ( !isProcessingRepositoryTask( task ) )
256 log.info( "cannot unqueue Repository task '{}' not already queued.", task );
261 return repositoryScanningQueue.remove( task );
267 public void configurationEvent( ConfigurationEvent event )
269 if ( event.getType() == ConfigurationEvent.SAVED )
271 for ( String job : jobs )
275 scheduler.unscheduleJob( job, REPOSITORY_SCAN_GROUP );
277 catch ( SchedulerException e )
279 log.error( "Error restarting the repository scanning job after property change." );
284 List<ManagedRepositoryConfiguration> repositories =
285 archivaConfiguration.getConfiguration().getManagedRepositories();
287 for ( ManagedRepositoryConfiguration repoConfig : repositories )
289 if ( repoConfig.getRefreshCronExpression() != null )
293 scheduleRepositoryJobs( repoConfig );
295 catch ( SchedulerException e )
297 log.error( "error restarting job: '{}' : '{}'", REPOSITORY_JOB, repoConfig.getId() );
304 private boolean isPreviouslyScanned( ManagedRepositoryConfiguration repoConfig,
305 MetadataRepository metadataRepository )
306 throws MetadataRepositoryException
308 long start = System.currentTimeMillis();
310 boolean res = repositoryStatisticsManager.hasStatistics( metadataRepository, repoConfig.getId() );
312 long end = System.currentTimeMillis();
314 log.debug( "isPreviouslyScanned repo {} {} time: {} ms", repoConfig.getId(), res, ( end - start ) );
319 // MRM-848: Pre-configured repository initially appear to be empty
320 private synchronized void queueInitialRepoScan( ManagedRepositoryConfiguration repoConfig )
322 String repoId = repoConfig.getId();
323 RepositoryTask task = new RepositoryTask();
324 task.setRepositoryId( repoId );
326 if ( !queuedRepos.contains( repoId ) )
328 log.info( "Repository [{}] is queued to be scanned as it hasn't been previously.", repoId );
332 queuedRepos.add( repoConfig.getId() );
333 this.queueTask( task );
335 catch ( TaskQueueException e )
337 log.error( "Error occurred while queueing repository [{}] task : {}", e.getMessage(), repoId );
342 private synchronized void scheduleRepositoryJobs( ManagedRepositoryConfiguration repoConfig )
343 throws SchedulerException
345 if ( repoConfig.getRefreshCronExpression() == null )
347 log.warn( "Skipping job, no cron expression for {}", repoConfig.getId() );
351 if ( !repoConfig.isScanned() )
353 log.warn( "Skipping job, repository scannable has been disabled for {}", repoConfig.getId() );
357 // get the cron string for these database scanning jobs
358 String cronString = repoConfig.getRefreshCronExpression();
360 if ( !cronValidator.validate( cronString ) )
362 log.warn( "Cron expression [{}] for repository [{}] is invalid. Defaulting to hourly.", cronString,
363 repoConfig.getId() );
364 cronString = CRON_HOURLY;
367 JobDataMap jobDataMap = new JobDataMap( );
368 jobDataMap.put( TASK_QUEUE, repositoryScanningQueue );
369 jobDataMap.put( TASK_REPOSITORY, repoConfig.getId() );
371 // setup the unprocessed artifact job
372 JobDetail repositoryJob = JobBuilder.newJob( RepositoryTaskJob.class )
373 .withIdentity( REPOSITORY_JOB + ":" + repoConfig.getId(), REPOSITORY_SCAN_GROUP )
374 .setJobData( jobDataMap )
379 CronTrigger trigger = TriggerBuilder.newTrigger()
380 .withIdentity( REPOSITORY_JOB_TRIGGER + ":" + repoConfig.getId(), REPOSITORY_SCAN_GROUP )
381 .withSchedule( CronScheduleBuilder.cronSchedule( cronString ) )
384 jobs.add( REPOSITORY_JOB + ":" + repoConfig.getId() );
385 scheduler.scheduleJob( repositoryJob, trigger );
387 catch ( RuntimeException e )
390 "ParseException in repository scanning cron expression, disabling repository scanning for '': {}",
391 repoConfig.getId(), e.getMessage() );