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;
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 );
70 Collections.sort( scans );
71 if ( !scans.isEmpty() )
73 String name = scans.get( scans.size() - 1 );
74 return (RepositoryStatistics) metadataRepository.getMetadataFacet( repositoryId,
75 RepositoryStatistics.FACET_ID, name );
83 private void walkRepository( MetadataRepository metadataRepository, RepositoryStatistics stats, String repositoryId,
85 throws MetadataResolutionException
87 for ( String namespace : metadataRepository.getNamespaces( repositoryId, ns ) )
89 walkRepository( metadataRepository, stats, repositoryId, ns + "." + namespace );
92 Collection<String> projects = metadataRepository.getProjects( repositoryId, ns );
93 if ( !projects.isEmpty() )
95 stats.setTotalGroupCount( stats.getTotalGroupCount() + 1 );
96 stats.setTotalProjectCount( stats.getTotalProjectCount() + projects.size() );
98 for ( String project : projects )
100 for ( String version : metadataRepository.getProjectVersions( repositoryId, ns, project ) )
102 for ( ArtifactMetadata artifact : metadataRepository.getArtifacts( repositoryId, ns, project,
105 stats.setTotalArtifactCount( stats.getTotalArtifactCount() + 1 );
106 stats.setTotalArtifactFileSize( stats.getTotalArtifactFileSize() + artifact.getSize() );
108 MavenArtifactFacet facet = (MavenArtifactFacet) artifact.getFacet(
109 MavenArtifactFacet.FACET_ID );
112 String type = facet.getType();
113 stats.setTotalCountForType( type, stats.getTotalCountForType( type ) + 1 );
121 public void addStatisticsAfterScan( MetadataRepository metadataRepository, String repositoryId, Date startTime,
122 Date endTime, long totalFiles, long newFiles )
123 throws MetadataRepositoryException
125 RepositoryStatistics repositoryStatistics = new RepositoryStatistics();
126 repositoryStatistics.setScanStartTime( startTime );
127 repositoryStatistics.setScanEndTime( endTime );
128 repositoryStatistics.setTotalFileCount( totalFiles );
129 repositoryStatistics.setNewFileCount( newFiles );
132 // In the future, instead of being tied to a scan we might want to record information in the fly based on
133 // events that are occurring. Even without these totals we could query much of the information on demand based
134 // on information from the metadata content repository. In the mean time, we lock information in at scan time.
135 // Note that if new types are later discoverable due to a code change or new plugin, historical stats will not
136 // be updated and the repository will need to be rescanned.
138 long startGather = System.currentTimeMillis();
140 if ( metadataRepository.canObtainAccess( Session.class ) )
142 // TODO: this is currently very raw and susceptible to changes in content structure. Should we instead
143 // depend directly on the plugin and interrogate the JCR repository's knowledge of the structure?
144 populateStatisticsFromJcr( (Session) metadataRepository.obtainAccess( Session.class ), repositoryId,
145 repositoryStatistics );
150 // if the file repository is used more permanently, we may seek a more efficient mechanism - e.g. we could
151 // build an index, or store the aggregate information and update it on the fly. We can perhaps even walk
152 // but retrieve less information to speed it up. In the mean time, we walk the repository using the
154 populateStatisticsFromRepositoryWalk( metadataRepository, repositoryId, repositoryStatistics );
157 log.info( "Gathering statistics executed in " + ( System.currentTimeMillis() - startGather ) + "ms" );
159 metadataRepository.addMetadataFacet( repositoryId, repositoryStatistics );
162 private void populateStatisticsFromJcr( Session session, String repositoryId,
163 RepositoryStatistics repositoryStatistics )
164 throws MetadataRepositoryException
166 // TODO: these may be best as running totals, maintained by observations on the properties in JCR
170 QueryManager queryManager = session.getWorkspace().getQueryManager();
172 // TODO: JCR-SQL2 query will not complete on a large repo in Jackrabbit 2.2.0 - see JCR-2835
173 // Using the JCR-SQL2 variants gives
174 // "org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024"
175 // String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])";
176 // Query query = queryManager.createQuery( "SELECT size FROM [archiva:artifact] " + whereClause,
178 String whereClause = "WHERE jcr:path LIKE '/repositories/" + repositoryId + "/content/%'";
179 Query query = queryManager.createQuery( "SELECT size FROM archiva:artifact " + whereClause, Query.SQL );
181 QueryResult queryResult = query.execute();
183 Map<String, Integer> totalByType = new HashMap<String, Integer>();
184 long totalSize = 0, totalArtifacts = 0;
185 for ( Row row : JcrUtils.getRows( queryResult ) )
187 Node n = row.getNode();
188 totalSize += row.getValue( "size" ).getLong();
191 if ( n.hasNode( MavenArtifactFacet.FACET_ID ) )
193 Node facetNode = n.getNode( MavenArtifactFacet.FACET_ID );
194 type = facetNode.getProperty( "type" ).getString();
200 Integer prev = totalByType.get( type );
201 totalByType.put( type, prev != null ? prev + 1 : 1 );
206 repositoryStatistics.setTotalArtifactCount( totalArtifacts );
207 repositoryStatistics.setTotalArtifactFileSize( totalSize );
208 for ( Map.Entry<String, Integer> entry : totalByType.entrySet() )
210 repositoryStatistics.setTotalCountForType( entry.getKey(), entry.getValue() );
213 // The query ordering is a trick to ensure that the size is correct, otherwise due to lazy init it will be -1
214 // query = queryManager.createQuery( "SELECT * FROM [archiva:project] " + whereClause, Query.JCR_SQL2 );
215 query = queryManager.createQuery( "SELECT * FROM archiva:project " + whereClause + " ORDER BY jcr:score",
217 repositoryStatistics.setTotalProjectCount( query.execute().getRows().getSize() );
219 // query = queryManager.createQuery(
220 // "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL", Query.JCR_SQL2 );
221 query = queryManager.createQuery(
222 "SELECT * FROM archiva:namespace " + whereClause + " AND namespace IS NOT NULL ORDER BY jcr:score",
224 repositoryStatistics.setTotalGroupCount( query.execute().getRows().getSize() );
226 catch ( RepositoryException e )
228 throw new MetadataRepositoryException( e.getMessage(), e );
232 private void populateStatisticsFromRepositoryWalk( MetadataRepository metadataRepository, String repositoryId,
233 RepositoryStatistics repositoryStatistics )
234 throws MetadataRepositoryException
238 for ( String ns : metadataRepository.getRootNamespaces( repositoryId ) )
240 walkRepository( metadataRepository, repositoryStatistics, repositoryId, ns );
243 catch ( MetadataResolutionException e )
245 throw new MetadataRepositoryException( e.getMessage(), e );
249 public void deleteStatistics( MetadataRepository metadataRepository, String repositoryId )
250 throws MetadataRepositoryException
252 metadataRepository.removeMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
255 public List<RepositoryStatistics> getStatisticsInRange( MetadataRepository metadataRepository, String repositoryId,
256 Date startTime, Date endTime )
257 throws MetadataRepositoryException
259 List<RepositoryStatistics> results = new ArrayList<RepositoryStatistics>();
260 List<String> list = metadataRepository.getMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
261 Collections.sort( list, Collections.reverseOrder() );
262 for ( String name : list )
266 Date date = createNameFormat().parse( name );
267 if ( ( startTime == null || !date.before( startTime ) ) && ( endTime == null || !date.after(
270 RepositoryStatistics stats = (RepositoryStatistics) metadataRepository.getMetadataFacet(
271 repositoryId, RepositoryStatistics.FACET_ID, name );
272 results.add( stats );
275 catch ( ParseException e )
277 log.error( "Invalid scan result found in the metadata repository: " + e.getMessage() );
278 // continue and ignore this one
284 private static SimpleDateFormat createNameFormat()
286 SimpleDateFormat fmt = new SimpleDateFormat( RepositoryStatistics.SCAN_TIMESTAMP_FORMAT );
287 fmt.setTimeZone( UTC_TIME_ZONE );