REPO-3007: This is a squash commit containing scheduling and clustering commits

* Add job cron expression and unique id to HBBaseDataCollector
* Remove HeartBeat class and move its responsibilities to HBDataCollectorServiceImpl
* Refactor HBDataCollectorServiceImpl
* Update collector bean definitions with cron expression
* Add job locking functionality
* Refactor tests to work with new code changes

Squashed commit of the following:

commit 522a8c07b65aa0170387d7cea8b1a89230e019ed
Author: Erik Knizat <erik.knizat@alfresco.com>
Date:   Fri Nov 17 15:22:48 2017 +0000

    Cleaned up code:
    * HBDataCollectorServiceImpl - improved logic so that collectors which fail to schedule job do not get registered
    * HBDataCollectorServiceImpl - clean up code
    * HBDataCollectorServiceImplTest - Revrite old test to work with new changed
    * heartbeat-context.xml - add register method to the base collector template
    * Minor comment updates

commit d75b920a9172b3e53d901d1abbf33bada9419c4d
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Nov 6 20:17:30 2017 +0000

    REPO-3007 bug in usage system collector

commit 2f25ec04868569eab4de34bd804ee9fb3490f9c2
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Nov 6 20:15:41 2017 +0000

    Revert "REPO-3007 try to fix context load errors"

    This reverts commit 30d0f70609e1c774b7989c18cd76ad87ccf239ed.

commit 30d0f70609e1c774b7989c18cd76ad87ccf239ed
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Nov 6 19:57:14 2017 +0000

    REPO-3007 try to fix context load errors

commit 615e72bfdb6d08f1d82cfe581d0a222932eec483
Merge: c128561fc e357becce
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Nov 6 19:30:41 2017 +0000

    Merge branch 'develop' into feature/REPO-2627_Clust-Test

commit c128561fc977979dda5c2d397da9b05993e0db68
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Nov 6 19:13:47 2017 +0000

    REPO-3007 reduced time for TTL and TTL_OFFSET

commit 02184034908775ea835d7022478a9c7b6a8dc66a
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Mon Nov 6 18:47:06 2017 +0000

    REPO-3007 additional life time of the job for keeping the lock longer. Reduced additional work.

commit 63332cdf08d8819518bbe6a3b80e988e2c8bc554
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Mon Nov 6 18:42:22 2017 +0000

    REPO-3007 additional life time of the job for keeping the lock longer. Reduced additional work.

commit 7333ae7f448b5fe3601a99d25c814c8a58ca0e92
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Mon Nov 6 18:12:47 2017 +0000

    REPO-3007 additional life time of the job for keeping the lock longer. Reduced additional work.

commit e43c3cff787d6985cbf4d957dfcf7cf27e4aa495
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Mon Nov 6 18:05:51 2017 +0000

    REPO-3007 additional life time of the job for keeping the lock longer. Reduced additional work.

commit 5f8d19fc05b5ef4855c89aab86e2e786fcc8b0d9
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Wed Nov 1 15:37:27 2017 +0000

    REPO-3007 spell check.

commit e7c8aa3f96939e29cd9ac6b962ad5a5d848269e3
Merge: 2bbcba39f b0f057f0d
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Tue Oct 31 14:47:23 2017 +0000

    Merge branch 'develop' into feature/REPO-2627_Clust-Test

commit 2bbcba39faaa4ba97d9ec81a691256c2292e5f8d
Author: alfresco-build <build@alfresco.com>
Date:   Tue Oct 31 14:03:04 2017 +0000

    [maven-release-plugin] prepare for next development iteration

commit 1e74e1dc6652daa5964d2c8cf1b06ef32147e15f
Author: alfresco-build <build@alfresco.com>
Date:   Tue Oct 31 14:02:57 2017 +0000

    [maven-release-plugin] prepare release alfresco-repository-6.9-REPO-2627_Clust-Test-1

commit fdf8b40dc6ad00433c3601782864c5cdaec63706
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Tue Oct 31 13:45:02 2017 +0000

    REPO-3007 Some syntax clean ups

commit ca1b8a2b6019b1a21c84eb949bbe57ae9bbdef9c
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Tue Oct 31 11:59:48 2017 +0000

    REPO-3007 Bring back the concrete collector tests. And little refactoring of them.

commit 73fbafc4732f06e0c48d0fa0e6225ba26265d75c
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Oct 30 16:49:21 2017 +0000

    REPO-3007 Implemented each data collection in his own data collector. Removed some unnecessary tests.

commit e41d3afd7b414aae921599aa193d6fbd167ab35a
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Oct 30 16:08:00 2017 +0000

    REPO-3007 Implemented each data collection in his own data collector. Removed some unnecessary tests.

commit f13ec13a5b4dc6fb490fcc93c06a13d0b0348df5
Author: Martin Müller <martin.muller@alfresco.com>
Date:   Mon Oct 30 11:54:33 2017 +0000

    REPO-3007 Implemented each data collection in his own data collector. Removed some unnecessary tests.

commit 37115ba39a73b9ea4fc7e5d562c83bb792b11c9b
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 18:00:44 2017 +0100

    REPO-3007 Remove old HeartBeat.java references

commit cd6af905914119bc4f8526500303d29b4759a6e2
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 17:50:39 2017 +0100

    REPO-3007 Reduce mocking objects

commit 4c5b82a50f1d42b35162dfcf31a21a303fddbc6b
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 17:38:09 2017 +0100

    REPO-3007 Improve tests for hb default enabled

commit 7abd1467de33b72f304c26bdf18f3769ef9632b1
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 14:22:53 2017 +0100

    REPO-3007 Delete old HeartBeat files

commit 301ab0525f1a146223f21aaba0122a70384c6342
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 14:21:58 2017 +0100

    Delete old HeartBeat files

commit c3a84596d7f809aa7ebb7789ae98f953f44b4d36
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 14:13:50 2017 +0100

    REPO-3007 Some CollectorServiceImplTests

commit e7071811e9e0276861c374248215fdde94285623
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 14:11:39 2017 +0100

    Some CollectorServiceImplTests

commit ac5aa8e9a295f250920f8ebbe2a5ad97ba4270eb
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 13:26:25 2017 +0100

    Continued refactoring. Get some tests running

commit d5ef15fe0080cebb586360f10a21eef94ba63d51
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 12:45:05 2017 +0100

    Continued refactoring. Get some tests running

commit f7ae53236daaa5e48dbd829f5f1cd984c2c06e8c
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Fri Oct 27 12:24:36 2017 +0100

    Continued refactoring. Get some tests running

commit 7c200d0f7633efe7cda4a68e7ef279e85b7e5d99
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 17:32:37 2017 +0100

    REPO-3007 implemented dynamic lock with JobLockCallBack

commit 5def15950b87b9df4136fedff447d4f54aa87736
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 17:28:09 2017 +0100

    REPO-3007 implemented dynamic lock with JobLockCallBack

commit bdbbe49a081661373a2114b7cf2cb415d4383afd
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 17:25:28 2017 +0100

    REPO-3007 implemented dynamic lock with JobLockCallBack

commit a5d1f45f28a0ae228a8c9bf2f8a4171413a692e7
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 16:07:46 2017 +0100

    Update heartbeat-context.xml

    We don't need the licenseService here

commit c2efe1bd325f89f0a4c0ebf95b5a0e99baa249f4
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 16:07:03 2017 +0100

    Update HBDataCollectorServiceImpl.java

    We don't need the licenseService here

commit 8f1bd298e1f03f0a45be31b28f14289ad1684c9f
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 14:41:53 2017 +0100

    REPO-3007 the collectors are unique

commit 2f8ad8fff384c1f525759be59ab8c1ba5b05b5f2
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 14:32:02 2017 +0100

    REPO-3007 starting refactoring

commit 5a3e7f2d25d9c20017f12b8fec26198a4f7d705b
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 14:26:32 2017 +0100

    REPO-3007 starting refactoring

commit ed111b77f6f311be967929ba09025d6bb4fb9ab8
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Thu Oct 26 14:16:49 2017 +0100

    REPO-3007 starting refactoring

commit 8e2497dc1f05f71451736b8366b3be1f420bf8a6
Author: alfresco-build <build@alfresco.com>
Date:   Thu Oct 26 11:26:19 2017 +0100

    [maven-release-plugin] prepare for next development iteration

commit e15f02390fc09ab7baaad1e186ed35e27e1f7445
Author: alfresco-build <build@alfresco.com>
Date:   Thu Oct 26 11:26:12 2017 +0100

    [maven-release-plugin] prepare release alfresco-repository-6.9-REPO-2627_Clust-Test

commit 35eed74bd869ee8a6a9f4a30c86b9f7cd4bd331b
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Wed Oct 25 13:41:47 2017 +0100

    REPO-2627 Implemented job locking for hb collectors and added unit cluster test

commit b67fc751cd11a9a73fee6873663216bbd05422e1
Author: Martin Muller <martin.muller@alfresco.com>
Date:   Wed Oct 25 13:22:05 2017 +0100

    REPO-2627 Implemented job locking for hb collectors and added unit cluster test
This commit is contained in:
Erik Knizat
2017-11-17 16:12:24 +00:00
parent 865b5f8153
commit 310b9d88f3
25 changed files with 1532 additions and 874 deletions

View File

