/** Get a list of the individual 'child resources' of that autogroup. */ private List<AutoGroupComposite> getAutoGroupChildren( Subject subject, int parentId, int resourceTypeId) { List<AutoGroupComposite> children = new ArrayList<AutoGroupComposite>(); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); ResourceTypeManagerLocal resourceTypeMananger = LookupUtil.getResourceTypeManager(); Resource parentResource = resourceManager.getResourceById(subject, parentId); ResourceType resourceType = null; try { resourceType = resourceTypeMananger.getResourceTypeById(subject, resourceTypeId); } catch (ResourceTypeNotFoundException e) { return children; // empty list if we don't know the child type } if ((resourceType != null) && (parentResource != null)) { // first get the resources in the autogroup List<ResourceWithAvailability> resourcesForAutoGroup = resourceManager.findResourcesByParentAndType(subject, parentResource, resourceType); int i = 0; int[] resourceIds = new int[resourcesForAutoGroup.size()]; for (ResourceWithAvailability resourceInAutoGroup : resourcesForAutoGroup) { int id = resourceInAutoGroup.getResource().getId(); resourceIds[i++] = id; } // And then the composite to return List<AutoGroupComposite> composites = resourceManager.findResourcesAutoGroups(subject, resourceIds); return composites; } return children; // empty }
protected void setResource(HttpServletRequest request, boolean config) throws Exception { try { Subject subject = WebUtility.getSubject(request); Integer resourceTypeId = WebUtility.getOptionalIntRequestParameter( request, ParamConstants.RESOURCE_TYPE_ID_PARAM, -1); int groupId = WebUtility.getOptionalIntRequestParameter(request, AttrConstants.GROUP_ID, -1); int parent = WebUtility.getOptionalIntRequestParameter(request, "parent", -1); String[] r = request.getParameterValues("r"); String[] resourceIds = request.getParameterValues("resourceIds"); // TODO rewrite the selection using WebUtility.getMetricsDisplayMode() if ((resourceTypeId > 0) && (parent > 0)) // autogroup { ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager(); ResourceType resourceType = resourceTypeManager.getResourceTypeById(subject, resourceTypeId); request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType); request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resourceType.getName()); request.setAttribute("parent", parent); request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId); if (log.isDebugEnabled()) { log.debug("Autogroup p=" + parent + ", ct=" + resourceTypeId); } } else if (groupId > 0) // compat (or mixed) group { ResourceGroupManagerLocal resourceGroupManager = LookupUtil.getResourceGroupManager(); ResourceGroup group = resourceGroupManager.getResourceGroupById(subject, groupId, null); request.setAttribute(AttrConstants.GROUP_ID, groupId); request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, group.getName()); // TODO more ? } else if ((resourceTypeId > 0) && (parent == -1)) // MeasurementDefinition { ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager(); ResourceType resourceType = resourceTypeManager.getResourceTypeById(subject, resourceTypeId); request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType); request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId); } else if ((r != null) && (r.length > 0)) // multiple scathered resources { log.trace("Multiple resources not handled yet"); // TODO what do we do here? } else if ((resourceIds != null) && (resourceIds.length > 0)) { log.trace("Multiple resources not yet handled"); // TODO what to we do here? } else // single resource { Integer resourceId = WebUtility.getRequiredIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Resource resource = resourceManager.getResourceById(subject, resourceId); ResourceUIBean resourceUIBean = new ResourceUIBean(resource, subject); request.setAttribute(AttrConstants.RESOURCE_ATTR, resource); request.setAttribute(AttrConstants.RESOURCE_ID_ATTR, resourceId); request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resource.getName()); request.setAttribute( AttrConstants.PERFORMANCE_SUPPORTED_ATTR, resourceUIBean.getFacets().isCallTime()); } } catch (ResourceNotFoundException e) { RequestUtils.setError(request, MessageConstants.ERR_RESOURCE_NOT_FOUND); } }
public OperationsDelegate() { SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); overlord = subjectManager.getOverlord(); resourceGroupManager = LookupUtil.getResourceGroupManager(); bundleManager = LookupUtil.getBundleManager(); }
/** * Bean responsible for the agent details display page. This bean will also provide a pagable list * of the failover servers for a particular agent. * * @author Jason Dobies */ public class ViewAgentUIBean extends PagedDataTableUIBean { public static final String MANAGED_BEAN_NAME = "ViewAgentUIBean"; private AgentManagerLocal agentManager = LookupUtil.getAgentManager(); private CloudManagerLocal cloudManager = LookupUtil.getCloudManager(); private Agent agent; public Agent getAgent() { if (agent == null) { hasPermission(); int agentId = FacesContextUtility.getRequiredRequestParameter("agentId", Integer.class); agent = agentManager.getAgentByID(agentId); } return agent; } @Override public DataModel getDataModel() { if (dataModel == null) { dataModel = new ViewAgentUIBeanDataModel(PageControlView.AgentFailoverListView, MANAGED_BEAN_NAME); } return dataModel; } private class ViewAgentUIBeanDataModel extends PagedListDataModel<FailoverListDetails> { private ViewAgentUIBeanDataModel(PageControlView view, String beanName) { super(view, beanName); } @Override public PageList<FailoverListDetails> fetchPage(PageControl pc) { int agentId = getAgent().getId(); PageList<FailoverListDetails> pageList = cloudManager.getFailoverListDetailsByAgentId(agentId, pc); return pageList; } } /** Throws a permission exception if the user is not allowed to access this functionality. */ private void hasPermission() { Subject subject = EnterpriseFacesContextUtility.getSubject(); if (!LookupUtil.getAuthorizationManager() .hasGlobalPermission(subject, Permission.MANAGE_INVENTORY)) { throw new PermissionException( "User [" + subject.getName() + "] does not have the proper permissions to view or manage agents"); } } }
@Override public void setResourceEnablement(int resourceId, boolean setEnabled) { ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Subject overlord = LookupUtil.getSubjectManager().getOverlord(); if (setEnabled) { resourceManager.enableResources(overlord, new int[] {resourceId}); } else { resourceManager.disableResources(overlord, new int[] {resourceId}); } }
public void testRegisterPlugins() throws Exception { subjectMgr = LookupUtil.getSubjectManager(); resourceTypeMgr = LookupUtil.getResourceTypeManager(); registerParentPluginV1(); // create an initial type (called the parent) registerChildPluginV1(); // using plugin extension mechanism, create a child type that extends // that parent type registerParentPluginV2(); // update the parent type checkChildPlugin(); // check that the changes to the parent type propogated to the child }
/** Prepares things for the entire test class. */ @BeforeClass public void beforeClass() throws Exception { digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); jpaDriftServer = LookupUtil.getJPADriftServer(); driftManager = LookupUtil.getDriftManager(); overlord = LookupUtil.getSubjectManager().getOverlord(); driftServerService = new DriftServerServiceImpl(); TestServerCommunicationsService agentServiceContainer = prepareForTestAgents(); agentServiceContainer.driftService = new TestDefService(); }
@Override protected void beforeMethod() throws Exception { systemManager = LookupUtil.getSystemManager(); // do this each method so it doesn't expire overlord = LookupUtil.getSubjectManager().getOverlord(); // we need this because the drift plugins are referenced from the system settings that we use in // our tests testServerPluginService = new TestServerPluginService(getTempDir()); prepareCustomServerPluginService(testServerPluginService); testServerPluginService.startMasterPluginContainer(); }
public String deleteSelectedRepoSubscriptions() { Subject subject = EnterpriseFacesContextUtility.getSubject(); String[] selected = getSelectedRepoSubscriptions(); int repoId = Integer.valueOf(FacesContextUtility.getRequiredRequestParameter("id")); int[] resourceIds = getIntegerArray(selected); if ((resourceIds != null) && (resourceIds.length > 0)) { try { RepoManagerLocal manager = LookupUtil.getRepoManagerLocal(); // TODO: we should have a SLSB method that takes a list of resources for (int resourceId : resourceIds) { manager.unsubscribeResourceFromRepos(subject, resourceId, new int[] {repoId}); } FacesContextUtility.addMessage( FacesMessage.SEVERITY_INFO, "Unsubscribed [" + resourceIds.length + "] resources from repository"); } catch (Exception e) { FacesContextUtility.addMessage( FacesMessage.SEVERITY_ERROR, "Failed to unsubscribe one or more resources from repository", e); } } return "success"; }
@Override @RequiredPermission(Permission.MANAGE_SETTINGS) public ServerDetails getServerDetails(Subject subject) { CoreServerMBean coreServerMBean = LookupUtil.getCoreServer(); ServerDetails serverDetails = new ServerDetails(); serverDetails.setProductInfo(getProductInfo(subject)); HashMap<Detail, String> details = serverDetails.getDetails(); DateFormat localTimeFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL); details.put(ServerDetails.Detail.SERVER_LOCAL_TIME, localTimeFormatter.format(new Date())); details.put(ServerDetails.Detail.SERVER_TIMEZONE, TimeZone.getDefault().getDisplayName()); details.put( ServerDetails.Detail.SERVER_HOME_DIR, coreServerMBean.getJBossServerHomeDir().getAbsolutePath()); details.put( ServerDetails.Detail.SERVER_INSTALL_DIR, coreServerMBean.getInstallDir().getAbsolutePath()); SystemDatabaseInformation dbInfo = SystemDatabaseInformation.getInstance(); details.put(ServerDetails.Detail.DATABASE_CONNECTION_URL, dbInfo.getDatabaseConnectionURL()); details.put(ServerDetails.Detail.DATABASE_DRIVER_NAME, dbInfo.getDatabaseDriverName()); details.put(ServerDetails.Detail.DATABASE_DRIVER_VERSION, dbInfo.getDatabaseDriverVersion()); details.put(ServerDetails.Detail.DATABASE_PRODUCT_NAME, dbInfo.getDatabaseProductName()); details.put(ServerDetails.Detail.DATABASE_PRODUCT_VERSION, dbInfo.getDatabaseProductVersion()); details.put(ServerDetails.Detail.SERVER_IDENTITY, serverManager.getServer().getName()); return serverDetails; }
@Override public Set<Resource> getResources(Set<Integer> resourceIds, boolean includeDescendants) { long start = System.currentTimeMillis(); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Set<Resource> resources = new HashSet<Resource>(); for (Integer resourceId : resourceIds) { Resource resource = resourceManager.getResourceTree(resourceId, includeDescendants); if (isVisibleInInventory(resource)) { resource = convertToPojoResource(resource, includeDescendants); cleanoutResource(resource); resources.add(resource); } } if (log.isDebugEnabled()) { log.debug( "Performance: get Resources [" + resourceIds + "], recursive=" + includeDescendants + ", timing (" + (System.currentTimeMillis() - start) + ")ms"); } return resources; }
/** * Returns true if any of the condition sets match an inventoried Resource. * * @param context * @return */ public boolean isActive(GlobalActivationContext context) { ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Subject subject = context.getSubject(); for (ResourceConditionSet rcs : this.resourceConditionSets) { ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterPluginName(rcs.getPluginName()); criteria.addFilterResourceTypeName(rcs.getResourceTypeName()); Set<Permission> requiredPermissions = rcs.getPermissions(); if (!((null == requiredPermissions) || requiredPermissions.isEmpty())) { Permission[] arr = requiredPermissions.toArray(new Permission[requiredPermissions.size()]); criteria.addRequiredPermissions(arr); } PageList<Resource> resources = resourceManager.findResourcesByCriteria(context.getSubject(), criteria); if (!((null == resources) || resources.isEmpty())) { return ActivatorHelper.areTraitsSatisfied( subject, rcs.getTraitMatchers(), resources, false); } } return false; }
private List<AutoGroupComposite> getResourceChildren(Resource resource, Subject subject) { ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); List<AutoGroupComposite> children = resourceManager.findChildrenAutoGroups(subject, resource.getId()); AutoGroupComposite resourceGroupComposite = resourceManager.getResourceAutoGroup(subject, resource.getId()); if (resourceGroupComposite != null) resourceGroupComposite.setMainResource(true); else return new ArrayList<AutoGroupComposite>(); // now increase everyone's depth by one to account for the resource for (AutoGroupComposite child : children) { child.setDepth(child.getDepth() + 1); } children.add(0, resourceGroupComposite); Resource parentResource = resourceManager.getParentResource(resource.getId()); AutoGroupComposite parentGroupComposite = null; if (parentResource != null) { parentGroupComposite = resourceManager.getResourceAutoGroup(subject, parentResource.getId()); } if (parentGroupComposite != null) { // now increase everyone's depth by one to account for the parent for (AutoGroupComposite child : children) { child.increaseDepth(1); } children.add(0, parentGroupComposite); } return children; }
public String associateSelectedContentSourcesWithRepo() { Subject subject = EnterpriseFacesContextUtility.getSubject(); String[] selected = getSelectedRepoUnsubscriptions(); int repoId = Integer.valueOf(FacesContextUtility.getRequiredRequestParameter("id")); int[] resourceIds = getIntegerArray(selected); if ((resourceIds != null) && (resourceIds.length > 0)) { try { RepoManagerLocal manager = LookupUtil.getRepoManagerLocal(); for (int resourceId : resourceIds) { manager.subscribeResourceToRepos(subject, resourceId, new int[] {repoId}); } FacesContextUtility.addMessage( FacesMessage.SEVERITY_INFO, "Subscribed [" + resourceIds.length + "] resources with repository"); } catch (Exception e) { FacesContextUtility.addMessage( FacesMessage.SEVERITY_ERROR, "Failed to subscribe one or more resources with repository", e); } } return "success"; }
public class GroupAlertDefinitionGWTServiceImpl extends AbstractGWTServiceImpl implements GroupAlertDefinitionGWTService { private static final long serialVersionUID = 1L; private GroupAlertDefinitionManagerLocal groupAlertDefManager = LookupUtil.getGroupAlertDefinitionManager(); @Override public int createGroupAlertDefinitions( AlertDefinition groupAlertDefinition, Integer resourceGroupId) throws RuntimeException { try { int results = groupAlertDefManager.createGroupAlertDefinitions( getSessionSubject(), groupAlertDefinition, resourceGroupId); return results; } catch (Throwable t) { throw getExceptionToThrowToClient(t); } } @Override public AlertDefinition updateGroupAlertDefinitions( AlertDefinition groupAlertDefinition, boolean purgeInternals) throws RuntimeException { try { AlertDefinition results = groupAlertDefManager.updateGroupAlertDefinitions( getSessionSubject(), groupAlertDefinition, purgeInternals); return SerialUtility.prepare(results, "updateGroupAlertDefinitions"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); } } }
/** * Encode the beginning of the given {@link ResourceLineageComponent}. * * @param facesContext the JSF context for the current request * @param component the {@link ResourceLineageComponent} to be encoded */ @Override public void encodeBegin(FacesContext facesContext, UIComponent component) throws IOException { ResourceLineageComponent resourceLineage = (ResourceLineageComponent) component; ResponseWriter writer = facesContext.getResponseWriter(); long monitorId = HibernatePerformanceMonitor.get().start(); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); List<Resource> ancestorResources = resourceManager.getResourceLineage(resourceLineage.getResourceId()); HibernatePerformanceMonitor.get().stop(monitorId, "ResourceLineage renderer"); if (ancestorResources.isEmpty()) { throw new IllegalStateException( "The list of ancestor resources should always contain at least one resource - the resource whose lineage was requested."); } Resource parentResource = ancestorResources.get(ancestorResources.size() - 1); for (Resource ancestorResource : ancestorResources) { writer.startElement("a", resourceLineage); writer.writeAttribute("href", buildURL(ancestorResource), null); writer.writeText(ancestorResource.getName(), null); writer.endElement("a"); if (ancestorResource.getId() != parentResource.getId()) // separator after every item except the last one { writer.writeText(SEPARATOR, null); } } }
public PageList<Resource> fetchDataForPage(PageControl pc) { Subject subject = EnterpriseFacesContextUtility.getSubject(); ResourceManagerLocal manager = LookupUtil.getResourceManager(); int repoId = Integer.parseInt(FacesContextUtility.getRequiredRequestParameter("id")); String search = FacesContextUtility.getOptionalRequestParameter( "repoUnsubscriptionsListForm:searchStringFilter"); String category = FacesContextUtility.getOptionalRequestParameter( "repoUnsubscriptionsListForm:searchCategoryFilter"); ResourceCategory categoryEnum = ResourceCategory.PLATFORM; if (search != null && search.trim().equals("")) { search = null; } if (category != null) { categoryEnum = ResourceCategory.valueOf(category); } PageList<Resource> results = manager.findAvailableResourcesForRepo(subject, repoId, search, categoryEnum, pc); // PageList<ResourceComposite> results = manager.findResourceComposites(subject, categoryEnum, // null, null, search, pc); return results; }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { BundleManagerLocal bundleManager = LookupUtil.getBundleManager(); SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); Subject overlord = subjectManager.getOverlord(); PageList<BundleDeployment> deployments = bundleManager.findBundleDeploymentsByCriteria(overlord, getCriteriaFromContext(context)); if (deployments.size() > 0) { BundleDeployment bundleDeployment = deployments.get(0); SchedulerLocal scheduler = LookupUtil.getSchedulerBean(); JobDetail jobDetail = context.getJobDetail(); BundleDeploymentStatus bundleDeploymentStatus = bundleManager.determineBundleDeploymentStatus(bundleDeployment.getId()); if (bundleDeploymentStatus.isTerminal()) { // delete this job, we've assigned a final status try { context.setResult(bundleDeploymentStatus); // Return status to possible listeners scheduler.deleteJob(jobDetail.getName(), jobDetail.getGroup()); } catch (SchedulerException e) { throw new JobExecutionException( "Could not delete the bundle deployment completion check job for " + bundleDeployment + ".", e); } } else { // try again in 10s try { Trigger trigger = QuartzUtil.getFireOnceOffsetTrigger(jobDetail, 10000L); // just need a trigger name unique for this job trigger.setName(String.valueOf(System.currentTimeMillis())); scheduler.scheduleJob(trigger); } catch (SchedulerException e) { throw new JobExecutionException( "Could not schedule the bundle deployment completion check job for " + bundleDeployment + ".", e); } } } }
public AgentConditionCache(int agentId) { super(); this.agentId = agentId; measurementDataCache = new HashMap<Integer, List<NumericDoubleCacheElement>>(); measurementTraitCache = new HashMap<Integer, List<MeasurementTraitCacheElement>>(); callTimeCache = new HashMap<Integer, List<CallTimeDataCacheElement>>(); eventsCache = new HashMap<Integer, List<EventCacheElement>>(); driftCache = new HashMap<Integer, List<DriftCacheElement>>(); alertConditionManager = LookupUtil.getAlertConditionManager(); measurementDataManager = LookupUtil.getMeasurementDataManager(); subjectManager = LookupUtil.getSubjectManager(); loadCachesForAgent(agentId); }
public PageList<Resource> fetchDataForPage(PageControl pc) { Subject subject = EnterpriseFacesContextUtility.getSubject(); int id = Integer.valueOf(FacesContextUtility.getRequiredRequestParameter("id")); RepoManagerLocal manager = LookupUtil.getRepoManagerLocal(); PageList<Resource> results = manager.findSubscribedResources(subject, id, pc); return results; }
/** Get the server purge configuration, loaded on startup. */ private static void loadPurgeDefaults() { LOG.debug("Loading default purge intervals"); try { Properties conf = LookupUtil.getSystemManager() .getSystemConfiguration(LookupUtil.getSubjectManager().getOverlord()); purge1h = Long.parseLong(conf.getProperty(RHQConstants.DataPurge1Hour)); purge6h = Long.parseLong(conf.getProperty(RHQConstants.DataPurge6Hour)); purge1d = Long.parseLong(conf.getProperty(RHQConstants.DataPurge1Day)); purgeRt = Long.parseLong(conf.getProperty(RHQConstants.RtDataPurge)); purgeAlert = Long.parseLong(conf.getProperty(RHQConstants.AlertPurge)); } catch (Exception e) { // Shouldn't happen unless manual edit of config table // throw new IllegalArgumentException("Invalid purge interval: " + e); } }
@Override public void setResourceError(ResourceError resourceError) { try { ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); resourceManager.addResourceError(resourceError); } catch (RuntimeException re) { log.error("Failed to persist Resource error [" + resourceError + "].", re); throw re; } }
/** Throws a permission exception if the user is not allowed to access this functionality. */ private void hasPermission() { Subject subject = EnterpriseFacesContextUtility.getSubject(); if (!LookupUtil.getAuthorizationManager() .hasGlobalPermission(subject, Permission.MANAGE_INVENTORY)) { throw new PermissionException( "User [" + subject.getName() + "] does not have the proper permissions to view or manage agents"); } }
/** * Starts the server-side plugin container. * * @throws RuntimeException */ private void startServerPluginContainer() throws RuntimeException { log.info("Starting the master server plugin container..."); try { ServerPluginServiceMBean mbean = LookupUtil.getServerPluginService(); mbean.startMasterPluginContainerWithoutSchedulingJobs(); } catch (Exception e) { throw new RuntimeException("Cannot start the master server plugin container!", e); } }
/** @see DiscoveryServerService#mergeInventoryReport(InventoryReport) */ @Override public MergeInventoryReportResults mergeInventoryReport(InventoryReport report) throws InvalidInventoryReportException, StaleTypeException { InventoryReportSerializer.getSingleton().lock(report.getAgent().getName()); try { long start = System.currentTimeMillis(); DiscoveryBossLocal discoveryBoss = LookupUtil.getDiscoveryBoss(); MergeInventoryReportResults results; try { results = discoveryBoss.mergeInventoryReport(report); } catch (StaleTypeException e) { // There is no need to log this exception as it is part of a normal work flow // that occurs as a result of a user deleting a plugin. DiscoveryBossBean // already logs a message about the stale types that can be useful for // debugging; so, we just need to propagate the exception to the agent. throw e; } catch (InvalidInventoryReportException e) { Agent agent = report.getAgent(); if (log.isDebugEnabled()) { log.error("Received invalid inventory report from agent [" + agent + "]", e); } else { /* * this is expected when the platform is uninventoried, because the agent often has in-flight reports * going to the server at the time the platform's agent is being deleted from the database */ log.error( "Received invalid inventory report from agent [" + agent + "]: " + e.getMessage()); } throw e; } catch (RuntimeException e) { log.error( "Fatal error occurred during merging of inventory report from agent [" + report.getAgent() + "].", e); throw e; } long elapsed = (System.currentTimeMillis() - start); if (elapsed > 30000L) { log.warn("Performance: inventory merge (" + elapsed + ")ms"); } else { if (log.isDebugEnabled()) { log.debug("Performance: inventory merge (" + elapsed + ")ms"); } } return results; } finally { InventoryReportSerializer.getSingleton().unlock(report.getAgent().getName()); } }
@Override protected void beforeMethod() throws Exception { digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); jpaDriftServer = LookupUtil.getJPADriftServer(); driftManager = LookupUtil.getDriftManager(); overlord = LookupUtil.getSubjectManager().getOverlord(); driftServerService = new DriftServerServiceImpl(); TestServerCommunicationsService agentServiceContainer = prepareForTestAgents(); agentServiceContainer.driftService = new TestDefService(); prepareScheduler(); DriftServerPluginService driftServerPluginService = new DriftServerPluginService(getTempDir()); prepareCustomServerPluginService(driftServerPluginService); driftServerPluginService.masterConfig.getPluginDirectory().mkdirs(); deleteDriftFiles(); newResource = createNewResource(); }
/** @author Jason Dobies */ public class AffinityGroupSubscribedServersUIBean extends PagedDataTableUIBean { public static final String MANAGED_BEAN_NAME = "AffinityGroupSubscribedServersUIBean"; private AffinityGroupManagerLocal affinityGroupManager = LookupUtil.getAffinityGroupManager(); public String unsubscribeServers() { Subject subject = EnterpriseFacesContextUtility.getSubject(); String[] selectedServerIdStrings = FacesContextUtility.getRequest().getParameterValues("selectedServersToUnsubscribe"); // Parse the server IDs to ints Integer[] selectedServerIds = new Integer[selectedServerIdStrings.length]; for (int ii = 0; ii < selectedServerIdStrings.length; ii++) { selectedServerIds[ii] = Integer.parseInt(selectedServerIdStrings[ii]); } // Update the group affinityGroupManager.removeServersFromGroup(subject, selectedServerIds); return "successOrFailure"; } @Override public DataModel getDataModel() { if (dataModel == null) { dataModel = new AffinityGroupSubscribedServersDataModel( PageControlView.AffinityGroupSubscribedServers, MANAGED_BEAN_NAME); } return dataModel; } private class AffinityGroupSubscribedServersDataModel extends PagedListDataModel<Server> { private AffinityGroupSubscribedServersDataModel(PageControlView view, String beanName) { super(view, beanName); } @Override public PageList<Server> fetchPage(PageControl pc) { int affinityGroupId = FacesContextUtility.getRequiredRequestParameter("affinityGroupId", Integer.class); PageList<Server> results = affinityGroupManager.getServerMembers(getSubject(), affinityGroupId, pc); return results; } } }
@Override public List<Resource> getResourcesAsList(Integer... resourceIds) { long start = System.currentTimeMillis(); ResourceCriteria criteria = new ResourceCriteria(); // get all of the resources for the supplied ids criteria.addFilterIds(resourceIds); // filter out any that are not actually in inventory criteria.addFilterInventoryStatuses( new ArrayList<InventoryStatus>(InventoryStatus.getInInventorySet())); // get all of them, don't limit to default paging criteria.clearPaging(); criteria.fetchResourceType(true); criteria.fetchPluginConfiguration(true); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Subject overlord = LookupUtil.getSubjectManager().getOverlord(); List<Resource> result = resourceManager.findResourcesByCriteria(overlord, criteria); if (log.isDebugEnabled()) { log.debug( "Performance: get ResourcesAsList [" + resourceIds + "], timing (" + (System.currentTimeMillis() - start) + ")ms"); } // Now do some clean out of stuff the agent does not need // Perhaps we should limit the query above to only return relevant stuff for (Resource resource : result) { cleanoutResource(resource); } return result; }
@Override public Map<Integer, InventoryStatus> getInventoryStatus(int rootResourceId, boolean descendents) { long start = System.currentTimeMillis(); ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); Map<Integer, InventoryStatus> statuses = resourceManager.getResourceStatuses(rootResourceId, descendents); if (log.isDebugEnabled()) { log.debug( "Performance: get inventory statuses for [" + statuses.size() + "] timing (" + (System.currentTimeMillis() - start) + ")ms"); } return statuses; }
@Override public boolean mergeAvailabilityReport(AvailabilityReport availabilityReport) { AvailabilityReportSerializer.getSingleton().lock(availabilityReport.getAgentName()); try { String reportToString = availabilityReport.toString(false); if (log.isDebugEnabled()) log.debug("Processing " + reportToString); long start = System.currentTimeMillis(); AvailabilityManagerLocal availabilityManager = LookupUtil.getAvailabilityManager(); boolean ok = availabilityManager.mergeAvailabilityReport(availabilityReport); long elapsed = (System.currentTimeMillis() - start); if (elapsed > 20000L) { log.warn( "Performance: processed " + reportToString + " - needFull=[" + !ok + "] in (" + elapsed + ")ms"); } else { if (log.isDebugEnabled()) { log.debug( "Performance: processed " + reportToString + " - needFull=[" + !ok + "] in (" + elapsed + ")ms"); } } return ok; } catch (Exception e) { log.info( "Error processing availability report from [" + availabilityReport.getAgentName() + "]: " + ThrowableUtil.getAllMessages(e)); return true; // not sure what happened, but avoid infinite recursion during error conditions; // do not ask for a full report } finally { AvailabilityReportSerializer.getSingleton().unlock(availabilityReport.getAgentName()); } }