1 package org.apache.archiva.repository.base;
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
20 import org.apache.archiva.components.registry.RegistryException;
21 import org.apache.archiva.configuration.Configuration;
22 import org.apache.archiva.configuration.IndeterminateConfigurationException;
23 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
24 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
25 import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler;
26 import org.apache.archiva.repository.CheckedResult;
27 import org.apache.archiva.repository.EditableRepository;
28 import org.apache.archiva.repository.EditableRepositoryGroup;
29 import org.apache.archiva.repository.ManagedRepository;
30 import org.apache.archiva.repository.RepositoryException;
31 import org.apache.archiva.repository.RepositoryGroup;
32 import org.apache.archiva.repository.RepositoryHandler;
33 import org.apache.archiva.repository.RepositoryProvider;
34 import org.apache.archiva.repository.RepositoryType;
35 import org.apache.archiva.repository.event.RepositoryEvent;
36 import org.apache.archiva.repository.features.IndexCreationFeature;
37 import org.apache.archiva.repository.storage.StorageAsset;
38 import org.apache.archiva.repository.validation.RepositoryChecker;
39 import org.apache.archiva.repository.validation.RepositoryValidator;
40 import org.apache.commons.lang3.StringUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.stereotype.Service;
45 import javax.annotation.PostConstruct;
46 import javax.annotation.PreDestroy;
47 import javax.inject.Named;
48 import java.io.IOException;
49 import java.nio.file.Files;
50 import java.nio.file.Path;
51 import java.util.Collection;
52 import java.util.Collections;
53 import java.util.HashMap;
54 import java.util.LinkedHashMap;
55 import java.util.List;
57 import java.util.concurrent.locks.ReentrantReadWriteLock;
58 import java.util.stream.Collectors;
60 import static org.apache.archiva.indexer.ArchivaIndexManager.DEFAULT_INDEX_PATH;
63 * This class manages repository groups for the RepositoryRegistry.
64 * It is tightly coupled with the {@link ArchivaRepositoryRegistry}.
66 * @author Martin Stockhammer <martin_s@apache.org>
68 @Service( "repositoryGroupHandler#default" )
69 public class RepositoryGroupHandler implements RepositoryHandler<RepositoryGroup, RepositoryGroupConfiguration>
71 private static final Logger log = LoggerFactory.getLogger( RepositoryGroupHandler.class );
73 private final ArchivaRepositoryRegistry repositoryRegistry;
74 private final ConfigurationHandler configurationHandler;
75 private final MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler;
77 private final Map<String, RepositoryGroup> repositoryGroups = new HashMap<>( );
78 private final RepositoryValidator<RepositoryGroup> validator;
80 private Path groupsDirectory;
84 * Creates a new instance. All dependencies are injected on the constructor.
86 * @param repositoryRegistry the registry. To avoid circular dependencies via DI, this class registers itself on the registry.
87 * @param configurationHandler the configuration handler is used to retrieve and save configuration.
88 * @param mergedRemoteIndexesScheduler the index scheduler is used for merging the indexes from all group members
90 public RepositoryGroupHandler( ArchivaRepositoryRegistry repositoryRegistry,
91 ConfigurationHandler configurationHandler,
92 @Named( "mergedRemoteIndexesScheduler#default" ) MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler,
93 @Named( "repositoryValidator#common#group") RepositoryValidator<RepositoryGroup> repositoryGroupValidator
96 this.configurationHandler = configurationHandler;
97 this.mergedRemoteIndexesScheduler = mergedRemoteIndexesScheduler;
98 this.repositoryRegistry = repositoryRegistry;
99 this.validator = repositoryGroupValidator;
106 log.debug( "Initializing repository group handler " + repositoryRegistry.toString( ) );
107 initializeStorage( );
108 // We are registering this class on the registry. This is necessary to avoid circular dependencies via injection.
109 this.repositoryRegistry.registerGroupHandler( this );
112 public void initializeFromConfig( )
114 this.repositoryGroups.clear( );
115 this.repositoryGroups.putAll( newInstancesFromConfig( ) );
116 for ( RepositoryGroup group : this.repositoryGroups.values( ) )
118 initializeGroup( group );
122 private void initializeStorage( )
124 Path baseDir = this.configurationHandler.getArchivaConfiguration( ).getRepositoryGroupBaseDir( );
125 if ( !Files.exists( baseDir ) )
129 Files.createDirectories( baseDir );
131 catch ( IOException e )
133 log.error( "Could not create group base directory: {}", e.getMessage( ), e );
136 this.groupsDirectory = baseDir;
139 private void initializeGroup( RepositoryGroup repositoryGroup )
141 StorageAsset indexDirectory = getMergedIndexDirectory( repositoryGroup );
142 if ( !indexDirectory.exists( ) )
146 indexDirectory.create( );
148 catch ( IOException e )
150 log.error( "Could not create index directory {} for group {}: {}", indexDirectory, repositoryGroup.getId( ), e.getMessage( ) );
153 Path groupPath = groupsDirectory.resolve( repositoryGroup.getId( ) );
154 if ( !Files.exists( groupPath ) )
158 Files.createDirectories( groupPath );
160 catch ( IOException e )
162 log.error( "Could not create repository group directory {}", groupPath );
165 mergedRemoteIndexesScheduler.schedule( repositoryGroup,
169 public StorageAsset getMergedIndexDirectory( RepositoryGroup group )
173 return group.getFeature( IndexCreationFeature.class ).get( ).getLocalIndexPath( );
183 public Map<String, RepositoryGroup> newInstancesFromConfig( )
187 List<RepositoryGroupConfiguration> repositoryGroupConfigurations =
188 this.configurationHandler.getBaseConfiguration( ).getRepositoryGroups( );
190 if ( repositoryGroupConfigurations == null )
192 return Collections.emptyMap( );
195 Map<String, RepositoryGroup> repositoryGroupMap = new LinkedHashMap<>( repositoryGroupConfigurations.size( ) );
197 Map<RepositoryType, RepositoryProvider> providerMap = repositoryRegistry.getRepositoryProviderMap( );
198 for ( RepositoryGroupConfiguration repoConfig : repositoryGroupConfigurations )
200 RepositoryType repositoryType = RepositoryType.valueOf( repoConfig.getType( ) );
201 if ( providerMap.containsKey( repositoryType ) )
205 RepositoryGroup repo = createNewRepositoryGroup( providerMap.get( repositoryType ), repoConfig );
206 repositoryGroupMap.put( repo.getId( ), repo );
208 catch ( Exception e )
210 log.error( "Could not create repository group {}: {}", repoConfig.getId( ), e.getMessage( ), e );
214 return repositoryGroupMap;
216 catch ( Throwable e )
218 log.error( "Could not initialize repositories from config: {}", e.getMessage( ), e );
219 return Collections.emptyMap( );
224 public RepositoryGroup newInstance( final RepositoryType type, String id ) throws RepositoryException
226 RepositoryProvider provider = repositoryRegistry.getProvider( type );
227 RepositoryGroupConfiguration config = new RepositoryGroupConfiguration( );
229 return createNewRepositoryGroup( provider, config );
233 public RepositoryGroup newInstance( final RepositoryGroupConfiguration repositoryConfiguration ) throws RepositoryException
235 RepositoryType type = RepositoryType.valueOf( repositoryConfiguration.getType( ) );
236 RepositoryProvider provider = repositoryRegistry.getProvider( type );
237 return createNewRepositoryGroup( provider, repositoryConfiguration );
240 private RepositoryGroup createNewRepositoryGroup( RepositoryProvider provider, RepositoryGroupConfiguration config ) throws RepositoryException
242 RepositoryGroup repositoryGroup = provider.createRepositoryGroup( config );
243 updateReferences( repositoryGroup, config );
244 return repositoryGroup;
249 * Adds a new repository group to the current list, or replaces the repository group definition with
250 * the same id, if it exists already.
251 * The change is saved to the configuration immediately.
253 * @param repositoryGroup the new repository group.
254 * @throws RepositoryException if the new repository group could not be saved to the configuration.
257 public RepositoryGroup put( final RepositoryGroup repositoryGroup ) throws RepositoryException
259 final String id = repositoryGroup.getId( );
260 RepositoryGroup originRepoGroup = repositoryGroups.remove( id );
263 if ( originRepoGroup != null && originRepoGroup != repositoryGroup )
265 this.mergedRemoteIndexesScheduler.unschedule( originRepoGroup );
266 originRepoGroup.close( );
268 RepositoryProvider provider = repositoryRegistry.getProvider( repositoryGroup.getType( ) );
269 RepositoryGroupConfiguration newCfg = provider.getRepositoryGroupConfiguration( repositoryGroup );
270 ReentrantReadWriteLock.WriteLock configLock = this.configurationHandler.getLock( ).writeLock( );
274 Configuration configuration = this.configurationHandler.getBaseConfiguration( );
275 updateReferences( repositoryGroup, newCfg );
276 RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( id );
277 if ( oldCfg != null )
279 configuration.removeRepositoryGroup( oldCfg );
281 configuration.addRepositoryGroup( newCfg );
282 configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
283 initializeGroup( repositoryGroup );
287 configLock.unlock( );
289 repositoryGroups.put( id, repositoryGroup );
290 return repositoryGroup;
292 catch ( Exception e )
295 if ( originRepoGroup != null )
297 repositoryGroups.put( id, originRepoGroup );
301 repositoryGroups.remove( id );
303 log.error( "Exception during configuration update {}", e.getMessage( ), e );
304 throw new RepositoryException( "Could not save the configuration" + ( e.getMessage( ) == null ? "" : ": " + e.getMessage( ) ), e);
309 * Adds a new repository group or updates the repository with the same id, if it exists already.
310 * The configuration is saved immediately.
312 * @param repositoryGroupConfiguration the repository configuration
313 * @return the updated or created repository
314 * @throws RepositoryException if an error occurs, or the configuration is not valid.
317 public RepositoryGroup put( RepositoryGroupConfiguration repositoryGroupConfiguration ) throws RepositoryException
319 final String id = repositoryGroupConfiguration.getId( );
320 final RepositoryType repositoryType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) );
321 final RepositoryProvider provider = repositoryRegistry.getProvider( repositoryType );
322 RepositoryGroup currentRepository;
323 ReentrantReadWriteLock.WriteLock configLock = this.configurationHandler.getLock( ).writeLock( );
327 Configuration configuration = this.configurationHandler.getBaseConfiguration( );
328 currentRepository = repositoryRegistry.getRepositoryGroup( id );
329 RepositoryGroup oldRepository = currentRepository == null ? null : clone( currentRepository );
333 if (currentRepository==null) {
334 currentRepository = put( repositoryGroupConfiguration, configuration );
337 setRepositoryGroupDefaults( repositoryGroupConfiguration );
338 provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, repositoryGroupConfiguration );
340 configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
341 updateReferences( currentRepository, repositoryGroupConfiguration );
342 initializeGroup( currentRepository );
343 this.repositoryGroups.put( id, currentRepository );
345 catch ( IndeterminateConfigurationException | RegistryException | RepositoryException e )
348 if ( oldRepository != null )
350 RepositoryGroupConfiguration oldCfg = provider.getRepositoryGroupConfiguration( oldRepository );
351 provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, oldCfg);
352 replaceOrAddRepositoryConfig( oldCfg, configuration );
355 configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
357 catch ( IndeterminateConfigurationException | RegistryException indeterminateConfigurationException )
359 log.error( "Fatal error, config save during rollback failed: {}", e.getMessage( ), e );
361 updateReferences( oldRepository, oldCfg );
362 initializeGroup( oldRepository );
364 log.error( "Could not save the configuration for repository group {}: {}", id, e.getMessage( ), e );
365 if (e instanceof RepositoryException) {
366 throw (RepositoryException) e;
369 throw new RepositoryException( "Could not save the configuration for repository group " + id + ": " + e.getMessage( ) );
375 configLock.unlock( );
377 return currentRepository;
381 public RepositoryGroup put( RepositoryGroupConfiguration repositoryGroupConfiguration, Configuration configuration ) throws RepositoryException
383 final String id = repositoryGroupConfiguration.getId( );
384 final RepositoryType repoType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) );
385 RepositoryGroup repo;
386 setRepositoryGroupDefaults( repositoryGroupConfiguration );
387 if ( repositoryGroups.containsKey( id ) )
389 repo = clone( repositoryGroups.get( id ) );
390 if ( repo instanceof EditableRepositoryGroup )
392 repositoryRegistry.getProvider( repoType ).updateRepositoryGroupInstance( (EditableRepositoryGroup) repo, repositoryGroupConfiguration );
396 throw new RepositoryException( "The repository is not editable " + id );
401 repo = repositoryRegistry.getProvider( repoType ).createRepositoryGroup( repositoryGroupConfiguration );
403 replaceOrAddRepositoryConfig( repositoryGroupConfiguration, configuration );
404 updateReferences( repo, repositoryGroupConfiguration );
409 public <D> CheckedResult<RepositoryGroup, D> putWithCheck( RepositoryGroupConfiguration repositoryConfiguration, RepositoryChecker<RepositoryGroup, D> checker ) throws RepositoryException
411 final String id = repositoryConfiguration.getId( );
412 RepositoryGroup currentGroup = repositoryGroups.get( id );
413 Configuration configuration = configurationHandler.getBaseConfiguration( );
414 RepositoryGroup repositoryGroup = put( repositoryConfiguration, configuration );
415 CheckedResult<RepositoryGroup, D> result;
416 if ( currentGroup == null )
418 result = checker.apply( repositoryGroup );
422 result = checker.applyForUpdate( repositoryGroup );
424 if ( result.isValid( ) )
426 put( result.getRepository() );
432 private void setRepositoryGroupDefaults( RepositoryGroupConfiguration repositoryGroupConfiguration )
434 if ( StringUtils.isEmpty( repositoryGroupConfiguration.getMergedIndexPath( ) ) )
436 repositoryGroupConfiguration.setMergedIndexPath( DEFAULT_INDEX_PATH );
438 if ( repositoryGroupConfiguration.getMergedIndexTtl( ) <= 0 )
440 repositoryGroupConfiguration.setMergedIndexTtl( 300 );
442 if ( StringUtils.isEmpty( repositoryGroupConfiguration.getCronExpression( ) ) )
444 repositoryGroupConfiguration.setCronExpression( "0 0 03 ? * MON" );
448 private void replaceOrAddRepositoryConfig( RepositoryGroupConfiguration repositoryGroupConfiguration, Configuration configuration )
450 RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( repositoryGroupConfiguration.getId( ) );
451 if ( oldCfg != null )
453 configuration.removeRepositoryGroup( oldCfg );
455 configuration.addRepositoryGroup( repositoryGroupConfiguration );
458 public void removeRepositoryFromGroups( ManagedRepository repo )
462 repositoryGroups.values( ).stream( ).filter( repoGroup -> repoGroup instanceof EditableRepository ).
463 map( repoGroup -> (EditableRepositoryGroup) repoGroup ).forEach( repoGroup -> repoGroup.removeRepository( repo ) );
468 * Removes a repository group from the registry and configuration, if it exists.
469 * The change is saved to the configuration immediately.
471 * @param id the id of the repository group to remove
472 * @throws RepositoryException if a error occurs during configuration save
475 public void remove( final String id ) throws RepositoryException
477 RepositoryGroup repo = get( id );
482 repo = repositoryGroups.remove( id );
485 this.mergedRemoteIndexesScheduler.unschedule( repo );
487 Configuration configuration = this.configurationHandler.getBaseConfiguration( );
488 RepositoryGroupConfiguration cfg = configuration.findRepositoryGroupById( id );
491 configuration.removeRepositoryGroup( cfg );
493 this.configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
497 catch ( RegistryException | IndeterminateConfigurationException e )
500 log.error( "Could not save config after repository removal: {}", e.getMessage( ), e );
501 repositoryGroups.put( repo.getId( ), repo );
502 throw new RepositoryException( "Could not save configuration after repository removal: " + e.getMessage( ) );
508 public void remove( String id, Configuration configuration ) throws RepositoryException
510 RepositoryGroup repo = repositoryGroups.get( id );
513 repo = repositoryGroups.remove( id );
516 this.mergedRemoteIndexesScheduler.unschedule( repo );
518 RepositoryGroupConfiguration cfg = configuration.findRepositoryGroupById( id );
521 configuration.removeRepositoryGroup( cfg );
529 public RepositoryGroup get( String groupId )
531 return repositoryGroups.get( groupId );
535 public RepositoryGroup clone( RepositoryGroup repo ) throws RepositoryException
537 RepositoryProvider provider = repositoryRegistry.getProvider( repo.getType( ) );
538 RepositoryGroupConfiguration cfg = provider.getRepositoryGroupConfiguration( repo );
539 RepositoryGroup cloned = provider.createRepositoryGroup( cfg );
540 cloned.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
545 public void updateReferences( RepositoryGroup repo, RepositoryGroupConfiguration repositoryConfiguration ) throws RepositoryException
547 if ( repo instanceof EditableRepositoryGroup )
549 EditableRepositoryGroup eGroup = (EditableRepositoryGroup) repo;
550 eGroup.setRepositories( repositoryConfiguration.getRepositories( ).stream( )
551 .map( repositoryRegistry::getManagedRepository ).collect( Collectors.toList( ) ) );
557 public Collection<RepositoryGroup> getAll( )
559 return repositoryGroups.values( );
563 public RepositoryValidator<RepositoryGroup> getValidator( )
565 return this.validator;
569 public boolean has( String id )
571 return repositoryGroups.containsKey( id );
575 private void destroy( )
583 for ( RepositoryGroup group : repositoryGroups.values( ) )
587 mergedRemoteIndexesScheduler.unschedule( group );
590 catch ( Throwable e )
592 log.error( "Could not close repository group {}: {}", group.getId( ), e.getMessage( ) );
595 this.repositoryGroups.clear( );