@@ -34,7 +34,7 @@ import org.apache.commons.logging.LogFactory;
import java.util.*;
/**
* This class collects authorities data for HeartBeat.
* This class collects authorities data for HBDataCollectorService.
* <br>
* <b>Collector ID:</b> acs.repository.usage.authorities
* <br>
@@ -54,6 +54,11 @@ public class AuthoritiesDataCollector extends HBBaseDataCollector
/** The authority service. */
private AuthorityService authorityService;
public AuthoritiesDataCollector(String collectorId)
{
super(collectorId);
}
public void setCurrentRepoDescriptorDAO(DescriptorDAO currentRepoDescriptorDAO)
{
this.currentRepoDescriptorDAO = currentRepoDescriptorDAO;
@@ -67,11 +72,19 @@ public class AuthoritiesDataCollector extends HBBaseDataCollector
@Override
public List<HBData> collectData()
{
if(authorityService == null)
{
logger.debug("Couldn't collect data because authority service is null");
return null;
}
if(currentRepoDescriptorDAO == null)
{
logger.debug("Couldn't collect data because repository descriptor is null");
return null;
}
List<HBData> collectedData = new LinkedList<>();
// Collect repository usage (authorities) data
this.logger.debug("Preparing repository usage (authorities) data...");
Map<String, Object> authoritiesUsageValues = new HashMap<>();
authoritiesUsageValues.put("numUsers", new Integer(this.authorityService.getAllAuthoritiesInZone(
AuthorityService.ZONE_APP_DEFAULT, AuthorityType.USER).size()));
@@ -79,10 +92,11 @@ public class AuthoritiesDataCollector extends HBBaseDataCollector
AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP).size()));
HBData authoritiesUsageData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
"acs.repository.usage.authorities",
"1.0",
this.getCollectorId(),
this.getCollectorVersion(),
new Date(),
authoritiesUsageValues);
List<HBData> collectedData = new LinkedList<>();
collectedData.add(authoritiesUsageData);
return collectedData;

View File

@@ -36,12 +36,48 @@ import org.alfresco.service.cmr.repository.HBDataCollectorService;
*
* @author eknizat
*/
public abstract class HBBaseDataCollector
{
private HBDataCollectorService hbDataCollectorService;
public abstract class HBBaseDataCollector {
private String collectorId;
private String collectorVersion;
private String cronExpression;
/**
* This method will register this collector with the provided {@link HBDataCollectorService}
* The collector service managing this collector.
*/
private HBDataCollectorService hbDataCollectorService;
public HBBaseDataCollector(String collectorId)
{
this.collectorId = collectorId;
}
public String getCollectorId()
{
return collectorId;
}
public void setCollectorVersion(String collectorVersion)
{
this.collectorVersion = collectorVersion;
}
public String getCollectorVersion()
{
return this.collectorVersion;
}
public void setCronExpression(String cronExpression)
{
this.cronExpression = cronExpression;
}
public String getCronExpression()
{
return this.cronExpression;
}
/**
* This method is called by Spring at initialisation and will register this collector with the provided {@link HBDataCollectorService}
*/
public void register()
{
@@ -55,7 +91,7 @@ public abstract class HBBaseDataCollector
/**
* This method returns data to be collected.
* @return List of data wrapped in {@link HBData}
* @return List of {@link HBData}
*/
public abstract List<HBData> collectData();
}

View File

@@ -25,16 +25,20 @@
*/
package org.alfresco.heartbeat;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.heartbeat.datasender.HBDataSenderService;
import org.alfresco.repo.lock.JobLockService;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.license.LicenseDescriptor;
import org.alfresco.service.license.LicenseService.LicenseChangeHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;
public class HBDataCollectorServiceImpl implements HBDataCollectorService
public class HBDataCollectorServiceImpl implements HBDataCollectorService, LicenseChangeHandler
{
/** The logger. */
private static final Log logger = LogFactory.getLog(HBDataCollectorServiceImpl.class);
@@ -44,18 +48,30 @@ public class HBDataCollectorServiceImpl implements HBDataCollectorService
/** The service responsible for sending the collected data */
private HBDataSenderService hbDataSenderService;
private JobLockService jobLockService;
/** The default enable state */
private final boolean defaultHbState;
private Scheduler scheduler;
/** schedule set for all collectors if testMode is on */
private boolean testMode = false;
private final String testCronExpression = "0 0/1 * * * ?";
/** Current enabled state */
private boolean enabled = false;
/**
*
* @param defaultHeartBeatState the default enabled state of heartbeat
* @param defaultHeartBeatState
* the default enabled state of heartbeat
*
*/
public HBDataCollectorServiceImpl (boolean defaultHeartBeatState)
{
this.defaultHbState = defaultHeartBeatState;
this.enabled = defaultHeartBeatState;
}
public void setHbDataSenderService(HBDataSenderService hbDataSenderService)
@@ -63,38 +79,69 @@ public class HBDataCollectorServiceImpl implements HBDataCollectorService
this.hbDataSenderService = hbDataSenderService;
}
public void setJobLockService(JobLockService jobLockService)
{
this.jobLockService = jobLockService;
}
public void setScheduler(Scheduler scheduler)
{
this.scheduler = scheduler;
}
public boolean isEnabled()
{
return this.enabled;
}
public void setTestMode(boolean testMode)
{
this.testMode = testMode;
}
/**
*
* Register data collector with this service.
* The registered collectors will be called to provide heartbeat data.
* Register data collector with this service and start the schedule.
* The registered collector will be called to provide heartbeat data at the scheduled interval.
* Each collector registered via this method must have a unique collector id.
*
* @param collector collector to register
*/
@Override
public void registerCollector(HBBaseDataCollector collector)
public void registerCollector(final HBBaseDataCollector collector)
{
this.collectors.add(collector);
}
/**
* Collects and sends data for all registered collectors using the provided sender service.
*/
@Override
public void collectAndSendData()
{
for (HBBaseDataCollector collector : collectors)
// Check collector ID is not null
if (collector.getCollectorId() == null)
{
List<HBData> data = collector.collectData();
try
logger.error("HeartBeat did not registered collector, collector ID must not be null.");
return;
}
// Check collector with the same ID does't already exist
for (HBBaseDataCollector col : collectors)
{
if(collector.getCollectorId().equals(col.getCollectorId()))
{
hbDataSenderService.sendData(data);
logger.error("HeartBeat did not registered collector, ID must be unique. ID: " + collector.getCollectorId());
return;
}
catch (Exception e)
}
// Schedule collector job and add collector to list of registered collectors
try
{
scheduleCollector(collector);
collectors.add(collector);
if (logger.isDebugEnabled())
{
// Log exception
logger.error(e);
logger.debug("HeartBeat registered collector: " + collectorInfo(collector));
}
}
catch (Exception e)
{
logger.error("HeartBeat did not registered collector: " + collectorInfo(collector), e);
}
}
@Override
@@ -103,10 +150,120 @@ public class HBDataCollectorServiceImpl implements HBDataCollectorService
return defaultHbState;
}
@Override
public synchronized void enabled(boolean enabled)
/**
* Start or stop the HertBeat jobs for all registered collectors depending on whether the heartbeat is enabled or not
*/
private synchronized void scheduleCollector(final HBBaseDataCollector collector) throws ParseException, SchedulerException
{
this.hbDataSenderService.enable(enabled);
final String jobName = "heartbeat-" + collector.getCollectorId();
final String triggerName = jobName + "-Trigger";
if (this.enabled)
{
scheduleJob(jobName, triggerName, collector);
}
else
{
unscheduleJob(triggerName, collector);
}
}
private void scheduleJob(final String jobName, final String triggerName, final HBBaseDataCollector collector) throws ParseException, SchedulerException
{
final JobDetail jobDetail = new JobDetail(jobName, Scheduler.DEFAULT_GROUP, HeartBeatJob.class);
final String cronExpression = testMode ? testCronExpression : collector.getCronExpression();
jobDetail.getJobDataMap().put("collector", collector);
jobDetail.getJobDataMap().put("hbDataSenderService", hbDataSenderService);
jobDetail.getJobDataMap().put("jobLockService", jobLockService);
// Ensure the job wasn't already scheduled in an earlier retry of this transaction
scheduler.unscheduleJob(triggerName, Scheduler.DEFAULT_GROUP);
// Schedule job
final CronTrigger cronTrigger = new CronTrigger(triggerName , Scheduler.DEFAULT_GROUP, cronExpression);
scheduler.scheduleJob(jobDetail, cronTrigger);
if (logger.isDebugEnabled())
{
logger.debug("HeartBeat job scheduled for collector: " + collectorInfo(collector));
}
}
private void unscheduleJob(final String triggerName, final HBBaseDataCollector collector) throws SchedulerException
{
scheduler.unscheduleJob(triggerName, Scheduler.DEFAULT_GROUP);
if (logger.isDebugEnabled())
{
logger.debug("HeartBeat unscheduled job for collector: " + collectorInfo(collector));
}
}
/**
* Listens for license changes. If a license is change or removed, the heartbeat job is rescheduled.
*/
@Override
public synchronized void onLicenseChange(final LicenseDescriptor licenseDescriptor)
{
final boolean newEnabled = !licenseDescriptor.isHeartBeatDisabled();
if (newEnabled != this.enabled)
{
if (logger.isDebugEnabled())
{
logger.debug("HeartBeat enabled state change. Enabled=" + newEnabled);
}
enable(newEnabled);
restartAllCollectorSchedules();
}
}
/**
* License load failure resets the heartbeat back to the default state
*/
@Override
public synchronized void onLicenseFail()
{
final boolean newEnabled = isEnabledByDefault();
if (newEnabled != this.enabled)
{
if (logger.isDebugEnabled())
{
logger.debug("HeartBeat enabled state change. Enabled=" + newEnabled);
}
enable(newEnabled);
restartAllCollectorSchedules();
}
}
private void restartAllCollectorSchedules()
{
for(HBBaseDataCollector collector : collectors)
{
try
{
scheduleCollector(collector);
}
catch (Exception e)
{
// Log and ignore
logger.error("HeartBeat failed to restart collector: " + collector.getCollectorId() ,e);
}
}
}
private void enable(boolean enable)
{
this.enabled = enable;
if (hbDataSenderService != null)
{
hbDataSenderService.enable(enable);
}
}
private String collectorInfo(HBBaseDataCollector collector)
{
return collector.getCollectorId() + " " + collector.getCollectorVersion();
}
}

View File

