http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/NoStatisticsFoundException.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/NoStatisticsFoundException.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/NoStatisticsFoundException.java new file mode 100644 index 0000000..fc097df --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/NoStatisticsFoundException.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.exceptions; + +/** + * No statistics found exception. + */ +public class NoStatisticsFoundException extends Exception { +}
http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/StopStatisticsPublishingException.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/StopStatisticsPublishingException.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/StopStatisticsPublishingException.java new file mode 100644 index 0000000..3d61213 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/exceptions/StopStatisticsPublishingException.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.exceptions; + +/** + * Stop statistics publishing exception. + */ +public class StopStatisticsPublishingException extends Exception { +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/MockIaasServiceComponent.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/MockIaasServiceComponent.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/MockIaasServiceComponent.java new file mode 100644 index 0000000..3eda43f --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/MockIaasServiceComponent.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.persistence.PersistenceManager; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerFactory; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerType; +import org.apache.stratos.mock.iaas.services.MockIaasService; +import org.apache.stratos.mock.iaas.services.impl.MockIaasServiceImpl; +import org.apache.stratos.mock.iaas.services.impl.MockIaasServiceUtil; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.registry.core.session.UserRegistry; + +/** + * + * @scr.component name="org.apache.stratos.mock.iaas.internal.MockIaasServiceComponent" immediate="true" + * @scr.reference name="registry.service" interface="org.wso2.carbon.registry.core.service.RegistryService" + * cardinality="1..1" policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" + */ +public class MockIaasServiceComponent { + + private static final Log log = LogFactory.getLog(MockIaasServiceComponent.class); + + protected void activate(ComponentContext context) { + try { + PersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager(PersistenceManagerType.Registry); + MockIaasServiceUtil mockIaasServiceUtil = new MockIaasServiceUtil(persistenceManager); + mockIaasServiceUtil.startInstancesPersisted(); + + MockIaasService mockIaasService = new MockIaasServiceImpl(); + context.getBundleContext().registerService(MockIaasService.class.getName(), mockIaasService, null); + log.info("Mock IaaS service registered"); + + log.info("Mock IaaS service component activated"); + } catch (Exception e) { + log.error("An error occurred when starting mock instances", e); + } + } + + protected void deactivate(ComponentContext context) { + } + + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Setting the Registry Service"); + } + + try { + UserRegistry registry = registryService.getGovernanceSystemRegistry(); + ServiceReferenceHolder.getInstance().setRegistry(registry); + } catch (RegistryException e) { + String msg = "Failed when retrieving Governance System Registry."; + log.error(msg, e); + } + } + + protected void unsetRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting the Registry Service"); + } + ServiceReferenceHolder.getInstance().setRegistry(null); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/ServiceReferenceHolder.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/ServiceReferenceHolder.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/ServiceReferenceHolder.java new file mode 100644 index 0000000..1d75f8a --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/internal/ServiceReferenceHolder.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.internal; + +import org.wso2.carbon.registry.core.session.UserRegistry; + +/** + * Mock iaas service reference holder. + */ +public class ServiceReferenceHolder { + + private static volatile ServiceReferenceHolder instance; + private UserRegistry registry; + + private ServiceReferenceHolder() { + } + + public static ServiceReferenceHolder getInstance() { + if (instance == null) { + synchronized (ServiceReferenceHolder.class) { + if(instance == null) { + instance = new ServiceReferenceHolder(); + } + } + } + return instance; + } + + public void setRegistry(UserRegistry registry) { + this.registry = registry; + } + + public UserRegistry getRegistry() { + return registry; + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/MockPersistenceManager.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/MockPersistenceManager.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/MockPersistenceManager.java new file mode 100644 index 0000000..26241b0 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/MockPersistenceManager.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.persistence; + +import org.wso2.carbon.registry.core.exceptions.RegistryException; + +import java.io.Serializable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Mock persistence manager. + */ +public class MockPersistenceManager implements PersistenceManager { + + private Map<String, Serializable> resourcePathToObjectMap; + + MockPersistenceManager() { + resourcePathToObjectMap = new ConcurrentHashMap<String, Serializable>(); + } + + @Override + public void persist(String resourcePath, Serializable serializableObject) throws RegistryException { + resourcePathToObjectMap.put(resourcePath, serializableObject); + } + + @Override + public Object read(String resourcePath) throws RegistryException { + return resourcePathToObjectMap.get(resourcePath); + } + + @Override + public void remove(String resourcePath) throws RegistryException { + resourcePathToObjectMap.remove(resourcePath); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManager.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManager.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManager.java new file mode 100644 index 0000000..9cd2df1 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManager.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.persistence; + +import org.wso2.carbon.registry.core.exceptions.RegistryException; + +import java.io.Serializable; + +/** + * Persistence manager interface. + */ +public interface PersistenceManager { + + void persist(String resourcePath, Serializable serializableObject) throws RegistryException; + + Object read(String resourcePath) throws RegistryException; + + void remove(String resourcePath) throws RegistryException; +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerFactory.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerFactory.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerFactory.java new file mode 100644 index 0000000..85c7d34 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerFactory.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.persistence; + +/** + * Persistence manager factory. + */ +public class PersistenceManagerFactory { + + public static PersistenceManager getPersistenceManager(PersistenceManagerType persistenceManagerType) { + if(persistenceManagerType == PersistenceManagerType.Registry) { + return new RegistryManager(); + } + else if(persistenceManagerType == PersistenceManagerType.Mock) { + return new MockPersistenceManager(); + } + throw new RuntimeException("Invalid persistence manager type"); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerType.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerType.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerType.java new file mode 100644 index 0000000..3308354 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/PersistenceManagerType.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.persistence; + +/** + * Persistence manager type enumeration. + */ +public enum PersistenceManagerType { + Registry, Mock +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/RegistryManager.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/RegistryManager.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/RegistryManager.java new file mode 100644 index 0000000..c566049 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/persistence/RegistryManager.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.persistence; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.internal.ServiceReferenceHolder; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.Resource; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.io.*; + +/** + * Registry manager provides functionality for persisting resources in the registry and reading them back. + */ +public class RegistryManager implements PersistenceManager { + + private final static Log log = LogFactory.getLog(RegistryManager.class); + + RegistryManager() { + } + + /** + * Persist a serializable object in the registry with the given resource path. + * + * @param serializableObject object to be persisted. + */ + @Override + public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException { + if(log.isDebugEnabled()) { + log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath)); + } + + Registry registry = getRegistry(); + + try { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + + registry.beginTransaction(); + + Resource nodeResource = registry.newResource(); + nodeResource.setContent(serializeToByteArray(serializableObject)); + registry.put(resourcePath, nodeResource); + + registry.commitTransaction(); + + if(log.isDebugEnabled()) { + log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s", + resourcePath)); + } + } catch (Exception e) { + String msg = "Failed to persist resource in registry: " + resourcePath; + registry.rollbackTransaction(); + log.error(msg, e); + throw new RegistryException(msg, e); + } + } + + /** + * Returns an object stored in the given resource path. + * @param resourcePath + * @return + * @throws org.wso2.carbon.registry.core.exceptions.RegistryException + */ + @Override + public synchronized Object read(String resourcePath) throws RegistryException { + try { + Registry registry = getRegistry(); + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + Resource resource = registry.get(resourcePath); + Object content = resource.getContent(); + if ((content != null) && (content instanceof byte[])) { + try { + return deserializeFromByteArray((byte[]) content); + } catch (Exception e) { + log.error("Could not de-serialize object stored in registry", e); + throw new RuntimeException(e); + } + } + return content; + } catch (ResourceNotFoundException ignore) { + return null; + } catch (RegistryException e) { + String msg = "Failed to read resource from registry: " + resourcePath; + log.error(msg, e); + throw new RegistryException(msg, e); + } + } + + @Override + public synchronized void remove(String resourcePath) throws RegistryException{ + Registry registry = getRegistry(); + + try { + registry.beginTransaction(); + registry.delete(resourcePath); + registry.commitTransaction(); + } catch (RegistryException e) { + try { + registry.rollbackTransaction(); + } catch (RegistryException e1) { + if (log.isErrorEnabled()) { + log.error("Could not rollback transaction", e); + } + } + log.error("Could not remove registry resource: [resource-path] " + resourcePath); + } + } + + private UserRegistry getRegistry() throws RegistryException { + return ServiceReferenceHolder.getInstance().getRegistry(); + } + + /** + * Serialize an object to a byte array. + * @param serializableObject + * @return + * @throws java.io.IOException + */ + private byte[] serializeToByteArray(Serializable serializableObject) throws IOException { + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = null; + try { + out = new ObjectOutputStream(bos); + out.writeObject(serializableObject); + return bos.toByteArray(); + + } finally { + if (out != null) { + out.close(); + } + bos.close(); + } + } + + /** + * Deserialize a byte array and retrieve the object. + * @param bytes bytes to be deserialized + * @return the deserialized {@link Object} + * @throws Exception if the deserialization is failed. + */ + private Object deserializeFromByteArray(byte[] bytes) throws Exception { + + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + ObjectInput in = null; + try { + in = new ObjectInputStream(bis); + return in.readObject(); + } finally { + bis.close(); + if (in != null) { + in.close(); + } + } + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/MockIaasService.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/MockIaasService.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/MockIaasService.java new file mode 100644 index 0000000..e4bbdf5 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/MockIaasService.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services; + +import org.apache.stratos.mock.iaas.domain.MockInstanceContext; +import org.apache.stratos.mock.iaas.domain.MockInstanceMetadata; +import org.apache.stratos.mock.iaas.exceptions.MockIaasException; + +import java.util.List; + +/** + * Mock iaas service interface. + */ +public interface MockIaasService { + + /** + * Start mock instance. + * @param mockInstanceContext + * @return + * @throws MockIaasException + */ + MockInstanceMetadata startInstance(MockInstanceContext mockInstanceContext) throws MockIaasException; + + /** + * Terminate mock instance. + * @param instanceId + */ + void terminateInstance(String instanceId); + + /** + * Get mock instances. + * @return + */ + List<MockInstanceMetadata> getInstances(); + + /** + * Get mock instance by instance id. + * @param instanceId + * @return + */ + MockInstanceMetadata getInstance(String instanceId); + + /** + * Allocate ip address to mock instance. + * @param instanceId + * @return + */ + MockInstanceMetadata allocateIpAddress(String instanceId) throws MockIaasException; +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockAutoscalingFactor.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockAutoscalingFactor.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockAutoscalingFactor.java new file mode 100644 index 0000000..518cb0f --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockAutoscalingFactor.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +/** + * Mock autoscaling factor enumeration + */ +public enum MockAutoscalingFactor { + MemoryConsumption, LoadAverage, RequestInFlight +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockConstants.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockConstants.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockConstants.java new file mode 100644 index 0000000..dce1899 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockConstants.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +/** + * Mock constant definitions. + */ +public class MockConstants { + public static final String MOCK_MEMBER_THREAD_POOL = "mock.member.thread.pool"; + public static final int MOCK_MEMBER_THREAD_POOL_SIZE = 100; + public static final String PERSISTENCE_MANAGER_TYPE = "persistence.manager.type"; + public static final String PERSISTENCE_MANAGER_REGISTRY = "registry"; + public static final String PERSISTENCE_MANAGER_MOCK = "mock"; +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIPAddressPool.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIPAddressPool.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIPAddressPool.java new file mode 100644 index 0000000..a98a0c2 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIPAddressPool.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.persistence.PersistenceManager; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerFactory; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerType; +import org.wso2.carbon.registry.core.exceptions.RegistryException; + +import java.io.Serializable; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Mock IP address pool is a singleton class for managing mocked private and public IP addresses. + */ +public class MockIPAddressPool { + private static final Log log = LogFactory.getLog(MockIPAddressPool.class); + + private static final String MOCK_IAAS_PRIVATE_IP_SEQUENCE = "/cloud.controller/mock/iaas/private-ip-sequence"; + private static final String MOCK_IAAS_PUBLIC_IP_SEQUENCE = "/cloud.controller/mock/iaas/public-ip-sequence"; + private static final String PRIVATE_IP_PREFIX = "10.0.0."; + private static final String PUBLIC_IP_PREFIX = "20.0.0."; + + private static volatile MockIPAddressPool instance; + + private PersistenceManager persistenceManager; + private AtomicInteger privateIpSequence; + private AtomicInteger publicIpSequence; + + private MockIPAddressPool() { + try { + String persistenceManagerTypeStr = System.getProperty(MockConstants.PERSISTENCE_MANAGER_TYPE, + PersistenceManagerType.Registry.toString()); + PersistenceManagerType persistenceManagerType = PersistenceManagerType.valueOf(persistenceManagerTypeStr); + persistenceManager = PersistenceManagerFactory.getPersistenceManager(persistenceManagerType); + + privateIpSequence = (AtomicInteger) persistenceManager.read(MOCK_IAAS_PRIVATE_IP_SEQUENCE); + if (privateIpSequence == null) { + privateIpSequence = new AtomicInteger(); + } + } catch (RegistryException e) { + String message = "Could not read private ip sequence from registry"; + log.error(message, e); + throw new RuntimeException(e); + } + + try { + publicIpSequence = (AtomicInteger) persistenceManager.read(MOCK_IAAS_PUBLIC_IP_SEQUENCE); + if (publicIpSequence == null) { + publicIpSequence = new AtomicInteger(); + } + } catch (RegistryException e) { + String message = "Could not read public ip sequence from registry"; + log.error(message, e); + throw new RuntimeException(e); + } + } + + public static MockIPAddressPool getInstance() { + if (instance == null) { + synchronized (MockIPAddressPool.class) { + if (instance == null) { + instance = new MockIPAddressPool(); + } + } + } + return instance; + } + + public String getNextPrivateIpAddress() { + int nextSequence = privateIpSequence.incrementAndGet(); + String ipAddress = PRIVATE_IP_PREFIX + nextSequence; + persistInRegistry(MOCK_IAAS_PRIVATE_IP_SEQUENCE, privateIpSequence); + if (log.isDebugEnabled()) { + log.debug("Mock private IP address allocated: " + ipAddress); + } + return ipAddress; + } + + public String getNextPublicIpAddress() { + int nextSequence = publicIpSequence.incrementAndGet(); + String ipAddress = PUBLIC_IP_PREFIX + nextSequence; + persistInRegistry(MOCK_IAAS_PRIVATE_IP_SEQUENCE, publicIpSequence); + if (log.isDebugEnabled()) { + log.debug("Mock public IP address allocated: " + ipAddress); + } + return ipAddress; + } + + private void persistInRegistry(String resourcePath, Serializable serializable) { + try { + persistenceManager.persist(resourcePath, serializable); + } catch (RegistryException e) { + log.error(String.format("Could not persist mock iaas ip sequence [%s] in registry", resourcePath), e); + } + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceImpl.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceImpl.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceImpl.java new file mode 100644 index 0000000..bc2e792 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceImpl.java @@ -0,0 +1,209 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.common.threading.StratosThreadPool; +import org.apache.stratos.mock.iaas.domain.MockInstanceContext; +import org.apache.stratos.mock.iaas.domain.MockInstanceMetadata; +import org.apache.stratos.mock.iaas.exceptions.MockIaasException; +import org.apache.stratos.mock.iaas.persistence.PersistenceManager; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerFactory; +import org.apache.stratos.mock.iaas.persistence.PersistenceManagerType; +import org.apache.stratos.mock.iaas.services.MockIaasService; +import org.apache.stratos.mock.iaas.statistics.generator.MockHealthStatisticsGenerator; +import org.wso2.carbon.registry.core.exceptions.RegistryException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +/** + * Mock IaaS service implementation. This is a singleton class that simulates a standard Infrastructure as a Service + * platform by creating mock instances and managing their lifecycle states. + * + * How does this work: + * - Mock IaaS starts a Mock Member thread or each instance created + * - A sample private IP and a public IP will be assigned to the instance + * - Mock Member will publish Instance Started and Instance Activated events once the thread is started + * - Afterwards it will start publishing sample health statistics values to CEP + * - If the Mock IaaS was asked to terminate an instance it will stop the relevant thread + */ +public class MockIaasServiceImpl implements MockIaasService { + + private static final Log log = LogFactory.getLog(MockIaasServiceImpl.class); + + private static final ExecutorService mockMemberExecutorService = + StratosThreadPool.getExecutorService(MockConstants.MOCK_MEMBER_THREAD_POOL, + MockConstants.MOCK_MEMBER_THREAD_POOL_SIZE); + private static volatile MockIaasServiceImpl instance; + + private PersistenceManager persistenceManager; + private MockIaasServiceUtil mockIaasServiceUtil; + private Map<String, MockInstance> instanceIdToMockInstanceMap; // Map<InstanceId,MockInstance> + + public MockIaasServiceImpl() { + try { + String persistenceManagerTypeStr = System.getProperty(MockConstants.PERSISTENCE_MANAGER_TYPE, + PersistenceManagerType.Registry.toString()); + PersistenceManagerType persistenceManagerType = PersistenceManagerType.valueOf(persistenceManagerTypeStr); + persistenceManager = PersistenceManagerFactory.getPersistenceManager(persistenceManagerType); + mockIaasServiceUtil = new MockIaasServiceUtil(persistenceManager); + + instanceIdToMockInstanceMap = mockIaasServiceUtil.readFromRegistry(); + } catch (RegistryException e) { + String message = "Could not read service name -> mock member map from registry"; + log.error(message, e); + throw new RuntimeException(message, e); + } + if(instanceIdToMockInstanceMap == null) { + // No instances found in registry, create a new map + instanceIdToMockInstanceMap = new ConcurrentHashMap<String, MockInstance>(); + } + } + + /** + * Start mock instance. + * @param mockInstanceContext + * @return + * @throws MockIaasException + */ + @Override + public MockInstanceMetadata startInstance(MockInstanceContext mockInstanceContext) throws MockIaasException { + synchronized (MockIaasServiceImpl.class) { + + if(mockInstanceContext == null) { + throw new MockIaasException("Mock instance context is null"); + } + + // Generate instance id + String instanceId = UUID.randomUUID().toString(); + mockInstanceContext.setInstanceId(instanceId); + + MockInstance mockInstance = new MockInstance(mockInstanceContext); + instanceIdToMockInstanceMap.put(instanceId, mockInstance); + mockMemberExecutorService.submit(mockInstance); + + // Persist changes + mockIaasServiceUtil.persistInRegistry((ConcurrentHashMap<String, MockInstance>) instanceIdToMockInstanceMap); + + String serviceName = mockInstanceContext.getServiceName(); + MockHealthStatisticsGenerator.getInstance().scheduleStatisticsUpdaterTasks(serviceName); + + return new MockInstanceMetadata(mockInstanceContext); + } + } + + /** + * Get mock instance contexts. + * @return + */ + @Override + public List<MockInstanceMetadata> getInstances() { + List<MockInstanceMetadata> mockInstanceMetadataList = new ArrayList<MockInstanceMetadata>(); + for(Map.Entry<String, MockInstance> entry : instanceIdToMockInstanceMap.entrySet()) { + MockInstanceContext mockMemberContext = entry.getValue().getMockInstanceContext(); + mockInstanceMetadataList.add(new MockInstanceMetadata(mockMemberContext)); + } + return mockInstanceMetadataList; + } + + /** + * Get mock instance context by instance id. + * @param instanceId + * @return + */ + @Override + public MockInstanceMetadata getInstance(String instanceId) { + if(instanceIdToMockInstanceMap.containsKey(instanceId)) { + MockInstanceContext mockInstanceContext = instanceIdToMockInstanceMap.get(instanceId).getMockInstanceContext(); + return new MockInstanceMetadata(mockInstanceContext); + } + return null; + } + + /** + * Allocate ip address to mock instance. + * @param instanceId + * @return + * @throws MockIaasException + */ + @Override + public MockInstanceMetadata allocateIpAddress(String instanceId) throws MockIaasException { + MockInstance mockInstance = instanceIdToMockInstanceMap.get(instanceId); + if(mockInstance == null) { + throw new MockIaasException(String.format("Mock instance not found: [instance-id] %s", instanceId)); + } + + MockInstanceContext mockInstanceContext = mockInstance.getMockInstanceContext(); + mockInstanceContext.setDefaultPrivateIP(MockIPAddressPool.getInstance().getNextPrivateIpAddress()); + mockInstanceContext.setDefaultPublicIP(MockIPAddressPool.getInstance().getNextPublicIpAddress()); + mockIaasServiceUtil.persistInRegistry((ConcurrentHashMap<String, MockInstance>) instanceIdToMockInstanceMap); + + return new MockInstanceMetadata(mockInstanceContext); + } + + /** + * Terminate mock instance by instance id. + * @param instanceId + */ + @Override + public void terminateInstance(String instanceId) { + synchronized (MockIaasServiceImpl.class) { + log.info(String.format("Terminating instance: [instance-id] %s", instanceId)); + + MockInstance mockInstance = instanceIdToMockInstanceMap.get(instanceId); + if (mockInstance != null) { + String serviceName = mockInstance.getMockInstanceContext().getServiceName(); + + mockInstance.terminate(); + instanceIdToMockInstanceMap.remove(instanceId); + mockIaasServiceUtil.persistInRegistry((ConcurrentHashMap<String, MockInstance>) instanceIdToMockInstanceMap); + + if (getMemberCount(serviceName) == 0) { + MockHealthStatisticsGenerator.getInstance().stopStatisticsUpdaterTasks(serviceName); + } + + log.info(String.format("Instance terminated successfully: [instance-id] %s", instanceId)); + } else { + log.warn(String.format("Instance not found: [instance-id] %s", instanceId)); + } + } + } + + /** + * Find number of instances available for service type. + * @param serviceName + * @return + */ + private int getMemberCount(String serviceName) { + int count = 0; + for(Map.Entry<String, MockInstance> entry : instanceIdToMockInstanceMap.entrySet()) { + if(serviceName.equals(entry.getValue().getMockInstanceContext().getServiceName())) { + count++; + } + } + return count; + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceUtil.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceUtil.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceUtil.java new file mode 100644 index 0000000..1d8d268 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockIaasServiceUtil.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.common.threading.StratosThreadPool; +import org.apache.stratos.mock.iaas.persistence.PersistenceManager; +import org.apache.stratos.mock.iaas.statistics.generator.MockHealthStatisticsGenerator; +import org.wso2.carbon.registry.core.exceptions.RegistryException; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +/** + * Mock iaas service util. + */ +public class MockIaasServiceUtil { + + private static final Log log = LogFactory.getLog(MockIaasServiceUtil.class); + private static final String MOCK_IAAS_MEMBERS = "/mock.iaas/instances"; + + private PersistenceManager persistenceManager; + + public MockIaasServiceUtil(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + public void persistInRegistry(ConcurrentHashMap<String, MockInstance> instanceIdToMockMemberMap) { + try { + persistenceManager.persist(MOCK_IAAS_MEMBERS, instanceIdToMockMemberMap); + } catch (RegistryException e) { + log.error("Could not persist mock iaas instances in registry", e); + } + } + + public ConcurrentHashMap<String, MockInstance> readFromRegistry() throws RegistryException { + return (ConcurrentHashMap<String, MockInstance>) persistenceManager.read(MOCK_IAAS_MEMBERS); + } + + public void startInstancesPersisted() throws RegistryException { + Map<String, MockInstance> instanceIdToMockMemberMap = readFromRegistry(); + ExecutorService mockMemberExecutorService = + StratosThreadPool.getExecutorService(MockConstants.MOCK_MEMBER_THREAD_POOL, + MockConstants.MOCK_MEMBER_THREAD_POOL_SIZE); + + if(instanceIdToMockMemberMap != null) { + log.info("Starting mock instances persisted..."); + + Set<String> serviceNameSet = new HashSet<String>(); + for(MockInstance mockInstance : instanceIdToMockMemberMap.values()) { + mockMemberExecutorService.submit(mockInstance); + + // Schedule statistics updater tasks for service + String serviceName = mockInstance.getMockInstanceContext().getServiceName(); + if(!serviceNameSet.contains(serviceName)) { + MockHealthStatisticsGenerator.getInstance().scheduleStatisticsUpdaterTasks(serviceName); + serviceNameSet.add(serviceName); + } + } + } + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockInstance.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockInstance.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockInstance.java new file mode 100644 index 0000000..4ddf4bd --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/services/impl/MockInstance.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.domain.MockInstanceContext; +import org.apache.stratos.mock.iaas.event.publisher.MockMemberEventPublisher; +import org.apache.stratos.mock.iaas.statistics.publisher.MockHealthStatisticsNotifier; +import org.apache.stratos.common.threading.StratosThreadPool; +import org.apache.stratos.messaging.event.Event; +import org.apache.stratos.messaging.event.instance.notifier.InstanceCleanupClusterEvent; +import org.apache.stratos.messaging.event.instance.notifier.InstanceCleanupMemberEvent; +import org.apache.stratos.messaging.listener.instance.notifier.InstanceCleanupClusterEventListener; +import org.apache.stratos.messaging.listener.instance.notifier.InstanceCleanupMemberEventListener; +import org.apache.stratos.messaging.message.receiver.instance.notifier.InstanceNotifierEventReceiver; + +import java.io.Serializable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Mock member definition. + */ +public class MockInstance implements Runnable, Serializable { + + private static final Log log = LogFactory.getLog(MockInstance.class); + private static final ExecutorService instanceNotifierExecutorService = + StratosThreadPool.getExecutorService("MOCK_MEMBER_INSTANCE_NOTIFIER_EXECUTOR_SERVICE", 20); + private static final ScheduledExecutorService healthStatNotifierExecutorService = + StratosThreadPool.getScheduledExecutorService("MOCK_MEMBER_HEALTH_STAT_NOTIFIER_EXECUTOR_SERVICE", 20); + private static final int HEALTH_STAT_INTERVAL = 15; // 15 seconds + + private final MockInstanceContext mockMemberContext; + private boolean terminated; + + public MockInstance(MockInstanceContext mockMemberContext) { + this.mockMemberContext = mockMemberContext; + } + + @Override + public void run() { + if (log.isInfoEnabled()) { + log.info(String.format("Mock member started: [member-id] %s", mockMemberContext.getMemberId())); + } + + sleep(5000); + MockMemberEventPublisher.publishInstanceStartedEvent(mockMemberContext); + + sleep(5000); + MockMemberEventPublisher.publishInstanceActivatedEvent(mockMemberContext); + + startInstanceNotifierReceiver(); + startHealthStatisticsPublisher(); + + while (!terminated) { + sleep(1000); + } + + if (log.isInfoEnabled()) { + log.info(String.format("Mock member terminated: [member-id] %s", mockMemberContext.getMemberId())); + } + } + + private void startInstanceNotifierReceiver() { + if (log.isDebugEnabled()) { + log.debug("Starting instance notifier event message receiver"); + } + + final InstanceNotifierEventReceiver instanceNotifierEventReceiver = new InstanceNotifierEventReceiver(); + instanceNotifierEventReceiver.addEventListener(new InstanceCleanupClusterEventListener() { + @Override + protected void onEvent(Event event) { + InstanceCleanupClusterEvent instanceCleanupClusterEvent = (InstanceCleanupClusterEvent) event; + if (mockMemberContext.getClusterId().equals(instanceCleanupClusterEvent.getClusterId()) && + mockMemberContext.getClusterInstanceId().equals( + instanceCleanupClusterEvent.getClusterInstanceId())) { + handleMemberTermination(); + } + } + }); + + instanceNotifierEventReceiver.addEventListener(new InstanceCleanupMemberEventListener() { + @Override + protected void onEvent(Event event) { + InstanceCleanupMemberEvent instanceCleanupClusterEvent = (InstanceCleanupMemberEvent) event; + if (mockMemberContext.getMemberId().equals(instanceCleanupClusterEvent.getMemberId())) { + handleMemberTermination(); + } + } + }); + + instanceNotifierExecutorService.submit(new Runnable() { + @Override + public void run() { + instanceNotifierEventReceiver.execute(); + } + }); + + if (log.isDebugEnabled()) { + log.debug("Instance notifier event message receiver started"); + } + } + + private void handleMemberTermination() { + MockMemberEventPublisher.publishMaintenanceModeEvent(mockMemberContext); + sleep(2000); + MockMemberEventPublisher.publishInstanceReadyToShutdownEvent(mockMemberContext); + } + + private void startHealthStatisticsPublisher() { + if (log.isDebugEnabled()) { + log.debug(String.format("Starting health statistics notifier: [member-id] %s", mockMemberContext.getMemberId())); + } + + healthStatNotifierExecutorService.scheduleAtFixedRate(new MockHealthStatisticsNotifier(mockMemberContext), + 0, HEALTH_STAT_INTERVAL, TimeUnit.SECONDS); + + if (log.isDebugEnabled()) { + log.debug(String.format("Health statistics notifier started: [member-id] %s", mockMemberContext.getMemberId())); + } + } + + private void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException ignore) { + terminate(); + } + } + + public MockInstanceContext getMockInstanceContext() { + return mockMemberContext; + } + + public void terminate() { + terminated = true; + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/MockHealthStatistics.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/MockHealthStatistics.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/MockHealthStatistics.java new file mode 100644 index 0000000..bb53059 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/MockHealthStatistics.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics; + +import org.apache.stratos.mock.iaas.services.impl.MockAutoscalingFactor; +import org.apache.stratos.mock.iaas.exceptions.NoStatisticsFoundException; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Mock health statistics singleton class. + */ +public class MockHealthStatistics { + private final static int DEFAULT_MEMORY_CONSUMPTION = 20; + private final static int DEFAULT_LOAD_AVERAGE = 20; + private final static int DEFAULT_REQUESTS_IN_FLIGHT = 1; + + private static volatile MockHealthStatistics instance; + + private Map<String, Map<String, Integer>> statisticsMap; + + private MockHealthStatistics() { + statisticsMap = new ConcurrentHashMap<String, Map<String, Integer>>(); + } + + public static MockHealthStatistics getInstance() { + if (instance == null) { + synchronized (MockHealthStatistics.class) { + if (instance == null) { + instance = new MockHealthStatistics(); + } + } + } + return instance; + } + + /** + * Add statistics value for a cartridge type, autoscaling factor + * @param cartridgeType + * @param autoscalingFactor + * @param value + */ + public void addStatistics(String cartridgeType, MockAutoscalingFactor autoscalingFactor, Integer value) { + Map<String, Integer> factorValueMap = statisticsMap.get(cartridgeType); + if(factorValueMap == null) { + synchronized (MockHealthStatistics.class) { + if(factorValueMap == null) { + factorValueMap = new ConcurrentHashMap<String, Integer>(); + statisticsMap.put(cartridgeType, factorValueMap); + } + } + } + factorValueMap.put(autoscalingFactor.toString(), value); + } + + /** + * Returns current statistics of the given cartridge type, autoscaling factor + * @param cartridgeType + * @param autoscalingFactor + * @return + */ + public int getStatistics(String cartridgeType, MockAutoscalingFactor autoscalingFactor) throws NoStatisticsFoundException { + Map<String, Integer> factorValueMap = statisticsMap.get(cartridgeType); + if(factorValueMap != null) { + if(factorValueMap.containsKey(autoscalingFactor.toString())) { + return factorValueMap.get(autoscalingFactor.toString()); + } else { + throw new NoStatisticsFoundException(); + } + } + // No statistics patterns found, return default + return findDefault(autoscalingFactor); + } + + /** + * Remove statistics found for the cartridge type, autoscaling factor + * @param cartridgeType + * @param autoscalingFactor + */ + public void removeStatistics(String cartridgeType, MockAutoscalingFactor autoscalingFactor) { + Map<String, Integer> factorValueMap = statisticsMap.get(cartridgeType); + if(factorValueMap != null) { + if(factorValueMap.containsKey(autoscalingFactor.toString())) { + factorValueMap.remove(autoscalingFactor.toString()); + } + } + } + + /** + * Find default statistics value of the given autoscaling factor + * @param autoscalingFactor + * @return + */ + private int findDefault(MockAutoscalingFactor autoscalingFactor) { + if(autoscalingFactor == MockAutoscalingFactor.MemoryConsumption) { + return DEFAULT_MEMORY_CONSUMPTION; + } else if(autoscalingFactor == MockAutoscalingFactor.LoadAverage) { + return DEFAULT_LOAD_AVERAGE; + } else if(autoscalingFactor == MockAutoscalingFactor.RequestInFlight) { + return DEFAULT_REQUESTS_IN_FLIGHT; + } + throw new RuntimeException("An unknown autoscaling factor found: " + autoscalingFactor); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/StatisticsPatternMode.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/StatisticsPatternMode.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/StatisticsPatternMode.java new file mode 100644 index 0000000..b8ef9fd --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/StatisticsPatternMode.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics; + +/** + * Statistics pattern mode. + */ +public enum StatisticsPatternMode { + Loop, Continue, Stop +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsGenerator.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsGenerator.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsGenerator.java new file mode 100644 index 0000000..095d5a7 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsGenerator.java @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics.generator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.config.MockIaasConfig; +import org.apache.stratos.common.threading.StratosThreadPool; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +/** + * Mock health statistics generator. + */ +public class MockHealthStatisticsGenerator { + + private static final Log log = LogFactory.getLog(MockHealthStatisticsGenerator.class); + + private static volatile MockHealthStatisticsGenerator instance; + private static final ScheduledExecutorService scheduledExecutorService = + StratosThreadPool.getScheduledExecutorService("MOCK_STATISTICS_GENERATOR_EXECUTOR_SERVICE", 10); + + private boolean scheduled; + // Map<ServiceName, List<ScheduledFuture>> + private Map<String, Map<String, ScheduledFuture>> serviceNameToTaskListMap; + + public static MockHealthStatisticsGenerator getInstance() { + if (instance == null) { + synchronized (MockHealthStatisticsGenerator.class) { + if (instance == null) { + instance = new MockHealthStatisticsGenerator(); + } + } + } + return instance; + } + + private MockHealthStatisticsGenerator() { + serviceNameToTaskListMap = new ConcurrentHashMap<String, Map<String, ScheduledFuture>>(); + } + + /** + * Schedule statistics updater tasks for the given service/cartridge type. + * + * @param serviceName + */ + public void scheduleStatisticsUpdaterTasks(String serviceName) { + synchronized (MockHealthStatisticsGenerator.class) { + if (!statisticsUpdaterTasksScheduled(serviceName)) { + List<MockHealthStatisticsPattern> statisticsPatterns = MockIaasConfig.getInstance(). + getMockHealthStatisticsConfig().getStatisticsPatterns(); + + Map<String, ScheduledFuture> taskList = serviceNameToTaskListMap.get(serviceName); + if (taskList == null) { + taskList = new ConcurrentHashMap<String, ScheduledFuture>(); + serviceNameToTaskListMap.put(serviceName, taskList); + } + + for (MockHealthStatisticsPattern statisticsPattern : statisticsPatterns) { + if (statisticsPattern.getCartridgeType().equals(serviceName) && + (statisticsPattern.getSampleDuration() > 0)) { + MockHealthStatisticsUpdater runnable = new MockHealthStatisticsUpdater(statisticsPattern); + ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, + statisticsPattern.getSampleDuration(), TimeUnit.SECONDS); + taskList.put(statisticsPattern.getFactor().toString(), task); + } + } + + if (log.isInfoEnabled()) { + log.info(String.format("Mock statistics updaters scheduled: [service-name] %s", serviceName)); + } + } + } + } + + /** + * Stop statistics updater tasks of the given service/cartridge type. + * + * @param serviceName + */ + public void stopStatisticsUpdaterTasks(String serviceName) { + synchronized (MockHealthStatisticsGenerator.class) { + Map<String, ScheduledFuture> taskMap = serviceNameToTaskListMap.get(serviceName); + if ((taskMap != null) && (taskMap.size() > 0)) { + Iterator<String> factorIterator = taskMap.keySet().iterator(); + while(factorIterator.hasNext()) { + String factor = factorIterator.next(); + stopStatisticsUpdaterTask(serviceName, factor); + } + } + } + } + + /** + * Stop statistics updater task of a service/cartridge type, factor. + * @param serviceName + * @param factor + */ + public void stopStatisticsUpdaterTask(String serviceName, String factor) { + Map<String, ScheduledFuture> factorToTaskMap = serviceNameToTaskListMap.get(serviceName); + if(factorToTaskMap != null) { + ScheduledFuture task = factorToTaskMap.get(factor); + if(task != null) { + task.cancel(true); + factorToTaskMap.remove(factor); + + if (log.isInfoEnabled()) { + log.info(String.format("Mock statistics updater task stopped: [service-name] %s" + + " [factor] %s", serviceName, factor)); + } + } + } + } + + /** + * Returns true if there are statistics updater tasks scheduled for the given service/cartridge type + * else returns false. + * @param serviceName + * @return + */ + public boolean statisticsUpdaterTasksScheduled(String serviceName) { + Map<String, ScheduledFuture> tasks = serviceNameToTaskListMap.get(serviceName); + return ((tasks != null) && (tasks.size() > 0)); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsPattern.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsPattern.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsPattern.java new file mode 100644 index 0000000..ac14aa5 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsPattern.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics.generator; + +import org.apache.stratos.mock.iaas.services.impl.MockAutoscalingFactor; +import org.apache.stratos.mock.iaas.exceptions.ContinueLastSampleValueException; +import org.apache.stratos.mock.iaas.exceptions.NoSampleValuesFoundException; +import org.apache.stratos.mock.iaas.exceptions.StopStatisticsPublishingException; +import org.apache.stratos.mock.iaas.statistics.StatisticsPatternMode; + +import java.util.Iterator; +import java.util.List; + +/** + * Mock health statistics pattern definition. + */ +public class MockHealthStatisticsPattern { + + private String cartridgeType; + private MockAutoscalingFactor factor; + private StatisticsPatternMode mode; + private List<Integer> sampleValues; + private int sampleDuration; + private Iterator sampleValuesIterator; + + public MockHealthStatisticsPattern(String cartridgeType, MockAutoscalingFactor factor, StatisticsPatternMode mode, List<Integer> sampleValues, + int sampleDuration) { + this.cartridgeType = cartridgeType; + this.factor = factor; + this.mode = mode; + this.sampleValues = sampleValues; + this.sampleValuesIterator = this.sampleValues.iterator(); + this.sampleDuration = sampleDuration; + } + + public String getCartridgeType() { + return cartridgeType; + } + + /** + * Returns autoscaling factor + * @return + */ + public MockAutoscalingFactor getFactor() { + return factor; + } + + /** + * Returns statistics pattern mode + * @return + */ + public StatisticsPatternMode getMode() { + return mode; + } + + /** + * Returns next sample value + * @return + */ + public int getNextSample() throws NoSampleValuesFoundException, StopStatisticsPublishingException, + ContinueLastSampleValueException { + if((sampleValues == null) || (sampleValues.size() < 1)) { + throw new NoSampleValuesFoundException(); + } + + if(!sampleValuesIterator.hasNext()) { + // Iterator has come to the end of the list + if(getMode() == StatisticsPatternMode.Loop) { + // Looping: reset the iterator + sampleValuesIterator = sampleValues.iterator(); + return Integer.parseInt(sampleValuesIterator.next().toString()); + } else if(getMode() == StatisticsPatternMode.Continue) { + // Continue: return the last value + int lastSampleValue = Integer.parseInt(sampleValues.get(sampleValues.size() - 1).toString()); + throw new ContinueLastSampleValueException(lastSampleValue); + } else if(getMode() == StatisticsPatternMode.Stop) { + throw new StopStatisticsPublishingException(); + } else { + throw new RuntimeException("An unknown statistics pattern mode found"); + } + } else { + return Integer.parseInt(sampleValuesIterator.next().toString()); + } + } + + /** + * Returns sample duration in seconds + * @return + */ + public int getSampleDuration() { + return sampleDuration; + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsUpdater.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsUpdater.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsUpdater.java new file mode 100644 index 0000000..550c3f5 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/generator/MockHealthStatisticsUpdater.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics.generator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.exceptions.ContinueLastSampleValueException; +import org.apache.stratos.mock.iaas.exceptions.NoSampleValuesFoundException; +import org.apache.stratos.mock.iaas.exceptions.StopStatisticsPublishingException; +import org.apache.stratos.mock.iaas.statistics.MockHealthStatistics; + +/** + * Update health statistics according to the given sample pattern, for each pattern there will be + * one updater runnable created. + */ +public class MockHealthStatisticsUpdater implements Runnable { + + private static final Log log = LogFactory.getLog(MockHealthStatisticsUpdater.class); + + private MockHealthStatisticsPattern statisticsPattern; + + public MockHealthStatisticsUpdater(MockHealthStatisticsPattern statisticsPattern) { + this.statisticsPattern = statisticsPattern; + } + + @Override + public void run() { + try { + int nextSample = statisticsPattern.getNextSample(); + MockHealthStatistics.getInstance().addStatistics(statisticsPattern.getCartridgeType(), + statisticsPattern.getFactor(), nextSample); + + if (log.isInfoEnabled()) { + log.info(String.format("Mock statistics updated: [cartridge-type] %s [factor] %s [value] %d", + statisticsPattern.getCartridgeType(), statisticsPattern.getFactor().toString(), nextSample)); + } + } catch (NoSampleValuesFoundException ignore) { + if (log.isDebugEnabled()) { + log.debug(String.format("No sample values found for: [cartridge-type] %s [factor] %s", + statisticsPattern.getCartridgeType(), statisticsPattern.getFactor().toString())); + } + } catch (ContinueLastSampleValueException e) { + if (log.isInfoEnabled()) { + log.info(String.format("Continuing last sample value: [cartridge-type] %s [factor] %s [value] %d", + statisticsPattern.getCartridgeType(), statisticsPattern.getFactor().toString(), + e.getLastSampleValue())); + } + // Stop statistics updater task + MockHealthStatisticsGenerator.getInstance().stopStatisticsUpdaterTask(statisticsPattern.getCartridgeType(), + statisticsPattern.getFactor().toString()); + } catch (StopStatisticsPublishingException action) { + // Remove statistics + MockHealthStatistics.getInstance().removeStatistics(statisticsPattern.getCartridgeType(), + statisticsPattern.getFactor()); + if (log.isDebugEnabled()) { + log.debug(String.format("Statistics removed: [cartridge-type] %s [factor] %s", + statisticsPattern.getCartridgeType(), statisticsPattern.getFactor().toString())); + } + // Stop statistics updater task + MockHealthStatisticsGenerator.getInstance().stopStatisticsUpdaterTask(statisticsPattern.getCartridgeType(), + statisticsPattern.getFactor().toString()); + } catch (Exception e) { + log.error("Could not update mock statistics", e); + } + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/e16acd17/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/publisher/MockHealthStatisticsNotifier.java ---------------------------------------------------------------------- diff --git a/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/publisher/MockHealthStatisticsNotifier.java b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/publisher/MockHealthStatisticsNotifier.java new file mode 100644 index 0000000..fda5cc1 --- /dev/null +++ b/components/org.apache.stratos.mock.iaas/src/main/java/org/apache/stratos/mock/iaas/statistics/publisher/MockHealthStatisticsNotifier.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.stratos.mock.iaas.statistics.publisher; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.stratos.mock.iaas.services.impl.MockAutoscalingFactor; +import org.apache.stratos.mock.iaas.domain.MockInstanceContext; +import org.apache.stratos.mock.iaas.exceptions.NoStatisticsFoundException; +import org.apache.stratos.mock.iaas.statistics.MockHealthStatistics; + +/** + * Health statistics notifier thread for publishing statistics periodically to CEP. + */ +public class MockHealthStatisticsNotifier implements Runnable { + private static final Log log = LogFactory.getLog(MockHealthStatisticsNotifier.class); + + public static final String MEMORY_CONSUMPTION = "memory_consumption"; + public static final String LOAD_AVERAGE = "load_average"; + + private final MockInstanceContext mockMemberContext; + private final MockHealthStatisticsPublisher statsPublisher; + + public MockHealthStatisticsNotifier(MockInstanceContext mockMemberContext) { + this.mockMemberContext = mockMemberContext; + this.statsPublisher = new MockHealthStatisticsPublisher(); + this.statsPublisher.setEnabled(true); + } + + @Override + public void run() { + if (!statsPublisher.isEnabled()) { + if (log.isWarnEnabled()) { + log.warn("Statistics publisher is disabled"); + } + return; + } + + try { + double memoryConsumption = MockHealthStatistics.getInstance().getStatistics( + mockMemberContext.getServiceName(), MockAutoscalingFactor.MemoryConsumption); + + if (log.isDebugEnabled()) { + log.debug(String.format("Publishing memory consumption: [member-id] %s [value] %f", + mockMemberContext.getMemberId(), memoryConsumption)); + } + statsPublisher.publish( + mockMemberContext.getClusterId(), + mockMemberContext.getClusterInstanceId(), + mockMemberContext.getNetworkPartitionId(), + mockMemberContext.getMemberId(), + mockMemberContext.getPartitionId(), + MEMORY_CONSUMPTION, + memoryConsumption + ); + } catch (NoStatisticsFoundException ignore) { + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Could not publish health statistics", e); + } + } + + + try { + double loadAvereage = MockHealthStatistics.getInstance().getStatistics( + mockMemberContext.getServiceName(), MockAutoscalingFactor.LoadAverage); + if (log.isDebugEnabled()) { + log.debug(String.format("Publishing load average: [member-id] %s [value] %f", + mockMemberContext.getMemberId(), loadAvereage)); + } + statsPublisher.publish( + mockMemberContext.getClusterId(), + mockMemberContext.getClusterInstanceId(), + mockMemberContext.getNetworkPartitionId(), + mockMemberContext.getMemberId(), + mockMemberContext.getPartitionId(), + LOAD_AVERAGE, + loadAvereage + ); + } catch (NoStatisticsFoundException ignore) { + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Could not publish health statistics", e); + } + } + } +}
