1 package org.apache.archiva.metadata.repository.stats;
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.metadata.model.ArtifactMetadata;
23 import org.apache.archiva.metadata.repository.MetadataRepository;
24 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
25 import org.apache.archiva.metadata.repository.MetadataResolutionException;
26 import org.apache.archiva.metadata.repository.storage.maven2.MavenArtifactFacet;
27 import org.apache.jackrabbit.commons.JcrUtils;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.stereotype.Service;
32 import java.text.ParseException;
33 import java.text.SimpleDateFormat;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.HashMap;
39 import java.util.List;
41 import java.util.TimeZone;
42 import javax.jcr.Node;
43 import javax.jcr.RepositoryException;
44 import javax.jcr.Session;
45 import javax.jcr.query.Query;
46 import javax.jcr.query.QueryManager;
47 import javax.jcr.query.QueryResult;
48 import javax.jcr.query.Row;
51 * plexus.component role="org.apache.archiva.metadata.repository.stats.RepositoryStatisticsManager" role-hint="default"
53 @Service("repositoryStatisticsManager#default")
54 public class DefaultRepositoryStatisticsManager
55 implements RepositoryStatisticsManager
57 private static final Logger log = LoggerFactory.getLogger( DefaultRepositoryStatisticsManager.class );
59 private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" );
61 public RepositoryStatistics getLastStatistics( MetadataRepository metadataRepository, String repositoryId )
62 throws MetadataRepositoryException
64 // TODO: consider a more efficient implementation that directly gets the last one from the content repository
65 List<String> scans = metadataRepository.getMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
66 Collections.sort( scans );
67 if ( !scans.isEmpty() )
69 String name = scans.get( scans.size() - 1 );
70 return (RepositoryStatistics) metadataRepository.getMetadataFacet( repositoryId,
71 RepositoryStatistics.FACET_ID, name );
79 private void walkRepository( MetadataRepository metadataRepository, RepositoryStatistics stats, String repositoryId,
81 throws MetadataResolutionException
83 for ( String namespace : metadataRepository.getNamespaces( repositoryId, ns ) )
85 walkRepository( metadataRepository, stats, repositoryId, ns + "." + namespace );
88 Collection<String> projects = metadataRepository.getProjects( repositoryId, ns );
89 if ( !projects.isEmpty() )
91 stats.setTotalGroupCount( stats.getTotalGroupCount() + 1 );
92 stats.setTotalProjectCount( stats.getTotalProjectCount() + projects.size() );
94 for ( String project : projects )
96 for ( String version : metadataRepository.getProjectVersions( repositoryId, ns, project ) )
98 for ( ArtifactMetadata artifact : metadataRepository.getArtifacts( repositoryId, ns, project,
101 stats.setTotalArtifactCount( stats.getTotalArtifactCount() + 1 );
102 stats.setTotalArtifactFileSize( stats.getTotalArtifactFileSize() + artifact.getSize() );
104 MavenArtifactFacet facet = (MavenArtifactFacet) artifact.getFacet(
105 MavenArtifactFacet.FACET_ID );
108 String type = facet.getType();
109 stats.setTotalCountForType( type, stats.getTotalCountForType( type ) + 1 );
117 public void addStatisticsAfterScan( MetadataRepository metadataRepository, String repositoryId, Date startTime,
118 Date endTime, long totalFiles, long newFiles )
119 throws MetadataRepositoryException
121 RepositoryStatistics repositoryStatistics = new RepositoryStatistics();
122 repositoryStatistics.setScanStartTime( startTime );
123 repositoryStatistics.setScanEndTime( endTime );
124 repositoryStatistics.setTotalFileCount( totalFiles );
125 repositoryStatistics.setNewFileCount( newFiles );
128 // In the future, instead of being tied to a scan we might want to record information in the fly based on
129 // events that are occurring. Even without these totals we could query much of the information on demand based
130 // on information from the metadata content repository. In the mean time, we lock information in at scan time.
131 // Note that if new types are later discoverable due to a code change or new plugin, historical stats will not
132 // be updated and the repository will need to be rescanned.
134 long startGather = System.currentTimeMillis();
136 if ( metadataRepository.canObtainAccess( Session.class ) )
138 // TODO: this is currently very raw and susceptible to changes in content structure. Should we instead
139 // depend directly on the plugin and interrogate the JCR repository's knowledge of the structure?
140 populateStatisticsFromJcr( (Session) metadataRepository.obtainAccess( Session.class ), repositoryId,
141 repositoryStatistics );
146 // if the file repository is used more permanently, we may seek a more efficient mechanism - e.g. we could
147 // build an index, or store the aggregate information and update it on the fly. We can perhaps even walk
148 // but retrieve less information to speed it up. In the mean time, we walk the repository using the
150 populateStatisticsFromRepositoryWalk( metadataRepository, repositoryId, repositoryStatistics );
153 log.info( "Gathering statistics executed in " + ( System.currentTimeMillis() - startGather ) + "ms" );
155 metadataRepository.addMetadataFacet( repositoryId, repositoryStatistics );
158 private void populateStatisticsFromJcr( Session session, String repositoryId,
159 RepositoryStatistics repositoryStatistics )
160 throws MetadataRepositoryException
162 // TODO: these may be best as running totals, maintained by observations on the properties in JCR
166 QueryManager queryManager = session.getWorkspace().getQueryManager();
168 // TODO: JCR-SQL2 query will not complete on a large repo in Jackrabbit 2.2.0 - see JCR-2835
169 // Using the JCR-SQL2 variants gives
170 // "org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024"
171 // String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])";
172 // Query query = queryManager.createQuery( "SELECT size FROM [archiva:artifact] " + whereClause,
174 String whereClause = "WHERE jcr:path LIKE '/repositories/" + repositoryId + "/content/%'";
175 Query query = queryManager.createQuery( "SELECT size FROM archiva:artifact " + whereClause, Query.SQL );
177 QueryResult queryResult = query.execute();
179 Map<String, Integer> totalByType = new HashMap<String, Integer>();
180 long totalSize = 0, totalArtifacts = 0;
181 for ( Row row : JcrUtils.getRows( queryResult ) )
183 Node n = row.getNode();
184 totalSize += row.getValue( "size" ).getLong();
187 if ( n.hasNode( MavenArtifactFacet.FACET_ID ) )
189 Node facetNode = n.getNode( MavenArtifactFacet.FACET_ID );
190 type = facetNode.getProperty( "type" ).getString();
196 Integer prev = totalByType.get( type );
197 totalByType.put( type, prev != null ? prev + 1 : 1 );
202 repositoryStatistics.setTotalArtifactCount( totalArtifacts );
203 repositoryStatistics.setTotalArtifactFileSize( totalSize );
204 for ( Map.Entry<String, Integer> entry : totalByType.entrySet() )
206 repositoryStatistics.setTotalCountForType( entry.getKey(), entry.getValue() );
209 // The query ordering is a trick to ensure that the size is correct, otherwise due to lazy init it will be -1
210 // query = queryManager.createQuery( "SELECT * FROM [archiva:project] " + whereClause, Query.JCR_SQL2 );
211 query = queryManager.createQuery( "SELECT * FROM archiva:project " + whereClause + " ORDER BY jcr:score",
213 repositoryStatistics.setTotalProjectCount( query.execute().getRows().getSize() );
215 // query = queryManager.createQuery(
216 // "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL", Query.JCR_SQL2 );
217 query = queryManager.createQuery(
218 "SELECT * FROM archiva:namespace " + whereClause + " AND namespace IS NOT NULL ORDER BY jcr:score",
220 repositoryStatistics.setTotalGroupCount( query.execute().getRows().getSize() );
222 catch ( RepositoryException e )
224 throw new MetadataRepositoryException( e.getMessage(), e );
228 private void populateStatisticsFromRepositoryWalk( MetadataRepository metadataRepository, String repositoryId,
229 RepositoryStatistics repositoryStatistics )
230 throws MetadataRepositoryException
234 for ( String ns : metadataRepository.getRootNamespaces( repositoryId ) )
236 walkRepository( metadataRepository, repositoryStatistics, repositoryId, ns );
239 catch ( MetadataResolutionException e )
241 throw new MetadataRepositoryException( e.getMessage(), e );
245 public void deleteStatistics( MetadataRepository metadataRepository, String repositoryId )
246 throws MetadataRepositoryException
248 metadataRepository.removeMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
251 public List<RepositoryStatistics> getStatisticsInRange( MetadataRepository metadataRepository, String repositoryId,
252 Date startTime, Date endTime )
253 throws MetadataRepositoryException
255 List<RepositoryStatistics> results = new ArrayList<RepositoryStatistics>();
256 List<String> list = metadataRepository.getMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
257 Collections.sort( list, Collections.reverseOrder() );
258 for ( String name : list )
262 Date date = createNameFormat().parse( name );
263 if ( ( startTime == null || !date.before( startTime ) ) && ( endTime == null || !date.after(
266 RepositoryStatistics stats = (RepositoryStatistics) metadataRepository.getMetadataFacet(
267 repositoryId, RepositoryStatistics.FACET_ID, name );
268 results.add( stats );
271 catch ( ParseException e )
273 log.error( "Invalid scan result found in the metadata repository: " + e.getMessage() );
274 // continue and ignore this one
280 private static SimpleDateFormat createNameFormat()
282 SimpleDateFormat fmt = new SimpleDateFormat( RepositoryStatistics.SCAN_TIMESTAMP_FORMAT );
283 fmt.setTimeZone( UTC_TIME_ZONE );