@@ -1,272 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import java.util.Date;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.license.LicenseDescriptor;
import org.alfresco.service.license.LicenseService;
import org.alfresco.service.license.LicenseService.LicenseChangeHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
/**
* This class communicates some very basic repository statistics to Alfresco on a regular basis.
* The class is responsible for scheduling the HeartBeat job and reacting to licence change events.
*
* @author dward, eknizat
*/
public class HeartBeat implements LicenseChangeHandler
{
/** The logger */
private static final Log logger = LogFactory.getLog(HeartBeat.class);
private LicenseService licenseService;
private Scheduler scheduler;
private boolean testMode = true;
private final String JOB_NAME = "heartbeat";
private HBDataCollectorService dataCollectorService;
/** Current enabled state */
private boolean enabled = false;
/**
* Initialises the heart beat service. Note that dependencies are intentionally 'pulled' rather than injected
* because we don't want these to be reconfigured.
*
* @param context
* the context
*/
public HeartBeat(final ApplicationContext context)
{
this(context, false);
}
/**
* Initialises the heart beat service, potentially in test mode. Note that dependencies are intentionally 'pulled'
* rather than injected because we don't want these to be reconfigured.
*
* -@param context
* the context
* -@param testMode
* are we running in test mode? If so we send data to local port 9999 rather than an alfresco server. We
* also use a special test encryption certificate and ping on a more frequent basis.
*/
public HeartBeat(final ApplicationContext context, final Boolean testMode)
{
if (logger.isDebugEnabled())
{
logger.debug("Initialising HeartBeat");
}
this.dataCollectorService = (HBDataCollectorService) context.getBean("hbDataCollectorService");
this.scheduler = (Scheduler) context.getBean("schedulerFactory");
this.testMode = testMode;
this.enabled = dataCollectorService.isEnabledByDefault();
try
{
LicenseService licenseService = null;
try
{
licenseService = (LicenseService) context.getBean("licenseService");
licenseService.registerOnLicenseChange(this);
}
catch (NoSuchBeanDefinitionException e)
{
logger.error("licenseService not found", e);
}
this.licenseService = licenseService;
// We force the job to be scheduled regardless of the potential state of the licenses
scheduleJob();
}
catch (final RuntimeException e)
{
throw e;
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
public synchronized boolean isEnabled()
{
return this.enabled;
}
/**
* Delegates data collection and sending to HBDataCollectorService.
*
*/
public void collectAndSendData()
{
this.dataCollectorService.collectAndSendData();
}
/**
* Listens for license changes. If a license is change or removed, the heartbeat job is rescheduled.
*/
public synchronized void onLicenseChange(LicenseDescriptor licenseDescriptor)
{
if (logger.isDebugEnabled())
{
logger.debug("Update license called");
}
boolean newEnabled = !licenseDescriptor.isHeartBeatDisabled();
if (newEnabled != this.enabled)
{
if (logger.isDebugEnabled())
{
logger.debug("State change of heartbeat");
}
this.enabled = newEnabled;
dataCollectorService.enabled(newEnabled);
try
{
scheduleJob();
}
catch (Exception e)
{
logger.error("Unable to schedule heart beat", e);
}
}
}
/**
* License load failure resets the heartbeat back to the default state
*/
@Override
public synchronized void onLicenseFail()
{
boolean newEnabled = dataCollectorService.isEnabledByDefault();
if (newEnabled != this.enabled)
{
if (logger.isDebugEnabled())
{
logger.debug("State change of heartbeat");
}
this.enabled = newEnabled;
dataCollectorService.enabled(newEnabled);
try
{
scheduleJob();
}
catch (Exception e)
{
logger.error("Unable to schedule heart beat", e);
}
}
}
/**
* Start or stop the hertbeat job depending on whether the heartbeat is enabled or not
* @throws SchedulerException
*/
private synchronized void scheduleJob() throws SchedulerException
{
// Schedule the heart beat to run regularly
final String triggerName = JOB_NAME + "Trigger";
if(this.enabled)
{
if (logger.isDebugEnabled())
{
logger.debug("heartbeat job scheduled");
}
final JobDetail jobDetail = new JobDetail(JOB_NAME, Scheduler.DEFAULT_GROUP, HeartBeatJob.class);
jobDetail.getJobDataMap().put("heartBeat", this);
// Ensure the job wasn't already scheduled in an earlier retry of this transaction
scheduler.unscheduleJob(triggerName, Scheduler.DEFAULT_GROUP);
final Trigger trigger = new SimpleTrigger(triggerName, Scheduler.DEFAULT_GROUP, new Date(), null,
//SimpleTrigger.REPEAT_INDEFINITELY, testMode ? 1000 : 4 * 60 * 60 * 1000);
SimpleTrigger.REPEAT_INDEFINITELY, testMode ? 1000 : 2 * 60 * 1000);
scheduler.scheduleJob(jobDetail, trigger);
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("heartbeat job unscheduled");
}
scheduler.unscheduleJob(triggerName, Scheduler.DEFAULT_GROUP);
}
}
/**
* The scheduler job responsible for triggering a heartbeat on a regular basis.
*/
public static class HeartBeatJob implements Job
{
public void execute(final JobExecutionContext jobexecutioncontext) throws JobExecutionException
{
final JobDataMap dataMap = jobexecutioncontext.getJobDetail().getJobDataMap();
final HeartBeat heartBeat = (HeartBeat) dataMap.get("heartBeat");
try
{
heartBeat.collectAndSendData();
}
catch (final Exception e)
{
if (logger.isDebugEnabled())
{
// Verbose logging
HeartBeat.logger.debug("Heartbeat job failure", e);
}
else
{
// Heartbeat errors are non-fatal and will show as single line warnings
HeartBeat.logger.warn(e.toString());
throw new JobExecutionException(e);
}
}
}
}
}

View File

@@ -0,0 +1,209 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.heartbeat.datasender.HBDataSenderService;
import org.alfresco.repo.lock.JobLockService;
import org.alfresco.repo.lock.LockAcquisitionException;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The scheduler job responsible for triggering a heartbeat on a regular basis.
*/
public class HeartBeatJob implements Job
{
/** The logger. */
private static final Log logger = LogFactory.getLog(HeartBeatJob.class);
/** Time to live 5 seconds */
private static final long LOCK_TTL = 5000L;
/** Additional 5 seconds for how much longer the log will be kept */
private static final long LOCK_TTL_OFFSET = 5000L;
public void execute(final JobExecutionContext jobexecutioncontext) throws JobExecutionException
{
final JobDataMap dataMap = jobexecutioncontext.getJobDetail().getJobDataMap();
final HBBaseDataCollector collector = (HBBaseDataCollector) dataMap.get("collector");
final HBDataSenderService hbDataSenderService = (HBDataSenderService) dataMap.get("hbDataSenderService");
final JobLockService jobLockService = (JobLockService) dataMap.get("jobLockService");
if(collector == null)
{
if (logger.isDebugEnabled())
{
logger.debug("Exit HeartBeatJob because there is no assigned HB collector");
}
return;
}
if(hbDataSenderService == null)
{
if (logger.isDebugEnabled())
{
logger.debug("Exit HeartBeatJob because there is no HBDataSenderService");
}
return;
}
if(jobLockService == null)
{
if (logger.isDebugEnabled())
{
logger.debug("Exit HeartBeatJob because there is no JobLockService");
}
return;
}
QName qName = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, collector.getCollectorId());
String lockToken = null;
LockCallback lockCallback = new LockCallback(qName);
try
{
// Get a dynamic lock
lockToken = acquireLock(lockCallback, qName, jobLockService);
collectAndSendDataLocked(collector, hbDataSenderService);
// after it finished we want to keep the lock for 30 seconds more
try
{
Thread.sleep(LOCK_TTL_OFFSET);
}
catch (InterruptedException e)
{
//
}
}
catch (LockAcquisitionException e)
{
if (logger.isDebugEnabled())
{
logger.debug("Skipping collect and send data (could not get lock): " + e.getMessage());
}
}
finally
{
releaseLock(lockCallback, lockToken, qName, jobLockService);
}
}
private void collectAndSendDataLocked(final HBBaseDataCollector collector, final HBDataSenderService hbDataSenderService) throws JobExecutionException
{
try
{
List<HBData> data = collector.collectData();
try
{
hbDataSenderService.sendData(data);
}
catch (Exception e)
{
logger.warn(e);
}
}
catch (final Exception e)
{
if (logger.isDebugEnabled())
{
// Verbose logging
logger.debug("Heartbeat job failure from collector: " + collector.getCollectorId(), e);
}
else
{
// Heartbeat errors are non-fatal and will show as single line warnings
logger.warn(e.toString());
throw new JobExecutionException(e);
}
}
}
private String acquireLock(JobLockService.JobLockRefreshCallback lockCallback, QName lockQname, JobLockService jobLockService)
{
// Get lock
String lockToken = jobLockService.getLock(lockQname, LOCK_TTL);
// Register the refresh callback which will keep the lock alive
jobLockService.refreshLock(lockToken, lockQname, LOCK_TTL, lockCallback);
if (logger.isDebugEnabled())
{
logger.debug("Lock acquired: " + lockQname + ": " + lockToken);
}
return lockToken;
}
private class LockCallback implements JobLockService.JobLockRefreshCallback
{
final AtomicBoolean running = new AtomicBoolean(true);
private QName lockQname;
public LockCallback(QName lockQname)
{
this.lockQname = lockQname;
}
@Override
public boolean isActive()
{
return running.get();
}
@Override
public void lockReleased()
{
running.set(false);
if (logger.isDebugEnabled())
{
logger.debug("Lock release notification: " + lockQname);
}
}
}
private void releaseLock(LockCallback lockCallback, String lockToken, QName lockQname, JobLockService jobLockService)
{
if (lockCallback != null)
{
lockCallback.running.set(false);
}
if (lockToken != null)
{
jobLockService.releaseLock(lockToken, lockQname);
if (logger.isDebugEnabled())
{
logger.debug("Lock released: " + lockQname + ": " + lockToken);
}
}
}
}

View File

