public void start(ResourceContext<PlatformComponent> resourceContext) { if (resourceContext.getSystemInformation().isNative()) { cpuInformation = resourceContext .getSystemInformation() .getCpu(Integer.parseInt(resourceContext.getResourceKey())); cpuCache = new HashMap<String, CpuEntry>(); startCpuEntry = new CpuEntry(cpuInformation.getCpu()); } return; }
/** Start the resource connection */ @Override public void start(ResourceContext<CacheManagerComponent> context) { this.context = context; this.cacheManagerName = context.getParentResourceComponent().context.getResourceKey(); this.cacheName = context.getResourceKey(); if (log.isTraceEnabled()) log.trace( "Start cache component for cache manager " + cacheManagerName + " with cache key " + cacheName); }
protected void internalStart() throws Exception { Configuration pluginConfig = context.getPluginConfiguration(); String connectionTypeDescriptorClassName = pluginConfig.getSimple(JMXDiscoveryComponent.CONNECTION_TYPE).getStringValue(); if (JMXDiscoveryComponent.PARENT_TYPE.equals(connectionTypeDescriptorClassName)) { // Our parent is itself a JMX component, so just reuse its connection. this.connection = ((JMXComponent) context.getParentResourceComponent()).getEmsConnection(); this.connectionProvider = this.connection.getConnectionProvider(); } else { this.connectionProvider = ConnectionProviderFactory.createConnectionProvider( pluginConfig, this.context.getNativeProcess(), this.context.getTemporaryDirectory()); this.connection = this.connectionProvider.connect(); this.connection.loadSynchronous(false); } }
public Configuration loadResourceConfiguration() throws Exception { ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition(); ConfigurationLoadDelegate delegate = new ConfigurationLoadDelegate(configDef, connection, address); return delegate.loadResourceConfiguration(); }
public void updateResourceConfiguration(ConfigurationUpdateReport report) { ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition(); ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(configDef, connection, address); delegate.updateResourceConfiguration(report); }
/** * Returns an instantiated and loaded versions store access point. * * @return will not be <code>null</code> */ private org.rhq.core.pluginapi.content.version.PackageVersions loadPackageVersions() { if (this.versions == null) { ResourceType resourceType = resourceContext.getResourceType(); String pluginName = resourceType.getPlugin(); File dataDirectoryFile = resourceContext.getDataDirectory(); dataDirectoryFile.mkdirs(); String dataDirectory = dataDirectoryFile.getAbsolutePath(); log.trace( "Creating application versions store with plugin name [" //$NON-NLS-1$ + pluginName + "] and data directory [" + dataDirectory //$NON-NLS-1$ + "]"); //$NON-NLS-1$ this.versions = new PackageVersions(pluginName, dataDirectory); this.versions.loadFromDisk(); } return this.versions; }
public AvailabilityType getAvailability() { if (connectionProvider == null || !connectionProvider.isConnected()) { try { internalStart(); } catch (Exception e) { log.debug( "Still unable to reconnect to " + context.getResourceType() + "[" + context.getResourceKey() + "] due to error: " + e); } } return ((connectionProvider != null) && connectionProvider.isConnected()) ? AvailabilityType.UP : AvailabilityType.DOWN; }
public void start(ResourceContext context) throws Exception { this.context = context; log.debug( "Starting connection to " + context.getResourceType() + "[" + context.getResourceKey() + "]..."); // If connecting to the EMS fails, log a warning but still succeed in starting. getAvailablity() // will keep // trying to connect each time it is called. try { internalStart(); } catch (Exception e) { log.warn( "Failed to connect to " + context.getResourceType() + "[" + context.getResourceKey() + "].", e); } if (connection == null) { log.warn( "Unable to connect to " + context.getResourceType() + "[" + context.getResourceKey() + "]."); } }
/** * The plugin container will call this method when it has a new configuration for your managed * resource. Your plugin will re-configure the managed resource in your own custom way, setting * its configuration based on the new values of the given configuration. * * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport) */ public void updateResourceConfiguration(ConfigurationUpdateReport report) { resourceConfiguration = report.getConfiguration().deepCopy(); Configuration resourceConfig = report.getConfiguration(); ManagementView managementView = null; ComponentType componentType = null; if (this.getComponentType().equals(PluginConstants.ComponentType.VDB.NAME)) { componentType = new ComponentType( PluginConstants.ComponentType.VDB.TYPE, PluginConstants.ComponentType.VDB.SUBTYPE); } else { report.setStatus(ConfigurationUpdateStatus.FAILURE); report.setErrorMessage("Update not implemented for the component type."); // $NON-NLS-1$ } ManagedComponent managedComponent = null; report.setStatus(ConfigurationUpdateStatus.SUCCESS); try { managementView = getConnection().getManagementView(); managedComponent = managementView.getComponent(this.name, componentType); Map<String, ManagedProperty> managedProperties = managedComponent.getProperties(); ProfileServiceUtil.convertConfigurationToManagedProperties( managedProperties, resourceConfig, resourceContext.getResourceType(), null); try { managementView.updateComponent(managedComponent); } catch (Exception e) { LOG.error( "Unable to update component [" //$NON-NLS-1$ + managedComponent.getName() + "] of type " //$NON-NLS-1$ + componentType + ".", e); //$NON-NLS-1$ report.setStatus(ConfigurationUpdateStatus.FAILURE); report.setErrorMessageFromThrowable(e); } } catch (Exception e) { LOG.error("Unable to process update request", e); // $NON-NLS-1$ report.setStatus(ConfigurationUpdateStatus.FAILURE); report.setErrorMessageFromThrowable(e); } }
/** * Deploy content to the remote server - this is one half of #createResource * * @param report Create resource report that tells us what to do * @return report that tells us what has been done. */ protected CreateResourceReport deployContent(CreateResourceReport report) { ContentContext cctx = context.getContentContext(); ResourcePackageDetails details = report.getPackageDetails(); ContentServices contentServices = cctx.getContentServices(); String resourceTypeName = report.getResourceType().getName(); ASUploadConnection uploadConnection = new ASUploadConnection(host, port); OutputStream out = uploadConnection.getOutputStream(details.getFileName()); contentServices.downloadPackageBitsForChildResource( cctx, resourceTypeName, details.getKey(), out); JsonNode uploadResult = uploadConnection.finishUpload(); if (verbose) log.info(uploadResult); if (ASUploadConnection.isErrorReply(uploadResult)) { report.setStatus(CreateResourceStatus.FAILURE); report.setErrorMessage(ASUploadConnection.getFailureDescription(uploadResult)); return report; } String fileName = details.getFileName(); if (fileName.startsWith( "C:\\fakepath\\")) { // TODO this is a hack as the server adds the fake path somehow fileName = fileName.substring("C:\\fakepath\\".length()); } String tmpName = fileName; // TODO figure out the tmp-name biz with the AS guys JsonNode resultNode = uploadResult.get("result"); String hash = resultNode.get("BYTES_VALUE").getTextValue(); return runDeploymentMagicOnServer(report, fileName, tmpName, hash); }
/** * Start the resource connection * * @see * org.rhq.core.pluginapi.inventory.ResourceComponent#start(org.rhq.core.pluginapi.inventory.ResourceContext) */ public void start(ResourceContext context) throws InvalidPluginConfigurationException, Exception { this.context = context; pluginConfiguration = context.getPluginConfiguration(); if (!(context.getParentResourceComponent() instanceof BaseComponent)) { host = pluginConfiguration.getSimpleValue("hostname", LOCALHOST); String portString = pluginConfiguration.getSimpleValue("port", DEFAULT_HTTP_MANAGEMENT_PORT); port = Integer.parseInt(portString); connection = new ASConnection(host, port); } else { connection = ((BaseComponent) context.getParentResourceComponent()).getASConnection(); } path = pluginConfiguration.getSimpleValue("path", null); address = new Address(path); key = context.getResourceKey(); myServerName = context.getResourceKey().substring(context.getResourceKey().lastIndexOf("/") + 1); }
@Override public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, Exception { if (!name.contains(":")) { OperationResult badName = new OperationResult("Operation name did not contain a ':'"); badName.setErrorMessage("Operation name did not contain a ':'"); return badName; } int colonPos = name.indexOf(':'); String what = name.substring(0, colonPos); String op = name.substring(colonPos + 1); Operation operation = null; Address theAddress = new Address(); if (what.equals("server-group")) { String groupName = parameters.getSimpleValue("name", ""); String profile = parameters.getSimpleValue("profile", "default"); theAddress.add("server-group", groupName); operation = new Operation(op, theAddress); operation.addAdditionalProperty("profile", profile); } else if (what.equals("server")) { if (context.getResourceType().getName().equals("JBossAS-Managed")) { String host = pluginConfiguration.getSimpleValue("domainHost", "local"); theAddress.add("host", host); theAddress.add("server-config", myServerName); operation = new Operation(op, theAddress); } else if (context.getResourceType().getName().equals("Host")) { theAddress.add(address); String serverName = parameters.getSimpleValue("name", null); theAddress.add("server-config", serverName); Map<String, Object> props = new HashMap<String, Object>(); String serverGroup = parameters.getSimpleValue("group", null); props.put("group", serverGroup); if (op.equals("add")) { props.put("name", serverName); boolean autoStart = parameters.getSimple("auto-start").getBooleanValue(); props.put("auto-start", autoStart); // TODO put more properties in } operation = new Operation(op, theAddress, props); } else { operation = new Operation(op, theAddress); } } else if (what.equals("destination")) { theAddress.add(address); String newName = parameters.getSimpleValue("name", ""); String type = parameters.getSimpleValue("type", "jms-queue").toLowerCase(); theAddress.add(type, newName); PropertyList jndiNamesProp = parameters.getList("entries"); if (jndiNamesProp == null || jndiNamesProp.getList().isEmpty()) { OperationResult fail = new OperationResult(); fail.setErrorMessage("No jndi bindings given"); return fail; } List<String> jndiNames = new ArrayList<String>(); for (Property p : jndiNamesProp.getList()) { PropertySimple ps = (PropertySimple) p; jndiNames.add(ps.getStringValue()); } operation = new Operation(op, theAddress); operation.addAdditionalProperty("entries", jndiNames); if (type.equals("jms-queue")) { PropertySimple ps = (PropertySimple) parameters.get("durable"); if (ps != null) { boolean durable = ps.getBooleanValue(); operation.addAdditionalProperty("durable", durable); } String selector = parameters.getSimpleValue("selector", ""); if (!selector.isEmpty()) operation.addAdditionalProperty("selector", selector); } } else if (what.equals("managed-server")) { String chost = parameters.getSimpleValue("hostname", ""); String serverName = parameters.getSimpleValue("servername", ""); String serverGroup = parameters.getSimpleValue("server-group", ""); String socketBindings = parameters.getSimpleValue("socket-bindings", ""); String portS = parameters.getSimpleValue("port-offset", "0"); int port = Integer.parseInt(portS); String autostartS = parameters.getSimpleValue("auto-start", "false"); boolean autoStart = Boolean.getBoolean(autostartS); theAddress.add("host", chost); theAddress.add("server-config", serverName); Map<String, Object> props = new HashMap<String, Object>(); props.put("name", serverName); props.put("group", serverGroup); props.put("socket-binding-group", socketBindings); props.put("socket-binding-port-offset", port); props.put("auto-start", autoStart); operation = new Operation(op, theAddress, props); } else if (what.equals("domain")) { operation = new Operation(op, new Address()); } else if (what.equals("domain-deployment")) { if (op.equals("promote")) { String serverGroup = parameters.getSimpleValue("server-group", "-not set-"); List<String> serverGroups = new ArrayList<String>(); if (serverGroup.equals("__all")) { serverGroups.addAll(getServerGroups()); } else { serverGroups.add(serverGroup); } String resourceKey = context.getResourceKey(); resourceKey = resourceKey.substring(resourceKey.indexOf("=") + 1); log.info( "Promoting [" + resourceKey + "] to server group(s) [" + Arrays.asList(serverGroups) + "]"); PropertySimple simple = parameters.getSimple("enabled"); Boolean enabled = false; if (simple != null && simple.getBooleanValue() != null) enabled = simple.getBooleanValue(); operation = new CompositeOperation(); for (String theGroup : serverGroups) { theAddress = new Address(); theAddress.add("server-group", theGroup); theAddress.add("deployment", resourceKey); Operation step = new Operation("add", theAddress); step.addAdditionalProperty("enabled", enabled); ((CompositeOperation) operation).addStep(step); } } } else if (what.equals("naming")) { if (op.equals("jndi-view")) { theAddress.add(address); operation = new Operation("jndi-view", theAddress); } } OperationResult operationResult = new OperationResult(); if (operation != null) { Result result = connection.execute(operation); if (!result.isSuccess()) { operationResult.setErrorMessage(result.getFailureDescription()); } else { String tmp; if (result.getResult() == null) tmp = "-none provided by the server-"; else tmp = result.getResult().toString(); operationResult.setSimpleResult(tmp); } } else { operationResult.setErrorMessage("No valid operation was given for input [" + name + "]"); } return operationResult; }
/** * Do the actual fumbling with the domain api to deploy the uploaded content * * @param report CreateResourceReport to report the result * @param runtimeName File name to use as runtime name * @param deploymentName Name of the deployment * @param hash Hash of the content bytes * @return the passed report with success or failure settings */ public CreateResourceReport runDeploymentMagicOnServer( CreateResourceReport report, String runtimeName, String deploymentName, String hash) { boolean toServerGroup = context.getResourceKey().contains("server-group="); log.info("Deploying [" + runtimeName + "] to domain only= " + !toServerGroup + " ..."); ASConnection connection = getASConnection(); Operation step1 = new Operation("add", "deployment", deploymentName); // step1.addAdditionalProperty("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); List<Object> content = new ArrayList<Object>(1); Map<String, Object> contentValues = new HashMap<String, Object>(); contentValues.put("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); content.add(contentValues); step1.addAdditionalProperty("content", content); step1.addAdditionalProperty("name", deploymentName); step1.addAdditionalProperty("runtime-name", runtimeName); String resourceKey; Result result; CompositeOperation cop = new CompositeOperation(); cop.addStep(step1); /* * We need to check here if this is an upload to /deployment only * or if this should be deployed to a server group too */ if (!toServerGroup) { // if standalone, then :deploy the deployment anyway if (context.getResourceType().getName().contains("Standalone")) { Operation step2 = new Operation("deploy", step1.getAddress()); cop.addStep(step2); } result = connection.execute(cop); resourceKey = step1.getAddress().getPath(); } else { Address serverGroupAddress = new Address(context.getResourceKey()); serverGroupAddress.add("deployment", deploymentName); Operation step2 = new Operation("add", serverGroupAddress); cop.addStep(step2); Operation step3 = new Operation("deploy", serverGroupAddress); cop.addStep(step3); resourceKey = serverGroupAddress.getPath(); if (verbose) log.info("Deploy operation: " + cop); result = connection.execute(cop); } if ((!result.isSuccess())) { String failureDescription = result.getFailureDescription(); report.setErrorMessage(failureDescription); report.setStatus(CreateResourceStatus.FAILURE); log.warn(" ... done with failure: " + failureDescription); } else { report.setStatus(CreateResourceStatus.SUCCESS); report.setResourceName(runtimeName); report.setResourceKey(resourceKey); log.info(" ... with success and key [" + resourceKey + "]"); } return report; }
/** * This is called when your component has been started with the given context. You normally * initialize some internal state of your component as well as attempt to make a stateful * connection to your managed resource. * * @see ResourceComponent#start(ResourceContext) */ public void start(ResourceContext context) { resourceContext = context; deploymentName = context.getResourceKey(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void updateResourceConfigurationWithName() throws Exception { // tell the method story as it happens: mock or create dependencies and configure // those dependencies to get the method under test to completion. ResourceContext mockResourceContext = mock(ResourceContext.class); ResourceType mockResourceType = mock(ResourceType.class); when(mockResourceContext.getResourceType()).thenReturn(mockResourceType); ConfigurationDefinition mockConfigurationDefinition = mock(ConfigurationDefinition.class); when(mockResourceType.getResourceConfigurationDefinition()) .thenReturn(mockConfigurationDefinition); ConfigurationDefinition mockConfigurationDefinitionCopy = mock(ConfigurationDefinition.class); when(mockConfigurationDefinition.copy()).thenReturn(mockConfigurationDefinitionCopy); ConfigurationTemplate mockConfigurationTemplate = mock(ConfigurationTemplate.class); when(mockConfigurationDefinitionCopy.getDefaultTemplate()) .thenReturn(mockConfigurationTemplate); Configuration mockConfiguration = mock(Configuration.class); when(mockConfigurationTemplate.getConfiguration()).thenReturn(mockConfiguration); Property mockProperty = mock(Property.class); when(mockConfiguration.get(eq("__type"))).thenReturn(null); when(mockConfiguration.get(eq("__name"))).thenReturn(mockProperty); Map<String, PropertyDefinition> mockMap = (Map<String, PropertyDefinition>) mock(Map.class); when(mockConfigurationDefinitionCopy.getPropertyDefinitions()).thenReturn(mockMap); ConfigurationUpdateReport mockReport = mock(ConfigurationUpdateReport.class); when(mockReport.getConfiguration()).thenReturn(mockConfiguration); ConfigurationWriteDelegate mockConfigurationWriteDelegate = mock(ConfigurationWriteDelegate.class); PowerMockito.whenNew(ConfigurationWriteDelegate.class) .withParameterTypes(ConfigurationDefinition.class, ASConnection.class, Address.class) .withArguments( any(ConfigurationDefinition.class), any(ASConnection.class), any(Address.class)) .thenReturn(mockConfigurationWriteDelegate); ASConnection mockASConnection = mock(ASConnection.class); when(mockASConnection.execute(any(ReadResource.class))).thenReturn(new Result()); // create object to test and inject required dependencies TemplatedComponent objectUnderTest = new TemplatedComponent(); objectUnderTest.context = mockResourceContext; objectUnderTest.testConnection = mockASConnection; // run code under test objectUnderTest.updateResourceConfiguration(mockReport); // verify the results (Assert and mock verification) verify(mockMap, times(1)).remove(eq("__name")); verify(mockConfiguration, times(1)).get(eq("__type")); verify(mockConfiguration, times(1)).get(eq("__name")); verify(mockConfiguration, times(1)).remove(eq("__name")); PowerMockito.verifyNew(ConfigurationWriteDelegate.class) .withArguments( any(ConfigurationDefinition.class), eq(mockASConnection), any(Address.class)); }
private EmsConnection getConnection() { return context.getParentResourceComponent().getEmsConnection(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void loadResourceConfigurationWithType() throws Exception { // tell the method story as it happens: mock or create dependencies and configure // those dependencies to get the method under test to completion. ResourceContext mockResourceContext = mock(ResourceContext.class); ResourceType mockResourceType = mock(ResourceType.class); when(mockResourceContext.getResourceType()).thenReturn(mockResourceType); ConfigurationDefinition mockConfigurationDefinition = mock(ConfigurationDefinition.class); when(mockResourceType.getResourceConfigurationDefinition()) .thenReturn(mockConfigurationDefinition); ConfigurationTemplate mockConfigurationTemplate = mock(ConfigurationTemplate.class); when(mockConfigurationDefinition.getDefaultTemplate()).thenReturn(mockConfigurationTemplate); Configuration mockConfiguration = mock(Configuration.class); when(mockConfigurationTemplate.getConfiguration()).thenReturn(mockConfiguration); Property mockProperty = mock(Property.class); when(mockConfiguration.get(eq("__type"))).thenReturn(mockProperty); Map<String, PropertyDefinition> mockMap = (Map<String, PropertyDefinition>) mock(Map.class); when(mockConfigurationDefinition.getPropertyDefinitions()).thenReturn(mockMap); ConfigurationLoadDelegate mockConfigurationLoadDelegate = mock(ConfigurationLoadDelegate.class); PowerMockito.whenNew(ConfigurationLoadDelegate.class) .withParameterTypes(ConfigurationDefinition.class, ASConnection.class, Address.class) .withArguments( any(ConfigurationDefinition.class), any(ASConnection.class), any(Address.class)) .thenReturn(mockConfigurationLoadDelegate); when(mockConfigurationLoadDelegate.loadResourceConfiguration()).thenReturn(mockConfiguration); PropertySimple pathPropertySimple = new PropertySimple("path", "abc=def,xyz=test1"); when(mockConfiguration.get(eq("path"))).thenReturn(pathPropertySimple); when(mockResourceContext.getPluginConfiguration()).thenReturn(mockConfiguration); ASConnection mockASConnection = mock(ASConnection.class); PropertySimple typePropertySimple = new PropertySimple("__type", "xyz"); PowerMockito.whenNew(PropertySimple.class) .withParameterTypes(String.class, Object.class) .withArguments(eq("__type"), eq("xyz")) .thenReturn(typePropertySimple); // create object to test and inject required dependencies TemplatedComponent objectUnderTest = new TemplatedComponent(); objectUnderTest.context = mockResourceContext; objectUnderTest.testConnection = mockASConnection; // run code under test Configuration result = objectUnderTest.loadResourceConfiguration(); // verify the results (Assert and mock verification) Assert.assertEquals(result, mockConfiguration); verify(mockMap, times(1)).remove(eq("__type")); verify(mockConfiguration, times(1)).get(eq("__type")); verify(mockConfiguration, never()).get(eq("__name")); verify(mockConfiguration, times(1)).get(eq("path")); verify(mockConfiguration, times(1)).put(eq(typePropertySimple)); PowerMockito.verifyNew(PropertySimple.class).withArguments(eq("__type"), eq("xyz")); PowerMockito.verifyNew(ConfigurationLoadDelegate.class) .withArguments( any(ConfigurationDefinition.class), eq(mockASConnection), any(Address.class)); }