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.model.maven2.MavenArtifactFacet;
24 import org.apache.archiva.metadata.repository.MetadataRepository;
25 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
26 import org.apache.archiva.metadata.repository.MetadataResolutionException;
27 import org.apache.commons.lang.time.StopWatch;
28 import org.apache.jackrabbit.commons.JcrUtils;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.stereotype.Service;
33 import java.text.ParseException;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.List;
42 import java.util.TimeZone;
43 import javax.jcr.Node;
44 import javax.jcr.RepositoryException;
45 import javax.jcr.Session;
46 import javax.jcr.query.Query;
47 import javax.jcr.query.QueryManager;
48 import javax.jcr.query.QueryResult;
49 import javax.jcr.query.Row;
54 @Service("repositoryStatisticsManager#default")
55 public class DefaultRepositoryStatisticsManager
56 implements RepositoryStatisticsManager
58 private static final Logger log = LoggerFactory.getLogger( DefaultRepositoryStatisticsManager.class );
60 private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" );
62 public boolean hasStatistics( MetadataRepository metadataRepository, String repositoryId )
63 throws MetadataRepositoryException
65 return metadataRepository.hasMetadataFacet( repositoryId, RepositoryStatistics.FACET_ID );
68 public RepositoryStatistics getLastStatistics( MetadataRepository metadataRepository, String repositoryId )
69 throws MetadataRepositoryException
71 StopWatch stopWatch = new StopWatch();
73 // TODO: consider a more efficient implementation that directly gets the last one from the content repository
74 List<String> scans = metadataRepository.getMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
79 Collections.sort( scans );
80 if ( !scans.isEmpty() )
82 String name = scans.get( scans.size() - 1 );
83 RepositoryStatistics repositoryStatistics =
84 (RepositoryStatistics) metadataRepository.getMetadataFacet( repositoryId, RepositoryStatistics.FACET_ID,
87 log.debug( "time to find last RepositoryStatistics: {} ms", stopWatch.getTime() );
88 return repositoryStatistics;
96 private void walkRepository( MetadataRepository metadataRepository, RepositoryStatistics stats, String repositoryId,
98 throws MetadataResolutionException
100 for ( String namespace : metadataRepository.getNamespaces( repositoryId, ns ) )
102 walkRepository( metadataRepository, stats, repositoryId, ns + "." + namespace );
105 Collection<String> projects = metadataRepository.getProjects( repositoryId, ns );
106 if ( !projects.isEmpty() )
108 stats.setTotalGroupCount( stats.getTotalGroupCount() + 1 );
109 stats.setTotalProjectCount( stats.getTotalProjectCount() + projects.size() );
111 for ( String project : projects )
113 for ( String version : metadataRepository.getProjectVersions( repositoryId, ns, project ) )
115 for ( ArtifactMetadata artifact : metadataRepository.getArtifacts( repositoryId, ns, project,
118 stats.setTotalArtifactCount( stats.getTotalArtifactCount() + 1 );
119 stats.setTotalArtifactFileSize( stats.getTotalArtifactFileSize() + artifact.getSize() );
121 MavenArtifactFacet facet =
122 (MavenArtifactFacet) artifact.getFacet( MavenArtifactFacet.FACET_ID );
125 String type = facet.getType();
126 stats.setTotalCountForType( type, stats.getTotalCountForType( type ) + 1 );
134 public void addStatisticsAfterScan( MetadataRepository metadataRepository, String repositoryId, Date startTime,
135 Date endTime, long totalFiles, long newFiles )
136 throws MetadataRepositoryException
138 RepositoryStatistics repositoryStatistics = new RepositoryStatistics();
139 repositoryStatistics.setRepositoryId( repositoryId );
140 repositoryStatistics.setScanStartTime( startTime );
141 repositoryStatistics.setScanEndTime( endTime );
142 repositoryStatistics.setTotalFileCount( totalFiles );
143 repositoryStatistics.setNewFileCount( newFiles );
146 // In the future, instead of being tied to a scan we might want to record information in the fly based on
147 // events that are occurring. Even without these totals we could query much of the information on demand based
148 // on information from the metadata content repository. In the mean time, we lock information in at scan time.
149 // Note that if new types are later discoverable due to a code change or new plugin, historical stats will not
150 // be updated and the repository will need to be rescanned.
152 long startGather = System.currentTimeMillis();
154 if ( metadataRepository.canObtainAccess( Session.class ) )
156 // TODO: this is currently very raw and susceptible to changes in content structure. Should we instead
157 // depend directly on the plugin and interrogate the JCR repository's knowledge of the structure?
158 populateStatisticsFromJcr( (Session) metadataRepository.obtainAccess( Session.class ), repositoryId,
159 repositoryStatistics );
164 // if the file repository is used more permanently, we may seek a more efficient mechanism - e.g. we could
165 // build an index, or store the aggregate information and update it on the fly. We can perhaps even walk
166 // but retrieve less information to speed it up. In the mean time, we walk the repository using the
168 populateStatisticsFromRepositoryWalk( metadataRepository, repositoryId, repositoryStatistics );
171 log.info( "Gathering statistics executed in " + ( System.currentTimeMillis() - startGather ) + "ms" );
173 metadataRepository.addMetadataFacet( repositoryId, repositoryStatistics );
176 private void populateStatisticsFromJcr( Session session, String repositoryId,
177 RepositoryStatistics repositoryStatistics )
178 throws MetadataRepositoryException
180 // TODO: these may be best as running totals, maintained by observations on the properties in JCR
184 QueryManager queryManager = session.getWorkspace().getQueryManager();
186 // TODO: JCR-SQL2 query will not complete on a large repo in Jackrabbit 2.2.0 - see JCR-2835
187 // Using the JCR-SQL2 variants gives
188 // "org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024"
189 // String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])";
190 // Query query = queryManager.createQuery( "SELECT size FROM [archiva:artifact] " + whereClause,
192 String whereClause = "WHERE jcr:path LIKE '/repositories/" + repositoryId + "/content/%'";
193 Query query = queryManager.createQuery( "SELECT size FROM archiva:artifact " + whereClause, Query.SQL );
195 QueryResult queryResult = query.execute();
197 Map<String, Integer> totalByType = new HashMap<String, Integer>();
198 long totalSize = 0, totalArtifacts = 0;
199 for ( Row row : JcrUtils.getRows( queryResult ) )
201 Node n = row.getNode();
202 totalSize += row.getValue( "size" ).getLong();
205 if ( n.hasNode( MavenArtifactFacet.FACET_ID ) )
207 Node facetNode = n.getNode( MavenArtifactFacet.FACET_ID );
208 type = facetNode.getProperty( "type" ).getString();
214 Integer prev = totalByType.get( type );
215 totalByType.put( type, prev != null ? prev + 1 : 1 );
220 repositoryStatistics.setTotalArtifactCount( totalArtifacts );
221 repositoryStatistics.setTotalArtifactFileSize( totalSize );
222 for ( Map.Entry<String, Integer> entry : totalByType.entrySet() )
224 repositoryStatistics.setTotalCountForType( entry.getKey(), entry.getValue() );
227 // The query ordering is a trick to ensure that the size is correct, otherwise due to lazy init it will be -1
228 // query = queryManager.createQuery( "SELECT * FROM [archiva:project] " + whereClause, Query.JCR_SQL2 );
229 query = queryManager.createQuery( "SELECT * FROM archiva:project " + whereClause + " ORDER BY jcr:score",
231 repositoryStatistics.setTotalProjectCount( query.execute().getRows().getSize() );
233 // query = queryManager.createQuery(
234 // "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL", Query.JCR_SQL2 );
235 query = queryManager.createQuery(
236 "SELECT * FROM archiva:namespace " + whereClause + " AND namespace IS NOT NULL ORDER BY jcr:score",
238 repositoryStatistics.setTotalGroupCount( query.execute().getRows().getSize() );
240 catch ( RepositoryException e )
242 throw new MetadataRepositoryException( e.getMessage(), e );
246 private void populateStatisticsFromRepositoryWalk( MetadataRepository metadataRepository, String repositoryId,
247 RepositoryStatistics repositoryStatistics )
248 throws MetadataRepositoryException
252 for ( String ns : metadataRepository.getRootNamespaces( repositoryId ) )
254 walkRepository( metadataRepository, repositoryStatistics, repositoryId, ns );
257 catch ( MetadataResolutionException e )
259 throw new MetadataRepositoryException( e.getMessage(), e );
263 public void deleteStatistics( MetadataRepository metadataRepository, String repositoryId )
264 throws MetadataRepositoryException
266 metadataRepository.removeMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
269 public List<RepositoryStatistics> getStatisticsInRange( MetadataRepository metadataRepository, String repositoryId,
270 Date startTime, Date endTime )
271 throws MetadataRepositoryException
273 List<RepositoryStatistics> results = new ArrayList<RepositoryStatistics>();
274 List<String> list = metadataRepository.getMetadataFacets( repositoryId, RepositoryStatistics.FACET_ID );
275 Collections.sort( list, Collections.reverseOrder() );
276 for ( String name : list )
280 Date date = createNameFormat().parse( name );
281 if ( ( startTime == null || !date.before( startTime ) ) && ( endTime == null || !date.after(
284 RepositoryStatistics stats =
285 (RepositoryStatistics) metadataRepository.getMetadataFacet( repositoryId,
286 RepositoryStatistics.FACET_ID,
288 results.add( stats );
291 catch ( ParseException e )
293 log.error( "Invalid scan result found in the metadata repository: " + e.getMessage() );
294 // continue and ignore this one
300 private static SimpleDateFormat createNameFormat()
302 SimpleDateFormat fmt = new SimpleDateFormat( RepositoryStatistics.SCAN_TIMESTAMP_FORMAT );
303 fmt.setTimeZone( UTC_TIME_ZONE );