@@ -0,0 +1,95 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.service.descriptor.Descriptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
public class InfoDataCollector extends HBBaseDataCollector
{
/** The logger. */
private static final Log logger = LogFactory.getLog(InfoDataCollector.class);
/** DAO for current repository descriptor. */
private DescriptorDAO currentRepoDescriptorDAO;
/** DAO for current descriptor. */
private DescriptorDAO serverDescriptorDAO;
public InfoDataCollector(String collectorId)
{
super(collectorId);
}
public void setCurrentRepoDescriptorDAO(DescriptorDAO currentRepoDescriptorDAO)
{
this.currentRepoDescriptorDAO = currentRepoDescriptorDAO;
}
public void setServerDescriptorDAO(DescriptorDAO serverDescriptorDAO)
{
this.serverDescriptorDAO = serverDescriptorDAO;
}
@Override
public List<HBData> collectData()
{
if(serverDescriptorDAO == null)
{
logger.debug("Couldn't collect data because server descriptor is null");
return null;
}
if(currentRepoDescriptorDAO == null)
{
logger.debug("Couldn't collect data because repository descriptor is null");
return null;
}
logger.debug("Preparing repository info data...");
final Descriptor serverDescriptor = this.serverDescriptorDAO.getDescriptor();
Map<String, Object> infoValues = new HashMap<>();
infoValues.put("repoName", serverDescriptor.getName());
infoValues.put("edition", serverDescriptor.getEdition());
infoValues.put("versionMajor", serverDescriptor.getVersionMajor());
infoValues.put("versionMinor", serverDescriptor.getVersionMinor());
infoValues.put("schema", new Integer(serverDescriptor.getSchema()));
HBData infoData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
this.getCollectorId(),
this.getCollectorVersion(),
new Date(),
infoValues);
List<HBData> collectedData = new LinkedList<>();
collectedData.add(infoData);
return collectedData;
}
}

View File

@@ -1,205 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.repo.dictionary.CustomModelsInfo;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.dictionary.CustomModelService;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class collects repository data for HeartBeat through multiple collector.
* <br>
* <b>Collector ID: </b> acs.repository.info
* <br>
* <b>Data points: </b> repoName, edition, versionMajor, versionMinor, schema
*
* <br>
* <b>Collector ID: </b> acs.repository.usage.system
* <br>
* <b>Data points: </b> memFree, memMax, memTotal
*
* <br>
* <b>Collector ID: </b> acs.repository.usage.model
* <br>
* <b>Data points: </b> numOfActiveModels, numOfActiveTypes, numOfActiveAspects
*
* @author eknizat
*/
public class RepositoryDataCollector extends HBBaseDataCollector
{
/** The logger. */
private static final Log logger = LogFactory.getLog(RepositoryDataCollector.class);
/**
* The parameters that we expect to remain static throughout the lifetime of the repository. There is no need to
* continuously update these.
*/
private Map<String, Object> staticParameters;
/** The transaction service. */
private TransactionService transactionService;
/** DAO for current repository descriptor. */
private DescriptorDAO currentRepoDescriptorDAO;
/** DAO for current descriptor. */
private DescriptorDAO serverDescriptorDAO;
/** Provides information about custom models */
private CustomModelService customModelService;
public void setCurrentRepoDescriptorDAO(DescriptorDAO currentRepoDescriptorDAO)
{
this.currentRepoDescriptorDAO = currentRepoDescriptorDAO;
}
public void setServerDescriptorDAO(DescriptorDAO serverDescriptorDAO)
{
this.serverDescriptorDAO = serverDescriptorDAO;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
public void setCustomModelService(CustomModelService customModelService)
{
this.customModelService = customModelService;
}
@Override
public List<HBData> collectData()
{
List<HBData> collectedData = new LinkedList<>();
RetryingTransactionHelper.RetryingTransactionCallback<Void> initCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
lazyInit();
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(initCallback, true);
// collect repository info data
logger.debug("Preparing repository info data...");
Map<String, Object> infoValues = new HashMap<>();
infoValues.put("repoName", this.staticParameters.get("repoName"));
infoValues.put("edition", this.staticParameters.get("edition"));
infoValues.put("versionMajor", this.staticParameters.get("versionMajor"));
infoValues.put("versionMinor", this.staticParameters.get("versionMinor"));
infoValues.put("schema", this.staticParameters.get("schema"));
HBData infoData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
"acs.repository.info",
"1.0",
new Date(),
infoValues);
collectedData.add(infoData);
// collect repository usage (system) data
logger.debug("Preparing repository usage (system) data...");
Runtime runtime = Runtime.getRuntime();
Map<String, Object> systemUsageValues = new HashMap<>();
systemUsageValues.put("memFree", runtime.freeMemory());
systemUsageValues.put("memMax", runtime.maxMemory());
systemUsageValues.put("memTotal", runtime.totalMemory());
HBData systemUsageData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
"acs.repository.usage.system",
"1.0",
new Date(),
systemUsageValues);
collectedData.add(systemUsageData);
// collect repository usage (model) data
logger.debug("Preparing repository usage (model) data...");
final CustomModelsInfo customModelsInfo = transactionService.getRetryingTransactionHelper().doInTransaction(
new RetryingTransactionHelper.RetryingTransactionCallback<CustomModelsInfo>()
{
public CustomModelsInfo execute()
{
return customModelService.getCustomModelsInfo();
}
}, true);
Map<String, Object> modelUsageValues = new HashMap<>();
modelUsageValues.put("numOfActiveModels", new Integer(customModelsInfo.getNumberOfActiveModels()));
modelUsageValues.put("numOfActiveTypes", new Integer(customModelsInfo.getNumberOfActiveTypes()));
modelUsageValues.put("numOfActiveAspects", new Integer(customModelsInfo.getNumberOfActiveAspects()));
HBData modelUsageData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
"acs.repository.usage.model",
"1.0",
new Date(),
modelUsageValues);
collectedData.add(modelUsageData);
return collectedData;
}
/**
* Initializes static parameters on first invocation. Avoid doing it on construction due to bootstrap dependencies
* (e.g. patch service must have run)
*
* @throws GeneralSecurityException
* @throws IOException
*/
private synchronized void lazyInit() throws GeneralSecurityException, IOException
{
if (this.staticParameters == null)
{
this.staticParameters = new TreeMap<String, Object>();
// Load up the static parameters
final Descriptor serverDescriptor = this.serverDescriptorDAO.getDescriptor();
this.staticParameters.put("repoName", serverDescriptor.getName());
this.staticParameters.put("edition", serverDescriptor.getEdition());
this.staticParameters.put("versionMajor", serverDescriptor.getVersionMajor());
this.staticParameters.put("versionMinor", serverDescriptor.getVersionMinor());
this.staticParameters.put("schema", new Integer(serverDescriptor.getSchema()));
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.repo.dictionary.CustomModelsInfo;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.dictionary.CustomModelService;
import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
public class UsageModelDataCollector extends HBBaseDataCollector
{
/** The logger. */
private static final Log logger = LogFactory.getLog(UsageModelDataCollector.class);
/** DAO for current repository descriptor. */
private DescriptorDAO currentRepoDescriptorDAO;
/** Provides information about custom models */
private CustomModelService customModelService;
/** The transaction service. */
private TransactionService transactionService;
public UsageModelDataCollector(String collectorId) {
super(collectorId);
}
public void setCurrentRepoDescriptorDAO(DescriptorDAO currentRepoDescriptorDAO)
{
this.currentRepoDescriptorDAO = currentRepoDescriptorDAO;
}
public void setCustomModelService(CustomModelService customModelService)
{
this.customModelService = customModelService;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
@Override
public List<HBData> collectData()
{
if(transactionService == null)
{
logger.debug("Couldn't collect data because transaction service is null");
return null;
}
if(customModelService == null)
{
logger.debug("Couldn't collect data because custom model service is null");
return null;
}
if(currentRepoDescriptorDAO == null)
{
logger.debug("Couldn't collect data because repository descriptor is null");
return null;
}
logger.debug("Preparing repository usage (model) data...");
final CustomModelsInfo customModelsInfo = transactionService.getRetryingTransactionHelper().doInTransaction(
() -> customModelService.getCustomModelsInfo(), true);
Map<String, Object> modelUsageValues = new HashMap<>();
modelUsageValues.put("numOfActiveModels", new Integer(customModelsInfo.getNumberOfActiveModels()));
modelUsageValues.put("numOfActiveTypes", new Integer(customModelsInfo.getNumberOfActiveTypes()));
modelUsageValues.put("numOfActiveAspects", new Integer(customModelsInfo.getNumberOfActiveAspects()));
HBData modelUsageData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
this.getCollectorId(),
this.getCollectorVersion(),
new Date(),
modelUsageValues);
List<HBData> collectedData = new LinkedList<>();
collectedData.add(modelUsageData);
return collectedData;
}
}

View File

@@ -0,0 +1,80 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
public class UsageSystemDataCollector extends HBBaseDataCollector
{
/** The logger. */
private static final Log logger = LogFactory.getLog(UsageSystemDataCollector.class);
/** DAO for current repository descriptor. */
private DescriptorDAO currentRepoDescriptorDAO;
public UsageSystemDataCollector(String collectorId)
{
super(collectorId);
}
public void setCurrentRepoDescriptorDAO(DescriptorDAO currentRepoDescriptorDAO)
{
this.currentRepoDescriptorDAO = currentRepoDescriptorDAO;
}
@Override
public List<HBData> collectData()
{
if(currentRepoDescriptorDAO == null)
{
logger.debug("Couldn't collect data because repository descriptor is null");
return null;
}
logger.debug("Preparing repository usage (system) data...");
Runtime runtime = Runtime.getRuntime();
Map<String, Object> systemUsageValues = new HashMap<>();
systemUsageValues.put("memFree", runtime.freeMemory());
systemUsageValues.put("memMax", runtime.maxMemory());
systemUsageValues.put("memTotal", runtime.totalMemory());
HBData systemUsageData = new HBData(
this.currentRepoDescriptorDAO.getDescriptor().getId(),
this.getCollectorId(),
this.getCollectorVersion(),
new Date(),
systemUsageValues);
List<HBData> collectedData = new LinkedList<>();
collectedData.add(systemUsageData);
return collectedData;
}
}

View File

@@ -29,6 +29,7 @@ import java.io.InputStream;
import java.lang.reflect.Constructor;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.heartbeat.HBDataCollectorServiceImpl;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
@@ -37,6 +38,7 @@ import org.alfresco.repo.usage.RepoUsageComponent;
import org.alfresco.service.cmr.admin.RepoUsage;
import org.alfresco.service.cmr.admin.RepoUsage.LicenseMode;
import org.alfresco.service.cmr.admin.RepoUsage.UsageType;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.descriptor.DescriptorService;
import org.alfresco.service.license.LicenseDescriptor;
@@ -68,8 +70,8 @@ public class DescriptorServiceImpl extends AbstractLifecycleBean
private TransactionService transactionService;
private LicenseService licenseService;
private RepoUsageComponent repoUsageComponent;
private HBDataCollectorService hbDataCollectorService;
@SuppressWarnings("unused")
private Object heartBeat;
private boolean isBootstrapped;
@@ -127,6 +129,11 @@ public class DescriptorServiceImpl extends AbstractLifecycleBean
this.transactionService = transactionService;
}
public void setHbDataCollectorService(HBDataCollectorService hbDataCollectorService)
{
this.hbDataCollectorService = hbDataCollectorService;
}
public void setRepoUsageComponent(RepoUsageComponent repoUsageComponent)
{
this.repoUsageComponent = repoUsageComponent;
@@ -238,7 +245,7 @@ public class DescriptorServiceImpl extends AbstractLifecycleBean
}
/**
* On bootstrap load the special services for LicenseComponent and HeartBeat
* On bootstrap load the special services for LicenseComponent
*
* Also set installedRepoDescriptor and update current
*/
@@ -304,8 +311,9 @@ public class DescriptorServiceImpl extends AbstractLifecycleBean
"licenseService", licenseService);
}
// Load heart-beat special service (even if disabled at the moment)
heartBeat = constructSpecialService("org.alfresco.heartbeat.HeartBeat");
// Register HeartBeat with LicenseService
licenseService.registerOnLicenseChange((LicenseChangeHandler) hbDataCollectorService);
// Now listen for future license changes
licenseService.registerOnLicenseChange(this);

View File

@@ -31,11 +31,5 @@ public interface HBDataCollectorService
{
void registerCollector(HBBaseDataCollector collector);
void collectAndSendData();
void enabled(boolean enabled);
boolean isEnabledByDefault();
}

View File

@@ -284,6 +284,9 @@
<property name="transactionService">
<ref bean="transactionService"/>
</property>
<property name="hbDataCollectorService">
<ref bean="hbDataCollectorService"/>
</property>
<property name="repoUsageComponent" ref="repoUsageComponent"/>
</bean>

View File

@@ -16,10 +16,13 @@
<bean id="hbDataCollectorService" class="org.alfresco.heartbeat.HBDataCollectorServiceImpl">
<constructor-arg value="${heartbeat.enabled}" />
<property name="hbDataSenderService" ref="hbDataSenderService" />
<property name="scheduler" ref="schedulerFactory" />
<property name="jobLockService" ref="jobLockService" />
<property name="testMode" value="true"/>
</bean>
<!-- HeartBeat abstract data collector -->
<bean id="hbBaseDataCollector" class="org.alfresco.heartbeat.HBBaseDataCollector" abstract="true">
<!-- HeartBeat template data collector -->
<bean id="hbBaseDataCollector" abstract="true" init-method="register">
<property name="hbDataCollectorService" ref="hbDataCollectorService"/>
</bean>

View File

@@ -3,16 +3,38 @@
<beans>
<!-- HeartBeat repository data collector -->
<bean id="repositoryDataCollector" class="org.alfresco.heartbeat.RepositoryDataCollector" parent="hbBaseDataCollector" init-method="register">
<!-- HeartBeat repository info data collector -->
<bean id="infoDataCollector" class="org.alfresco.heartbeat.InfoDataCollector" parent="hbBaseDataCollector" >
<constructor-arg type = "java.lang.String" value = "acs.repository.info"/>
<property name="collectorVersion" value="1.0"/>
<property name="cronExpression" value="0 0 0 ? * SUN"/> <!-- Weekly -->
<property name="currentRepoDescriptorDAO" ref="currentRepoDescriptorDAO"/>
<property name="serverDescriptorDAO" ref="serverDescriptorDAO"/>
<property name="transactionService" ref="transactionService"/>
</bean>
<!-- HeartBeat repository usage model data collector -->
<bean id="usageModelDataCollector" class="org.alfresco.heartbeat.UsageModelDataCollector" parent="hbBaseDataCollector" >
<constructor-arg type = "java.lang.String" value = "acs.repository.usage.model"/>
<property name="collectorVersion" value="1.0"/>
<property name="cronExpression" value="0 0 0 ? * *"/> <!-- Daily -->
<property name="currentRepoDescriptorDAO" ref="currentRepoDescriptorDAO"/>
<property name="customModelService" ref="customModelService"/>
<property name="transactionService" ref="transactionService"/>
</bean>
<!-- HeartBeat repository usage system data collector -->
<bean id="usageSystemDataCollector" class="org.alfresco.heartbeat.UsageSystemDataCollector" parent="hbBaseDataCollector" >
<constructor-arg type = "java.lang.String" value = "acs.repository.usage.system"/>
<property name="collectorVersion" value="1.0"/>
<property name="cronExpression" value="0 0 0 ? * *"/> <!-- Daily -->
<property name="currentRepoDescriptorDAO" ref="currentRepoDescriptorDAO"/>
</bean>
<!-- HeartBeat authority data collector -->
<bean id="authorityDataCollector" class="org.alfresco.heartbeat.AuthoritiesDataCollector" parent="hbBaseDataCollector" init-method="register">
<bean id="authorityDataCollector" class="org.alfresco.heartbeat.AuthoritiesDataCollector" parent="hbBaseDataCollector" >
<constructor-arg type = "java.lang.String" value = "acs.repository.usage.authorities"/>
<property name="collectorVersion" value="1.0"/>
<property name="cronExpression" value="0 0 0 ? * *"/> <!-- Daily -->
<property name="currentRepoDescriptorDAO" ref="currentRepoDescriptorDAO"/>
<property name="authorityService" ref="authorityService"/>
</bean>

View File

@@ -187,7 +187,10 @@ import org.junit.runners.Suite;
org.alfresco.repo.workflow.WorkflowSuiteContextShutdownTest.class,
org.alfresco.repo.search.impl.lucene.analysis.PathTokenFilterTest.class,
org.alfresco.heartbeat.HBDataCollectorServiceImplTest.class,
org.alfresco.heartbeat.AuthoritiesDataCollectorTest.class
org.alfresco.heartbeat.HeartBeatJobTest.class,
org.alfresco.heartbeat.InfoDataCollectorTest.class,
org.alfresco.heartbeat.UsageModelDataCollectorTest.class,
org.alfresco.heartbeat.UsageSystemDataCollectorTest.class
})
public class AllUnitTestsSuite
{

View File

@@ -51,7 +51,6 @@ import org.junit.runners.Suite;
org.alfresco.repo.tenant.MultiTServiceImplTest.class,
org.alfresco.repo.search.SearcherComponentTest.class,
org.alfresco.repo.blog.BlogServiceImplTest.class,
org.alfresco.heartbeat.RepositoryDataCollectorTest.class,
})
public class AppContext06TestSuite
{

View File

@@ -130,9 +130,6 @@ import org.springframework.context.ApplicationContext;
// [alfresco/scheduler-core-context.xml, org/alfresco/util/test-scheduled-jobs-context.xml]
org.alfresco.util.CronTriggerBeanTest.class,
// [alfresco/scheduler-core-context.xml, org/alfresco/heartbeat/test-heartbeat-context.xml]
org.alfresco.heartbeat.HeartBeatTest.class,
// ----------------------------------------------------------------------
// Transformer/Rendition contexts
//
@@ -149,8 +146,6 @@ import org.springframework.context.ApplicationContext;
// this does NOT passes locally
org.alfresco.repo.rendition.RenditionServicePermissionsTest.class,
// [alfresco/scheduler-core-context.xml, org/alfresco/heartbeat/test-heartbeat-context.xml]
org.alfresco.heartbeat.HeartBeatTest.class,
})
public class MiscContextTestSuite
{

View File

@@ -59,7 +59,8 @@ public class AuthoritiesDataCollectorTest
DescriptorDAO descriptorDAO = mock(DescriptorDAO.class);
when(descriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
authorityDataCollector = new AuthoritiesDataCollector();
authorityDataCollector = new AuthoritiesDataCollector("acs.repository.usage.authorities");
authorityDataCollector.setCollectorVersion("1.0");
authorityDataCollector.setAuthorityService(authorityService);
authorityDataCollector.setCurrentRepoDescriptorDAO(descriptorDAO);
authorityDataCollector.setHbDataCollectorService(mockCollectorService);
@@ -83,7 +84,7 @@ public class AuthoritiesDataCollectorTest
@Test
public void testInfoDataIsCollected()
{
HBData authorityInfo = grabDataByCollectorId("acs.repository.usage.authorities");
HBData authorityInfo = grabDataByCollectorId(authorityDataCollector.getCollectorId());
assertNotNull("Authority info data missing.", authorityInfo);
Map<String,Object> data = authorityInfo.getData();

View File

@@ -27,17 +27,23 @@ package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.heartbeat.datasender.HBDataSenderService;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.repo.scheduler.AlfrescoSchedulerFactory;
import org.alfresco.service.license.LicenseDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.mockito.Mockito.when;
/**
* @author eknizat
@@ -45,83 +51,284 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
public class HBDataCollectorServiceImplTest
{
private HBDataCollectorServiceImpl dataCollectorService;
private HBDataSenderService mockDataSenderService;
private final String VALID_CRON = "0 0/2 * * * ?";
private final String INVALID_CRON = "0 no no * * ?";
private final HBBaseDataCollector validCollector1 = new SimpleHBDataCollector("validCollector1", VALID_CRON);
private final HBBaseDataCollector validCollector2 = new SimpleHBDataCollector("validCollector2", VALID_CRON);
private Scheduler scheduler;
@Before
public void setUp()
public void before() throws Exception
{
mockDataSenderService = mock(HBDataSenderService.class);
dataCollectorService = new HBDataCollectorServiceImpl(true);
dataCollectorService.setHbDataSenderService(mockDataSenderService);
// Create fresh scheduler
SchedulerFactoryBean sfb = new SchedulerFactoryBean();
sfb.setSchedulerFactoryClass(AlfrescoSchedulerFactory.class);
sfb.setAutoStartup(false);
sfb.afterPropertiesSet();
scheduler = sfb.getScheduler();
}
@Test
public void testInitialEnabledEqualsDefaultState()
public void testInitialEnabledEqualsDefaultState() throws Exception
{
HBDataCollectorService dataCollectorService = new HBDataCollectorServiceImpl(true);
HBDataCollectorServiceImpl dataCollectorService = new HBDataCollectorServiceImpl(true);
assertTrue(dataCollectorService.isEnabledByDefault());
dataCollectorService = new HBDataCollectorServiceImpl(false);
assertFalse(dataCollectorService.isEnabledByDefault());
}
@Test
public void testHBDataSenderServiceEnabledChange()
public void testJobSchedulingWhenEnabled() throws Exception
{
dataCollectorService.enabled(false);
verify(mockDataSenderService).enable(false);
// Enable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
collectorService.setScheduler(scheduler);
dataCollectorService.enabled(true);
verify(mockDataSenderService).enable(true);
// Register few collectors
registerValidCollectors(collectorService);
// Check that the jobs are scheduled for all collectors when heartbeat is enabled
assertTrue(collectorService.isEnabled());
assertCollectorJobsScheduled("Job was not scheduled but HB is enabled", scheduler);
}
@Test
public void testCollectAndSendData()
public void testJobSchedulingWhenDisabled() throws Exception
{
// Set up dummy collector 1
HBData c1Data = new HBData("sys", "c1","1.0",null);
HBBaseDataCollector c1 = new DummyCollector(c1Data);
c1.setHbDataCollectorService(dataCollectorService);
c1.register();
// Set up dummy collector 2
HBData c2Data = new HBData("sys", "c2","1.0",null);
HBBaseDataCollector c2 = new DummyCollector(c2Data);
c2.setHbDataCollectorService(dataCollectorService);
c2.register();
// Set up dummy collector 3
HBData c3Data = new HBData("sys", "c3","1.0",null);
HBBaseDataCollector c3 = new DummyCollector(c3Data);
c3.setHbDataCollectorService(dataCollectorService);
c3.register();
// Disable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(false);
collectorService.setScheduler(scheduler);
// Check that the collector service collects data from registered collectors and passes the data to data sender service
dataCollectorService.collectAndSendData();
// Register collectors
registerValidCollectors(collectorService);
// Check data is passed for each collector
verify(mockDataSenderService, times(3)).sendData(any(List.class));
verify(mockDataSenderService).sendData(c1.collectData());
verify(mockDataSenderService).sendData(c2.collectData());
verify(mockDataSenderService).sendData(c3.collectData());
// Check that the jobs are not scheduled for any collectors when heartbeat is disabled
assertFalse(collectorService.isEnabled());
assertCollectorJobsNotScheduled("Job was scheduled but HB is disabled", scheduler);
}
class DummyCollector extends HBBaseDataCollector
/**
* Heartbeat enabled by default but disabled in licence on onLicenseChange
*/
@Test
public void testOnLicenseChangeOverridesDefaultEnabled() throws Exception
{
private HBData data;
// Enable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
final HBDataSenderService sender = mock( HBDataSenderService.class);
collectorService.setHbDataSenderService(sender);
collectorService.setScheduler(scheduler);
public DummyCollector (HBData testData)
// Register few collectors
registerValidCollectors(collectorService);
// Heartbeat disabled in licence
enabledHbInLicense( collectorService,false);
// Check heart beat is disabled and all collector jobs are unscheduled
assertFalse(collectorService.isEnabled());
assertCollectorJobsNotScheduled("Job was scheduled but HB is disabled", scheduler);
// Also check sender is updated
verify(sender).enable(false);
}
/**
* Heartbeat disabled by default but enabled in licence on onLicenseChange
*/
@Test
public void testOnLicenseChangeOverridesDefaultDisabled() throws Exception
{
// Disable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(false);
final HBDataSenderService sender = mock( HBDataSenderService.class);
collectorService.setHbDataSenderService(sender);
collectorService.setScheduler(scheduler);
// Register few collectors
registerValidCollectors(collectorService);
// Heartbeat enabled in licence
enabledHbInLicense( collectorService,true);
// Check heart beat is enabled and all collector jobs are scheduled
assertTrue(collectorService.isEnabled());
assertCollectorJobsScheduled("Job was not scheduled but HB is enabled", scheduler);
// Also check sender is updated
verify(sender).enable(true);
}
/**
* Heartbeat revert back to default enabled state on license fail
*/
@Test
public void testOnLicenceFailRevertsToEnabled() throws Exception
{
// Enable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
collectorService.setScheduler(scheduler);
// Register few collectors
registerValidCollectors(collectorService);
// Heartbeat disabled in licence
enabledHbInLicense( collectorService,false);
// Revert back to default state
collectorService.onLicenseFail();
// Check heartbeat state reverts to default enabled state and jobs are scheduled
assertTrue(collectorService.isEnabled());
assertCollectorJobsScheduled("Job should be unscheduled.", scheduler);
}
/**
* Heartbeat revert back to default disabled state on license fail
*/
@Test
public void testOnLicenceFailRevertsToDisabled() throws Exception
{
// Disable heartbeat by setting the default enabled state ( as if set in prop file)
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(false);
collectorService.setScheduler(scheduler);
// Register few collectors
registerValidCollectors(collectorService);
// Heartbeat enabled in licence
enabledHbInLicense( collectorService,true);
// Revert back to default state
collectorService.onLicenseFail();
// Check heartbeat is disabled and job unscheduled
assertFalse(collectorService.isEnabled());
assertCollectorJobsNotScheduled("Job should be unscheduled.",scheduler);
}
/**
* Test scheduling job for collector with invalid cron expression
*/
@Test
public void testInvalidCronExpression() throws Exception
{
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
collectorService.setScheduler(scheduler);
// Register collector with valid cron expression
SimpleHBDataCollector c1 = new SimpleHBDataCollector("c1", VALID_CRON);
collectorService.registerCollector(c1);
// Register collector with invalid cron expression
SimpleHBDataCollector c2 = new SimpleHBDataCollector("c2", INVALID_CRON);
collectorService.registerCollector(c2);
assertTrue(isJobScheduledForCollector(c1.getCollectorId(),scheduler));
assertFalse(isJobScheduledForCollector(c2.getCollectorId(),scheduler));
}
/**
*
* Jobs are scheduled with cron expressions provided by collectors
*
*/
@Test
public void testJobsScheduledWithDifferentCronExpressions() throws Exception
{
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
collectorService.setScheduler(scheduler);
final String cron1 = "0 0/1 * * * ?";
final String cron2 = "0 0/2 * * * ?";
final String cron3 = "0 0/3 * * * ?";
final HBBaseDataCollector c1 = new SimpleHBDataCollector("c1", cron1);
final HBBaseDataCollector c2 = new SimpleHBDataCollector("c2", cron2);
final HBBaseDataCollector c3 = new SimpleHBDataCollector("c3", cron3);
final String triggerName1 = "heartbeat-" + c1.getCollectorId() + "-Trigger";
final String triggerName2 = "heartbeat-" + c2.getCollectorId() + "-Trigger";
final String triggerName3 = "heartbeat-" + c3.getCollectorId() + "-Trigger";
// Register 3 collectors with 3 different cron expressions
collectorService.registerCollector(c1);
collectorService.registerCollector(c2);
collectorService.registerCollector(c3);
String testCron1 = ((CronTrigger) scheduler.getTrigger(triggerName1, Scheduler.DEFAULT_GROUP)).getCronExpression();
String testCron2 = ((CronTrigger) scheduler.getTrigger(triggerName2, Scheduler.DEFAULT_GROUP)).getCronExpression();
String testCron3 = ((CronTrigger) scheduler.getTrigger(triggerName3, Scheduler.DEFAULT_GROUP)).getCronExpression();
assertEquals("Cron expression doesn't match", cron1, testCron1);
assertEquals("Cron expression doesn't match", cron2, testCron2);
assertEquals("Cron expression doesn't match", cron3, testCron3);
}
@Test
public void testRegisterSameCollectorTwice() throws Exception
{
final HBDataCollectorServiceImpl collectorService = new HBDataCollectorServiceImpl(true);
collectorService.setScheduler(scheduler);
HBBaseDataCollector c1 = new SimpleHBDataCollector("c1", VALID_CRON);
collectorService.registerCollector(c1);
collectorService.registerCollector(c1);
assertEquals("Expected only one collector to be scheduled.",1,scheduler.getJobNames(Scheduler.DEFAULT_GROUP).length );
}
// Helper methods
private void registerValidCollectors(HBDataCollectorServiceImpl collectorService)
{
collectorService.registerCollector(validCollector1);
collectorService.registerCollector(validCollector2);
}
private void assertCollectorJobsScheduled(String message, Scheduler scheduler) throws Exception
{
assertTrue(message, isJobScheduledForCollector(validCollector1.getCollectorId(), scheduler));
assertTrue(message, isJobScheduledForCollector(validCollector2.getCollectorId(), scheduler));
}
private void assertCollectorJobsNotScheduled(String message, Scheduler scheduler) throws Exception
{
assertFalse(message, isJobScheduledForCollector(validCollector1.getCollectorId(), scheduler));
assertFalse(message, isJobScheduledForCollector(validCollector2.getCollectorId(), scheduler));
}
private void enabledHbInLicense(HBDataCollectorServiceImpl collectorService, boolean activate)
{
LicenseDescriptor mockLicenseDescriptor = mock(LicenseDescriptor.class);
when(mockLicenseDescriptor.isHeartBeatDisabled()).thenReturn(!activate);
collectorService.onLicenseChange(mockLicenseDescriptor);
}
private boolean isJobScheduledForCollector(String collectorId, Scheduler scheduler) throws Exception
{
String jobName = "heartbeat-" + collectorId;
String triggerName = jobName + "-Trigger";
String[] jobs = scheduler.getJobNames(Scheduler.DEFAULT_GROUP);
String[] triggers = scheduler.getTriggerNames(Scheduler.DEFAULT_GROUP);
return Arrays.asList(jobs).contains(jobName) && Arrays.asList(triggers).contains(triggerName);
}
private class SimpleHBDataCollector extends HBBaseDataCollector
{
public SimpleHBDataCollector(String collectorId, String cron)
{
this.data = testData;
super(collectorId);
this.setCronExpression(cron);
}
@Override
public List<HBData> collectData() {
return Arrays.asList(data);
public List<HBData> collectData()
{
List<HBData> result = new LinkedList<>();
return result;
}
}
}

View File

@@ -0,0 +1,219 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.heartbeat.datasender.HBDataSenderService;
import org.alfresco.repo.lock.JobLockService;
import org.alfresco.repo.lock.LockAcquisitionException;
import org.alfresco.service.namespace.QName;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created by mmuller on 27/10/2017.
*/
public class HeartBeatJobTest
{
private HBDataSenderService mockDataSenderService;
private JobLockService mockJobLockService;
@Before
public void setUp()
{
mockDataSenderService = mock(HBDataSenderService.class);
mockJobLockService = mock(JobLockService.class);
}
private class SimpleHBDataCollector extends HBBaseDataCollector
{
public SimpleHBDataCollector(String collectorId)
{
super(collectorId);
}
public List<HBData> collectData()
{
List<HBData> result = new LinkedList<>();
result.add(new HBData("systemId2", this.getCollectorId(), "1", new Date()));
return result;
}
}
@Test
public void testJobInClusterNotLocked() throws Exception
{
// mock the job context
JobExecutionContext mockJobExecutionContext = mock(JobExecutionContext.class);
JobDetail jobDetail = new JobDetail();
when(mockJobExecutionContext.getJobDetail()).thenReturn(jobDetail);
// create the hb collector
SimpleHBDataCollector simpleCollector = spy(new SimpleHBDataCollector("simpleCollector"));
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("collector", simpleCollector);
jobDataMap.put("hbDataSenderService", mockDataSenderService);
jobDataMap.put("jobLockService", mockJobLockService);
jobDetail.setJobDataMap(jobDataMap);
// collector job is not locked from an other collector
String lockToken = "locked";
Runnable r1 = () ->
{
// if a second job tries to get the lock before we finished that will raise the exception
when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken).thenThrow(new LockAcquisitionException("", ""));
try
{
new HeartBeatJob().execute(mockJobExecutionContext);
}
catch (JobExecutionException e)
{
//
}
finally
{
// when we are finished an other job can have the lock
when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken);
}
};
Runnable r2 = () ->
{
try
{
new HeartBeatJob().execute(mockJobExecutionContext);
}
catch (JobExecutionException e)
{
//
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
Thread.sleep(6000);
t2.start();
Thread.sleep(6000);
// verify that we collected and send data but just one time
verify(simpleCollector, Mockito.times(2)).collectData();
verify(mockDataSenderService, Mockito.times(2)).sendData(any(List.class));
verify(mockDataSenderService, Mockito.times(0)).sendData(any(HBData.class));
verify(mockJobLockService, Mockito.times(2)).getLock(any(QName.class), anyLong());
verify(mockJobLockService, Mockito.times(2)).refreshLock(eq(lockToken), any(QName.class), anyLong(), any(
JobLockService.JobLockRefreshCallback.class));
verify(mockJobLockService, Mockito.times(2)).releaseLock(eq(lockToken), any(QName.class));
}
@Test
public void testJobInClusterLocked() throws Exception
{
// mock the job context
JobExecutionContext mockJobExecutionContext = mock(JobExecutionContext.class);
JobDetail jobDetail = new JobDetail();
when(mockJobExecutionContext.getJobDetail()).thenReturn(jobDetail);
// create the hb collector
SimpleHBDataCollector simpleCollector = spy(new SimpleHBDataCollector("simpleCollector"));
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("collector", simpleCollector);
jobDataMap.put("hbDataSenderService", mockDataSenderService);
jobDataMap.put("jobLockService", mockJobLockService);
jobDetail.setJobDataMap(jobDataMap);
// collector job is not locked from an other collector
String lockToken = "locked";
Runnable r1 = () ->
{
// if a second job tries to get the lock before we finished that will raise the exception
when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken).thenThrow(new LockAcquisitionException("", ""));
try
{
new HeartBeatJob().execute(mockJobExecutionContext);
}
catch (JobExecutionException e)
{
//
}
finally
{
// when we are finished an other job can have the lock
when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken);
}
};
Runnable r2 = () ->
{
try
{
new HeartBeatJob().execute(mockJobExecutionContext);
}
catch (JobExecutionException e)
{
//
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
Thread.sleep(1000);
t2.start();
Thread.sleep(6000);
// verify that we collected and send data but just one time
verify(simpleCollector, Mockito.times(1)).collectData();
verify(mockDataSenderService, Mockito.times(1)).sendData(any(List.class));
verify(mockDataSenderService, Mockito.times(0)).sendData(any(HBData.class));
verify(mockJobLockService, Mockito.times(2)).getLock(any(QName.class), anyLong());
verify(mockJobLockService, Mockito.times(1)).refreshLock(eq(lockToken), any(QName.class), anyLong(), any(
JobLockService.JobLockRefreshCallback.class));
verify(mockJobLockService, Mockito.times(1)).releaseLock(eq(lockToken), any(QName.class));
}
}

View File

@@ -1,208 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.license.LicenseDescriptor;
import org.alfresco.service.license.LicenseService;
import org.junit.Before;
import org.junit.Test;
import org.quartz.Scheduler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Arrays;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author eknizat
*/
public class HeartBeatTest
{
private static final String[] CONFIG_LOCATIONS = new String[] {
"classpath:alfresco/scheduler-core-context.xml",
"classpath:org/alfresco/heartbeat/test-heartbeat-context.xml"};
private ApplicationContext context;
LicenseService mockLicenseService;
HBDataCollectorService mockDataCollectorService;
@Before
public void setUp()
{
// New context with scheduler
context = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS);
// Add services to context
mockLicenseService = mock(LicenseService.class);
mockDataCollectorService = mock(HBDataCollectorService.class);
((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton("licenseService",mockLicenseService);
((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton("hbDataCollectorService",mockDataCollectorService);
}
@Test
public void testHBRegistersWithLicenceService()
{
HeartBeat heartbeat = new HeartBeat(context,false);
// Check that HearBeat registers itself with the licence service
verify(mockLicenseService).registerOnLicenseChange(heartbeat);
}
@Test
public void testJobSchedulingWhenEnabled() throws Exception
{
// Enable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(true);
HeartBeat heartbeat = new HeartBeat(context,true);
// Check that the job is scheduled when heartbeat is enabled
assertTrue("Job was not scheduled but HB is enabled", isJobScheduled());
}
@Test
public void testJobSchedulingWhenDisabled() throws Exception
{
// Disable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(false);
HeartBeat heartbeat = new HeartBeat(context,true);
// Check that the job is not scheduled when heartbeat is disabled
assertFalse("Job was scheduled but HB is disabled", isJobScheduled());
}
/**
* Heartbeat enabled by default but disabled in licence on onLicenseChange
*/
@Test
public void testOnLicenseChangeOverridesDefaultEnabled() throws Exception
{
// Enable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(true);
HeartBeat heartbeat = new HeartBeat(context,true);
// heartbeat disabled in licence
LicenseDescriptor mockLicenseDescriptor = mock(LicenseDescriptor.class);
when(mockLicenseDescriptor.isHeartBeatDisabled()).thenReturn(true);
assertTrue(heartbeat.isEnabled());
assertTrue("Job should be scheduled at this point.",isJobScheduled());
heartbeat.onLicenseChange(mockLicenseDescriptor);
// Check heartbeat is disabled and job unscheduled
assertFalse(heartbeat.isEnabled());
assertFalse("Job should be unscheduled.",isJobScheduled());
}
/**
* heartbeat disabled by default but enabled in licence
*/
@Test
public void testOnLicenseChangeOverridesDefaultDisabled() throws Exception
{
// Disable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(false);
HeartBeat heartbeat = new HeartBeat(context,true);
// heartbeat enabled in licence
LicenseDescriptor mockLicenseDescriptor = mock(LicenseDescriptor.class);
when(mockLicenseDescriptor.isHeartBeatDisabled()).thenReturn(false);
assertFalse(heartbeat.isEnabled());
assertFalse("Job should not be scheduled at this point.",isJobScheduled());
heartbeat.onLicenseChange(mockLicenseDescriptor);
// Check heartbeat is enabled and job unscheduled
assertTrue(heartbeat.isEnabled());
assertTrue("Job should be scheduled.",isJobScheduled());
}
@Test
public void testOnLicenceFailRevertsToEnabled() throws Exception
{
// Enable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(true);
HeartBeat heartbeat = new HeartBeat(context,true);
// heartbeat disabled in licence
LicenseDescriptor mockLicenseDescriptor = mock(LicenseDescriptor.class);
when(mockLicenseDescriptor.isHeartBeatDisabled()).thenReturn(true);
heartbeat.onLicenseChange(mockLicenseDescriptor);
assertFalse(heartbeat.isEnabled());
assertFalse("Job should not be scheduled at this point.",isJobScheduled());
// Revert back to default state
heartbeat.onLicenseFail();
// Check heartbeat is enabled and job unscheduled
assertTrue(heartbeat.isEnabled());
assertTrue("Job should be unscheduled.",isJobScheduled());
}
@Test
public void testOnLicenceFailRevertsToDisabled() throws Exception
{
// Disable heartbeat in data collector service ( as if set in prop file)
when(mockDataCollectorService.isEnabledByDefault()).thenReturn(false);
HeartBeat heartbeat = new HeartBeat(context,true);
// heartbeat enabled in licence
LicenseDescriptor mockLicenseDescriptor = mock(LicenseDescriptor.class);
when(mockLicenseDescriptor.isHeartBeatDisabled()).thenReturn(false);
heartbeat.onLicenseChange(mockLicenseDescriptor);
assertTrue(heartbeat.isEnabled());
assertTrue("Job should be scheduled at this point.",isJobScheduled());
// Revert back to default state
heartbeat.onLicenseFail();
// Check heartbeat is disabled and job unscheduled
assertFalse(heartbeat.isEnabled());
assertFalse("Job should be unscheduled.",isJobScheduled());
}
private boolean isJobScheduled() throws Exception
{
Scheduler scheduler = (Scheduler) context.getBean("schedulerFactory");
String[] jobs = scheduler.getJobNames( Scheduler.DEFAULT_GROUP);
return Arrays.asList(jobs).contains("heartbeat");
}
}

View File

@@ -0,0 +1,119 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.repo.dictionary.CustomModelsInfo;
import org.alfresco.service.cmr.dictionary.CustomModelService;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author eknizat
*/
public class InfoDataCollectorTest
{
private InfoDataCollector infoCollector;
private HBDataCollectorService mockCollectorService;
private DescriptorDAO mockDescriptorDAO;
private DescriptorDAO mockServerDescriptorDAO;
private List<HBData> collectedData;
@Before
public void setUp()
{
mockDescriptorDAO = mock(DescriptorDAO.class);
mockServerDescriptorDAO = mock(DescriptorDAO.class);
mockCollectorService = mock(HBDataCollectorService.class);
Descriptor mockDescriptor = mock(Descriptor.class);
when(mockDescriptor.getId()).thenReturn("mock_id");
when(mockServerDescriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
when(mockDescriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
infoCollector = new InfoDataCollector("acs.repository.info");
infoCollector.setCollectorVersion("1.0");
infoCollector.setHbDataCollectorService(mockCollectorService);
infoCollector.setCurrentRepoDescriptorDAO(mockDescriptorDAO);
infoCollector.setServerDescriptorDAO(mockServerDescriptorDAO);
collectedData = infoCollector.collectData();
}
@Test
public void testHBDataFields()
{
for(HBData data : this.collectedData)
{
assertNotNull(data.getCollectorId());
assertNotNull(data.getCollectorVersion());
assertNotNull(data.getSchemaVersion());
assertNotNull(data.getSystemId());
assertNotNull(data.getTimestamp());
}
}
@Test
public void testInfoDataIsCollected()
{
HBData repoInfo = grabDataByCollectorId(infoCollector.getCollectorId());
assertNotNull("Repository info data missing.", repoInfo);
Map<String,Object> data = repoInfo.getData();
assertTrue(data.containsKey("repoName"));
assertTrue(data.containsKey("edition"));
assertTrue(data.containsKey("versionMajor"));
assertTrue(data.containsKey("versionMinor"));
assertTrue(data.containsKey("schema"));
}
private HBData grabDataByCollectorId(String collectorId)
{
for (HBData d : this.collectedData)
{
if(d.getCollectorId()!=null && d.getCollectorId().equals(collectorId))
{
return d;
}
}
return null;
}
}

View File

@@ -28,54 +28,62 @@ package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.repo.dictionary.CustomModelsInfo;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.dictionary.CustomModelService;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author eknizat
*/
public class RepositoryDataCollectorTest
public class UsageModelDataCollectorTest
{
private ApplicationContext context;
private RepositoryDataCollector repoCollector;
private UsageModelDataCollector usageModelCollector;
private HBDataCollectorService mockCollectorService;
private DescriptorDAO mockDescriptorDAO;
private List<HBData> collectedData;
@Before
public void setUp()
{
context = ApplicationContextHelper.getApplicationContext();
TransactionService transactionService = (TransactionService) context.getBean("transactionService");
HBDataCollectorService mockCollectorService = mock(HBDataCollectorService.class);
mockDescriptorDAO = mock(DescriptorDAO.class);
mockCollectorService = mock(HBDataCollectorService.class);
Descriptor mockDescriptor = mock(Descriptor.class);
when(mockDescriptor.getId()).thenReturn("mock_id");
DescriptorDAO descriptorDAO = mock(DescriptorDAO.class);
when(descriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
when(mockDescriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
CustomModelsInfo mockCustomModelsInfo = mock(CustomModelsInfo.class);
CustomModelService customModelService = mock(CustomModelService.class);
when(customModelService.getCustomModelsInfo()).thenReturn(mockCustomModelsInfo);
repoCollector = new RepositoryDataCollector();
repoCollector.setCurrentRepoDescriptorDAO(descriptorDAO);
repoCollector.setCustomModelService(customModelService);
repoCollector.setServerDescriptorDAO(descriptorDAO);
repoCollector.setTransactionService(transactionService);
repoCollector.setHbDataCollectorService(mockCollectorService);
collectedData = repoCollector.collectData();
TransactionService mockTransactionService = mock(TransactionService.class);
RetryingTransactionHelper mockRetryingTransactionHelper = mock(RetryingTransactionHelper.class);
when(mockRetryingTransactionHelper.doInTransaction(any(RetryingTransactionHelper.RetryingTransactionCallback.class), anyBoolean())).thenReturn(mockCustomModelsInfo);
when(mockTransactionService.getRetryingTransactionHelper()).thenReturn(mockRetryingTransactionHelper);
usageModelCollector = new UsageModelDataCollector("acs.repository.usage.model");
usageModelCollector.setCollectorVersion("1.0");
usageModelCollector.setHbDataCollectorService(mockCollectorService);
usageModelCollector.setCurrentRepoDescriptorDAO(mockDescriptorDAO);
usageModelCollector.setCustomModelService(customModelService);
usageModelCollector.setTransactionService(mockTransactionService);
collectedData = usageModelCollector.collectData();
}
@Test
@@ -91,36 +99,10 @@ public class RepositoryDataCollectorTest
}
}
@Test
public void testInfoDataIsCollected()
{
HBData repoInfo = grabDataByCollectorId("acs.repository.info");
assertNotNull("Repository info data missing.", repoInfo);
Map<String,Object> data = repoInfo.getData();
assertTrue(data.containsKey("repoName"));
assertTrue(data.containsKey("edition"));
assertTrue(data.containsKey("versionMajor"));
assertTrue(data.containsKey("versionMinor"));
assertTrue(data.containsKey("schema"));
}
@Test
public void testSystemUsageDataIsCollected()
{
HBData systemUsage = grabDataByCollectorId("acs.repository.usage.system");
assertNotNull("Repository usage data missing.", systemUsage);
Map<String,Object> data = systemUsage.getData();
assertTrue(data.containsKey("memFree"));
assertTrue(data.containsKey("memMax"));
assertTrue(data.containsKey("memTotal"));
}
@Test
public void testModelUsageDataIsCollected()
{
HBData modelUsage = grabDataByCollectorId("acs.repository.usage.model");
HBData modelUsage = grabDataByCollectorId(usageModelCollector.getCollectorId());
assertNotNull("Model usage data missing.", modelUsage);
Map<String,Object> data = modelUsage.getData();

View File

@@ -0,0 +1,116 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.heartbeat;
import org.alfresco.heartbeat.datasender.HBData;
import org.alfresco.repo.descriptor.DescriptorDAO;
import org.alfresco.repo.dictionary.CustomModelsInfo;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.dictionary.CustomModelService;
import org.alfresco.service.cmr.repository.HBDataCollectorService;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author eknizat
*/
public class UsageSystemDataCollectorTest
{
private UsageSystemDataCollector usageSystemCollector;
private HBDataCollectorService mockCollectorService;
private DescriptorDAO mockDescriptorDAO;
private List<HBData> collectedData;
@Before
public void setUp()
{
mockDescriptorDAO = mock(DescriptorDAO.class);
mockCollectorService = mock(HBDataCollectorService.class);
Descriptor mockDescriptor = mock(Descriptor.class);
when(mockDescriptor.getId()).thenReturn("mock_id");
when(mockDescriptorDAO.getDescriptor()).thenReturn(mockDescriptor);
usageSystemCollector = new UsageSystemDataCollector("acs.repository.usage.system");
usageSystemCollector.setCollectorVersion("1.0");
usageSystemCollector.setHbDataCollectorService(mockCollectorService);
usageSystemCollector.setCurrentRepoDescriptorDAO(mockDescriptorDAO);
collectedData = usageSystemCollector.collectData();
}
@Test
public void testHBDataFields()
{
for(HBData data : this.collectedData)
{
assertNotNull(data.getCollectorId());
assertNotNull(data.getCollectorVersion());
assertNotNull(data.getSchemaVersion());
assertNotNull(data.getSystemId());
assertNotNull(data.getTimestamp());
}
}
@Test
public void testSystemUsageDataIsCollected()
{
HBData systemUsage = grabDataByCollectorId(usageSystemCollector.getCollectorId());
assertNotNull("Repository usage data missing.", systemUsage);
Map<String,Object> data = systemUsage.getData();
assertTrue(data.containsKey("memFree"));
assertTrue(data.containsKey("memMax"));
assertTrue(data.containsKey("memTotal"));
}
private HBData grabDataByCollectorId(String collectorId)
{
for (HBData d : this.collectedData)
{
if(d.getCollectorId()!=null && d.getCollectorId().equals(collectorId))
{
return d;
}
}
return null;
}
}

View File

@@ -1,29 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>
<beans>
<bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="waitForJobsToCompleteOnShutdown">
<value>true</value>
</property>
<property name="schedulerFactoryClass">
<value>org.alfresco.repo.scheduler.AlfrescoSchedulerFactory</value>
</property>
<property name="jobFactory">
<bean class="org.alfresco.repo.scheduler.AlfrescoJobFactory" />
</property>
<property name="quartzProperties">
<ref bean="schedulerProperties" />
</property>
<property name="schedulerName">
<value>DefaultScheduler</value>
</property>
<!-- Do not auto start the scheduler - this is done at the end of the bootstrap process -->
<property name="autoStartup">
<value>false</value>
</property>
</bean>
</beans>