You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by wi...@apache.org on 2012/06/23 11:40:28 UTC
[1/7] git commit: agent: Replace tabs by 4 spaces
Updated Branches:
refs/heads/master d630fa869 -> 5e9a193f2
agent: Replace tabs by 4 spaces
A lot of old code still has tabs inspead of 4 spaces for indentation.
The Coding Convention requires spaces, so we correct it.
Project: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/commit/5e9a193f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/tree/5e9a193f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/diff/5e9a193f
Branch: refs/heads/master
Commit: 5e9a193f2c66dd4901f182cc1f9cf01be7b1a79c
Parents: d630fa8
Author: Wido den Hollander <wi...@widodh.nl>
Authored: Sat Jun 23 11:16:16 2012 +0200
Committer: Wido den Hollander <wi...@widodh.nl>
Committed: Sat Jun 23 11:16:16 2012 +0200
----------------------------------------------------------------------
agent/src/com/cloud/agent/Agent.java | 30 +-
agent/src/com/cloud/agent/AgentShell.java | 1152 ++--
agent/src/com/cloud/agent/IAgentShell.java | 32 +-
.../configuration/AgentComponentLibraryBase.java | 72 +-
.../src/com/cloud/agent/dao/StorageComponent.java | 4 +-
.../cloud/agent/dao/impl/PropertiesStorage.java | 156 +-
.../cloud/agent/dhcp/DhcpProtocolParserServer.java | 58 +-
agent/src/com/cloud/agent/dhcp/DhcpSnooper.java | 12 +-
.../src/com/cloud/agent/dhcp/FakeDhcpSnooper.java | 198 +-
agent/src/com/cloud/agent/mockvm/MockVm.java | 92 +-
agent/src/com/cloud/agent/mockvm/MockVmMgr.java | 582 +-
agent/src/com/cloud/agent/mockvm/VmMgr.java | 50 +-
.../com/cloud/agent/resource/DummyResource.java | 358 +-
.../resource/computing/FakeComputingResource.java | 1064 +-
.../agent/resource/computing/KVMGuestOsMapper.java | 284 +-
.../cloud/agent/resource/computing/KVMHABase.java | 364 +-
.../agent/resource/computing/KVMHAChecker.java | 98 +-
.../agent/resource/computing/KVMHAMonitor.java | 182 +-
.../resource/computing/LibvirtCapXMLParser.java | 302 +-
.../computing/LibvirtComputingResource.java | 7710 +++++++-------
.../resource/computing/LibvirtConnection.java | 42 +-
.../resource/computing/LibvirtDomainXMLParser.java | 408 +-
.../resource/computing/LibvirtNetworkDef.java | 338 +-
.../resource/computing/LibvirtStoragePoolDef.java | 120 +-
.../computing/LibvirtStoragePoolXMLParser.java | 154 +-
.../computing/LibvirtStorageVolumeDef.java | 126 +-
.../computing/LibvirtStorageVolumeXMLParser.java | 120 +-
.../agent/resource/computing/LibvirtVMDef.java | 1748 ++--
.../agent/resource/computing/LibvirtXMLParser.java | 66 +-
.../ConsoleProxyAuthenticationResult.java | 96 +-
.../consoleproxy/ConsoleProxyResource.java | 822 +-
.../com/cloud/agent/storage/KVMPhysicalDisk.java | 96 +-
.../com/cloud/agent/storage/KVMStoragePool.java | 32 +-
.../cloud/agent/storage/KVMStoragePoolManager.java | 126 +-
.../cloud/agent/storage/LibvirtStorageAdaptor.java | 1304 ++--
.../cloud/agent/storage/LibvirtStoragePool.java | 262 +-
.../com/cloud/agent/storage/StorageAdaptor.java | 52 +-
.../com/cloud/agent/vmdata/JettyVmDataServer.java | 602 +-
agent/src/com/cloud/agent/vmdata/VmDataServer.java | 6 +-
agent/test/com/cloud/agent/TestAgentShell.java | 12 +-
40 files changed, 9666 insertions(+), 9666 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/Agent.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/Agent.java b/agent/src/com/cloud/agent/Agent.java
index 9f97213..babf0b3 100755
--- a/agent/src/com/cloud/agent/Agent.java
+++ b/agent/src/com/cloud/agent/Agent.java
@@ -245,9 +245,9 @@ public class Agent implements HandlerFactory, IAgentControl {
_connection.start();
while (!_connection.isStartup()) {
- _shell.getBackoffAlgorithm().waitBeforeRetry();
- _connection = new NioClient("Agent", _shell.getHost(), _shell.getPort(), _shell.getWorkers(), this);
- _connection.start();
+ _shell.getBackoffAlgorithm().waitBeforeRetry();
+ _connection = new NioClient("Agent", _shell.getHost(), _shell.getPort(), _shell.getWorkers(), this);
+ _connection.start();
}
}
@@ -495,7 +495,7 @@ public class Agent implements HandlerFactory, IAgentControl {
_reconnectAllowed = false;
answer = new Answer(cmd, true, null);
} else if (cmd instanceof MaintainCommand) {
- s_logger.debug("Received maintainCommand" );
+ s_logger.debug("Received maintainCommand" );
cancelTasks();
_reconnectAllowed = false;
answer = new MaintainAnswer((MaintainCommand)cmd);
@@ -820,17 +820,17 @@ public class Agent implements HandlerFactory, IAgentControl {
}
public class AgentRequestHandler extends Task {
- public AgentRequestHandler(Task.Type type, Link link, Request req) {
+ public AgentRequestHandler(Task.Type type, Link link, Request req) {
super(type, link, req);
}
- @Override
- protected void doTask(Task task) throws Exception {
- Request req = (Request)this.get();
- if (!(req instanceof Response)) {
- processRequest(req, task.getLink());
- }
- }
+ @Override
+ protected void doTask(Task task) throws Exception {
+ Request req = (Request)this.get();
+ if (!(req instanceof Response)) {
+ processRequest(req, task.getLink());
+ }
+ }
}
public class ServerHandler extends Task {
@@ -853,12 +853,12 @@ public class Agent implements HandlerFactory, IAgentControl {
try {
request = Request.parse(task.getData());
if (request instanceof Response) {
- //It's for pinganswer etc, should be processed immediately.
+ //It's for pinganswer etc, should be processed immediately.
processResponse((Response) request, task.getLink());
} else {
- //put the requests from mgt server into another thread pool, as the request may take a longer time to finish. Don't block the NIO main thread pool
+ //put the requests from mgt server into another thread pool, as the request may take a longer time to finish. Don't block the NIO main thread pool
//processRequest(request, task.getLink());
- _executor.execute(new AgentRequestHandler(this.getType(), this.getLink(), request));
+ _executor.execute(new AgentRequestHandler(this.getType(), this.getLink(), request));
}
} catch (final ClassNotFoundException e) {
s_logger.error("Unable to find this request ");
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/AgentShell.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java
index 49073e1..941f094 100644
--- a/agent/src/com/cloud/agent/AgentShell.java
+++ b/agent/src/com/cloud/agent/AgentShell.java
@@ -58,580 +58,580 @@ import com.cloud.utils.net.MacAddress;
import com.cloud.utils.script.Script;
public class AgentShell implements IAgentShell {
- private static final Logger s_logger = Logger.getLogger(AgentShell.class
- .getName());
-
- private final Properties _properties = new Properties();
- private final Map<String, Object> _cmdLineProperties = new HashMap<String, Object>();
- private StorageComponent _storage;
- private BackoffAlgorithm _backoff;
- private String _version;
- private String _zone;
- private String _pod;
- private String _host;
- private String _privateIp;
- private int _port;
- private int _proxyPort;
- private int _workers;
- private String _guid;
- private int _nextAgentId = 1;
- private volatile boolean _exit = false;
- private int _pingRetries;
- private Thread _consoleProxyMain = null;
- private final List<Agent> _agents = new ArrayList<Agent>();
-
- public AgentShell() {
- }
-
- @Override
- public Properties getProperties() {
- return _properties;
- }
-
- @Override
- public BackoffAlgorithm getBackoffAlgorithm() {
- return _backoff;
- }
-
- @Override
- public int getPingRetries() {
- return _pingRetries;
- }
-
- @Override
- public String getVersion() {
- return _version;
- }
-
- @Override
- public String getZone() {
- return _zone;
- }
-
- @Override
- public String getPod() {
- return _pod;
- }
-
- @Override
- public String getHost() {
- return _host;
- }
-
- @Override
- public String getPrivateIp() {
- return _privateIp;
- }
-
- @Override
- public int getPort() {
- return _port;
- }
-
- @Override
- public int getProxyPort() {
- return _proxyPort;
- }
-
- @Override
- public int getWorkers() {
- return _workers;
- }
-
- @Override
- public String getGuid() {
- return _guid;
- }
-
- public Map<String, Object> getCmdLineProperties() {
- return _cmdLineProperties;
- }
-
- public String getProperty(String prefix, String name) {
- if (prefix != null)
- return _properties.getProperty(prefix + "." + name);
-
- return _properties.getProperty(name);
- }
-
- @Override
- public String getPersistentProperty(String prefix, String name) {
- if (prefix != null)
- return _storage.get(prefix + "." + name);
- return _storage.get(name);
- }
-
- @Override
- public void setPersistentProperty(String prefix, String name, String value) {
- if (prefix != null)
- _storage.persist(prefix + "." + name, value);
- else
- _storage.persist(name, value);
- }
-
- @Override
- public void upgradeAgent(final String url) {
- s_logger.info("Updating agent with binary from " + url);
- synchronized (this) {
- final Class<?> c = this.getClass();
- String path = c.getResource(c.getSimpleName() + ".class")
- .toExternalForm();
- final int begin = path.indexOf(File.separator);
- int end = path.lastIndexOf("!");
- end = path.lastIndexOf(File.separator, end);
- path = path.substring(begin, end);
-
- s_logger.debug("Current binaries reside at " + path);
-
- File file = null;
- try {
- file = File.createTempFile("agent-",
- "-" + Long.toString(new Date().getTime()));
- wget(url, file);
- } catch (final IOException e) {
- s_logger.warn(
- "Exception while downloading agent update package, ", e);
- throw new CloudRuntimeException("Unable to update from " + url
- + ", exception:" + e.getMessage(), e);
- }
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Unzipping " + file.getAbsolutePath() + " to "
- + path);
- }
-
- final Script unzip = new Script("unzip", 120000, s_logger);
- unzip.add("-o", "-q"); // overwrite and quiet
- unzip.add(file.getAbsolutePath());
- unzip.add("-d", path);
-
- final String result = unzip.execute();
- if (result != null) {
- throw new CloudRuntimeException(
- "Unable to unzip the retrieved file: " + result);
- }
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Closing the connection to the management server");
- }
- }
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Exiting to start the new agent.");
- }
- System.exit(ExitStatus.Upgrade.value());
- }
-
- public static void wget(String url, File file) throws IOException {
- final HttpClient client = new HttpClient();
- final GetMethod method = new GetMethod(url);
- int response;
- response = client.executeMethod(method);
- if (response != HttpURLConnection.HTTP_OK) {
- s_logger.warn("Retrieving from " + url + " gives response code: "
- + response);
- throw new CloudRuntimeException("Unable to download from " + url
- + ". Response code is " + response);
- }
-
- final InputStream is = method.getResponseBodyAsStream();
- s_logger.debug("Downloading content into " + file.getAbsolutePath());
-
- final FileOutputStream fos = new FileOutputStream(file);
- byte[] buffer = new byte[4096];
- int len = 0;
- while ((len = is.read(buffer)) > 0)
- fos.write(buffer, 0, len);
- fos.close();
-
- try {
- is.close();
- } catch (IOException e) {
- s_logger.warn("Exception while closing download stream from "
- + url + ", ", e);
- }
- }
-
- private void loadProperties() throws ConfigurationException {
- final File file = PropertiesUtil.findConfigFile("agent.properties");
- if (file == null) {
- throw new ConfigurationException("Unable to find agent.properties.");
- }
-
- s_logger.info("agent.properties found at " + file.getAbsolutePath());
-
- try {
- _properties.load(new FileInputStream(file));
- } catch (final FileNotFoundException ex) {
- throw new CloudRuntimeException("Cannot find the file: "
- + file.getAbsolutePath(), ex);
- } catch (final IOException ex) {
- throw new CloudRuntimeException("IOException in reading "
- + file.getAbsolutePath(), ex);
- }
- }
-
- protected boolean parseCommand(final String[] args)
- throws ConfigurationException {
- String host = null;
- String workers = null;
- String port = null;
- String zone = null;
- String pod = null;
- String guid = null;
- for (int i = 0; i < args.length; i++) {
- final String[] tokens = args[i].split("=");
- if (tokens.length != 2) {
- System.out.println("Invalid Parameter: " + args[i]);
- continue;
- }
-
- // save command line properties
- _cmdLineProperties.put(tokens[0], tokens[1]);
-
- if (tokens[0].equalsIgnoreCase("port")) {
- port = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("threads")) {
- workers = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("host")) {
- host = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("zone")) {
- zone = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("pod")) {
- pod = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("guid")) {
- guid = tokens[1];
- } else if (tokens[0].equalsIgnoreCase("eth1ip")) {
- _privateIp = tokens[1];
- }
- }
-
- if (port == null) {
- port = getProperty(null, "port");
- }
-
- _port = NumbersUtil.parseInt(port, 8250);
-
- _proxyPort = NumbersUtil.parseInt(
- getProperty(null, "consoleproxy.httpListenPort"), 443);
-
- if (workers == null) {
- workers = getProperty(null, "workers");
- }
-
- _workers = NumbersUtil.parseInt(workers, 5);
-
- if (host == null) {
- host = getProperty(null, "host");
- }
-
- if (host == null) {
- host = "localhost";
- }
- _host = host;
-
- if (zone != null)
- _zone = zone;
- else
- _zone = getProperty(null, "zone");
- if (_zone == null || (_zone.startsWith("@") && _zone.endsWith("@"))) {
- _zone = "default";
- }
-
- if (pod != null)
- _pod = pod;
- else
- _pod = getProperty(null, "pod");
- if (_pod == null || (_pod.startsWith("@") && _pod.endsWith("@"))) {
- _pod = "default";
- }
-
- if (_host == null || (_host.startsWith("@") && _host.endsWith("@"))) {
- throw new ConfigurationException(
- "Host is not configured correctly: " + _host);
- }
-
- final String retries = getProperty(null, "ping.retries");
- _pingRetries = NumbersUtil.parseInt(retries, 5);
-
- String value = getProperty(null, "developer");
- boolean developer = Boolean.parseBoolean(value);
-
- if (guid != null)
- _guid = guid;
- else
- _guid = getProperty(null, "guid");
- if (_guid == null) {
- if (!developer) {
- throw new ConfigurationException("Unable to find the guid");
- }
- _guid = UUID.randomUUID().toString();
- }
-
- return true;
- }
-
- private void init(String[] args) throws ConfigurationException {
-
- final ComponentLocator locator = ComponentLocator.getLocator("agent");
-
- final Class<?> c = this.getClass();
- _version = c.getPackage().getImplementationVersion();
- if (_version == null) {
- throw new CloudRuntimeException(
- "Unable to find the implementation version of this agent");
- }
- s_logger.info("Implementation Version is " + _version);
-
- parseCommand(args);
-
- _storage = locator.getManager(StorageComponent.class);
- if (_storage == null) {
- s_logger.info("Defaulting to using properties file for storage");
- _storage = new PropertiesStorage();
- _storage.configure("Storage", new HashMap<String, Object>());
- }
-
- // merge with properties from command line to let resource access
- // command line parameters
- for (Map.Entry<String, Object> cmdLineProp : getCmdLineProperties()
- .entrySet()) {
- _properties.put(cmdLineProp.getKey(), cmdLineProp.getValue());
- }
-
- final Adapters adapters = locator.getAdapters(BackoffAlgorithm.class);
- final Enumeration en = adapters.enumeration();
- while (en.hasMoreElements()) {
- _backoff = (BackoffAlgorithm) en.nextElement();
- break;
- }
- if (en.hasMoreElements()) {
- s_logger.info("More than one backoff algorithm specified. Using the first one ");
- }
-
- if (_backoff == null) {
- s_logger.info("Defaulting to the constant time backoff algorithm");
- _backoff = new ConstantTimeBackoff();
- _backoff.configure("ConstantTimeBackoff",
- new HashMap<String, Object>());
- }
- }
-
- private void launchAgent() throws ConfigurationException {
- String resourceClassNames = getProperty(null, "resource");
- s_logger.trace("resource=" + resourceClassNames);
- if (resourceClassNames != null) {
- launchAgentFromClassInfo(resourceClassNames);
- return;
- }
-
- launchAgentFromTypeInfo();
- }
-
- private boolean needConsoleProxy() {
- for (Agent agent : _agents) {
- if (agent.getResource().getType().equals(Host.Type.ConsoleProxy)
- || agent.getResource().getType().equals(Host.Type.Routing))
- return true;
- }
- return false;
- }
-
- private int getConsoleProxyPort() {
- int port = NumbersUtil.parseInt(
- getProperty(null, "consoleproxy.httpListenPort"), 443);
- return port;
- }
-
- private void openPortWithIptables(int port) {
- // TODO
- }
-
- private void launchConsoleProxy() throws ConfigurationException {
- if (!needConsoleProxy()) {
- if (s_logger.isInfoEnabled())
- s_logger.info("Storage only agent, no need to start console proxy on it");
- return;
- }
-
- int port = getConsoleProxyPort();
- openPortWithIptables(port);
-
- _consoleProxyMain = new Thread(new Runnable() {
- public void run() {
- try {
- Class<?> consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy");
-
- try {
- Method method = consoleProxyClazz.getMethod("start",
- Properties.class);
- method.invoke(null, _properties);
- } catch (SecurityException e) {
- s_logger.error("Unable to launch console proxy due to SecurityException");
- System.exit(ExitStatus.Error.value());
- } catch (NoSuchMethodException e) {
- s_logger.error("Unable to launch console proxy due to NoSuchMethodException");
- System.exit(ExitStatus.Error.value());
- } catch (IllegalArgumentException e) {
- s_logger.error("Unable to launch console proxy due to IllegalArgumentException");
- System.exit(ExitStatus.Error.value());
- } catch (IllegalAccessException e) {
- s_logger.error("Unable to launch console proxy due to IllegalAccessException");
- System.exit(ExitStatus.Error.value());
- } catch (InvocationTargetException e) {
- s_logger.error("Unable to launch console proxy due to InvocationTargetException");
- System.exit(ExitStatus.Error.value());
- }
- } catch (final ClassNotFoundException e) {
- s_logger.error("Unable to launch console proxy due to ClassNotFoundException");
- System.exit(ExitStatus.Error.value());
- }
- }
- }, "Console-Proxy-Main");
- _consoleProxyMain.setDaemon(true);
- _consoleProxyMain.start();
- }
-
- private void launchAgentFromClassInfo(String resourceClassNames)
- throws ConfigurationException {
- String[] names = resourceClassNames.split("\\|");
- for (String name : names) {
- Class<?> impl;
- try {
- impl = Class.forName(name);
- final Constructor<?> constructor = impl
- .getDeclaredConstructor();
- constructor.setAccessible(true);
- ServerResource resource = (ServerResource) constructor
- .newInstance();
- launchAgent(getNextAgentId(), resource);
- } catch (final ClassNotFoundException e) {
- throw new ConfigurationException("Resource class not found: "
- + name + " due to: " + e.toString());
- } catch (final SecurityException e) {
- throw new ConfigurationException(
- "Security excetion when loading resource: " + name
- + " due to: " + e.toString());
- } catch (final NoSuchMethodException e) {
- throw new ConfigurationException(
- "Method not found excetion when loading resource: "
- + name + " due to: " + e.toString());
- } catch (final IllegalArgumentException e) {
- throw new ConfigurationException(
- "Illegal argument excetion when loading resource: "
- + name + " due to: " + e.toString());
- } catch (final InstantiationException e) {
- throw new ConfigurationException(
- "Instantiation excetion when loading resource: " + name
- + " due to: " + e.toString());
- } catch (final IllegalAccessException e) {
- throw new ConfigurationException(
- "Illegal access exception when loading resource: "
- + name + " due to: " + e.toString());
- } catch (final InvocationTargetException e) {
- throw new ConfigurationException(
- "Invocation target exception when loading resource: "
- + name + " due to: " + e.toString());
- }
- }
- }
-
- private void launchAgentFromTypeInfo() throws ConfigurationException {
- String typeInfo = getProperty(null, "type");
- if (typeInfo == null) {
- s_logger.error("Unable to retrieve the type");
- throw new ConfigurationException(
- "Unable to retrieve the type of this agent.");
- }
- s_logger.trace("Launching agent based on type=" + typeInfo);
- }
-
- private void launchAgent(int localAgentId, ServerResource resource)
- throws ConfigurationException {
- // we don't track agent after it is launched for now
- Agent agent = new Agent(this, localAgentId, resource);
- _agents.add(agent);
- agent.start();
- }
-
- public synchronized int getNextAgentId() {
- return _nextAgentId++;
- }
-
- private void run(String[] args) {
- try {
- System.setProperty("java.net.preferIPv4Stack", "true");
-
- loadProperties();
- init(args);
-
- String instance = getProperty(null, "instance");
- if (instance == null) {
- if (Boolean.parseBoolean(getProperty(null, "developer"))) {
- instance = UUID.randomUUID().toString();
- } else {
- instance = "";
- }
- } else {
- instance += ".";
- }
-
- String pidDir = getProperty(null, "piddir");
-
- final String run = "agent." + instance + "pid";
- s_logger.debug("Checking to see if " + run + "exists.");
- ProcessUtil.pidCheck(pidDir, run);
-
- launchAgent();
-
- //
- // For both KVM & Xen-Server hypervisor, we have switched to
- // VM-based console proxy solution, disable launching
- // of console proxy here
- //
- // launchConsoleProxy();
- //
-
- try {
- while (!_exit)
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
-
- } catch (final ConfigurationException e) {
- s_logger.error("Unable to start agent: " + e.getMessage());
- System.out.println("Unable to start agent: " + e.getMessage());
- System.exit(ExitStatus.Configuration.value());
- } catch (final Exception e) {
- s_logger.error("Unable to start agent: ", e);
- System.out.println("Unable to start agent: " + e.getMessage());
- System.exit(ExitStatus.Error.value());
- }
- }
-
- public void stop() {
- _exit = true;
- if (_consoleProxyMain != null) {
- _consoleProxyMain.interrupt();
- }
- }
-
- public static void main(String[] args) {
- AgentShell shell = new AgentShell();
- Runtime.getRuntime().addShutdownHook(new ShutdownThread(shell));
- shell.run(args);
- }
-
- private static class ShutdownThread extends Thread {
- AgentShell _shell;
-
- public ShutdownThread(AgentShell shell) {
- this._shell = shell;
- }
-
- @Override
- public void run() {
- _shell.stop();
- }
- }
+ private static final Logger s_logger = Logger.getLogger(AgentShell.class
+ .getName());
+
+ private final Properties _properties = new Properties();
+ private final Map<String, Object> _cmdLineProperties = new HashMap<String, Object>();
+ private StorageComponent _storage;
+ private BackoffAlgorithm _backoff;
+ private String _version;
+ private String _zone;
+ private String _pod;
+ private String _host;
+ private String _privateIp;
+ private int _port;
+ private int _proxyPort;
+ private int _workers;
+ private String _guid;
+ private int _nextAgentId = 1;
+ private volatile boolean _exit = false;
+ private int _pingRetries;
+ private Thread _consoleProxyMain = null;
+ private final List<Agent> _agents = new ArrayList<Agent>();
+
+ public AgentShell() {
+ }
+
+ @Override
+ public Properties getProperties() {
+ return _properties;
+ }
+
+ @Override
+ public BackoffAlgorithm getBackoffAlgorithm() {
+ return _backoff;
+ }
+
+ @Override
+ public int getPingRetries() {
+ return _pingRetries;
+ }
+
+ @Override
+ public String getVersion() {
+ return _version;
+ }
+
+ @Override
+ public String getZone() {
+ return _zone;
+ }
+
+ @Override
+ public String getPod() {
+ return _pod;
+ }
+
+ @Override
+ public String getHost() {
+ return _host;
+ }
+
+ @Override
+ public String getPrivateIp() {
+ return _privateIp;
+ }
+
+ @Override
+ public int getPort() {
+ return _port;
+ }
+
+ @Override
+ public int getProxyPort() {
+ return _proxyPort;
+ }
+
+ @Override
+ public int getWorkers() {
+ return _workers;
+ }
+
+ @Override
+ public String getGuid() {
+ return _guid;
+ }
+
+ public Map<String, Object> getCmdLineProperties() {
+ return _cmdLineProperties;
+ }
+
+ public String getProperty(String prefix, String name) {
+ if (prefix != null)
+ return _properties.getProperty(prefix + "." + name);
+
+ return _properties.getProperty(name);
+ }
+
+ @Override
+ public String getPersistentProperty(String prefix, String name) {
+ if (prefix != null)
+ return _storage.get(prefix + "." + name);
+ return _storage.get(name);
+ }
+
+ @Override
+ public void setPersistentProperty(String prefix, String name, String value) {
+ if (prefix != null)
+ _storage.persist(prefix + "." + name, value);
+ else
+ _storage.persist(name, value);
+ }
+
+ @Override
+ public void upgradeAgent(final String url) {
+ s_logger.info("Updating agent with binary from " + url);
+ synchronized (this) {
+ final Class<?> c = this.getClass();
+ String path = c.getResource(c.getSimpleName() + ".class")
+ .toExternalForm();
+ final int begin = path.indexOf(File.separator);
+ int end = path.lastIndexOf("!");
+ end = path.lastIndexOf(File.separator, end);
+ path = path.substring(begin, end);
+
+ s_logger.debug("Current binaries reside at " + path);
+
+ File file = null;
+ try {
+ file = File.createTempFile("agent-",
+ "-" + Long.toString(new Date().getTime()));
+ wget(url, file);
+ } catch (final IOException e) {
+ s_logger.warn(
+ "Exception while downloading agent update package, ", e);
+ throw new CloudRuntimeException("Unable to update from " + url
+ + ", exception:" + e.getMessage(), e);
+ }
+
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Unzipping " + file.getAbsolutePath() + " to "
+ + path);
+ }
+
+ final Script unzip = new Script("unzip", 120000, s_logger);
+ unzip.add("-o", "-q"); // overwrite and quiet
+ unzip.add(file.getAbsolutePath());
+ unzip.add("-d", path);
+
+ final String result = unzip.execute();
+ if (result != null) {
+ throw new CloudRuntimeException(
+ "Unable to unzip the retrieved file: " + result);
+ }
+
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Closing the connection to the management server");
+ }
+ }
+
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Exiting to start the new agent.");
+ }
+ System.exit(ExitStatus.Upgrade.value());
+ }
+
+ public static void wget(String url, File file) throws IOException {
+ final HttpClient client = new HttpClient();
+ final GetMethod method = new GetMethod(url);
+ int response;
+ response = client.executeMethod(method);
+ if (response != HttpURLConnection.HTTP_OK) {
+ s_logger.warn("Retrieving from " + url + " gives response code: "
+ + response);
+ throw new CloudRuntimeException("Unable to download from " + url
+ + ". Response code is " + response);
+ }
+
+ final InputStream is = method.getResponseBodyAsStream();
+ s_logger.debug("Downloading content into " + file.getAbsolutePath());
+
+ final FileOutputStream fos = new FileOutputStream(file);
+ byte[] buffer = new byte[4096];
+ int len = 0;
+ while ((len = is.read(buffer)) > 0)
+ fos.write(buffer, 0, len);
+ fos.close();
+
+ try {
+ is.close();
+ } catch (IOException e) {
+ s_logger.warn("Exception while closing download stream from "
+ + url + ", ", e);
+ }
+ }
+
+ private void loadProperties() throws ConfigurationException {
+ final File file = PropertiesUtil.findConfigFile("agent.properties");
+ if (file == null) {
+ throw new ConfigurationException("Unable to find agent.properties.");
+ }
+
+ s_logger.info("agent.properties found at " + file.getAbsolutePath());
+
+ try {
+ _properties.load(new FileInputStream(file));
+ } catch (final FileNotFoundException ex) {
+ throw new CloudRuntimeException("Cannot find the file: "
+ + file.getAbsolutePath(), ex);
+ } catch (final IOException ex) {
+ throw new CloudRuntimeException("IOException in reading "
+ + file.getAbsolutePath(), ex);
+ }
+ }
+
+ protected boolean parseCommand(final String[] args)
+ throws ConfigurationException {
+ String host = null;
+ String workers = null;
+ String port = null;
+ String zone = null;
+ String pod = null;
+ String guid = null;
+ for (int i = 0; i < args.length; i++) {
+ final String[] tokens = args[i].split("=");
+ if (tokens.length != 2) {
+ System.out.println("Invalid Parameter: " + args[i]);
+ continue;
+ }
+
+ // save command line properties
+ _cmdLineProperties.put(tokens[0], tokens[1]);
+
+ if (tokens[0].equalsIgnoreCase("port")) {
+ port = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("threads")) {
+ workers = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("host")) {
+ host = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("zone")) {
+ zone = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("pod")) {
+ pod = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("guid")) {
+ guid = tokens[1];
+ } else if (tokens[0].equalsIgnoreCase("eth1ip")) {
+ _privateIp = tokens[1];
+ }
+ }
+
+ if (port == null) {
+ port = getProperty(null, "port");
+ }
+
+ _port = NumbersUtil.parseInt(port, 8250);
+
+ _proxyPort = NumbersUtil.parseInt(
+ getProperty(null, "consoleproxy.httpListenPort"), 443);
+
+ if (workers == null) {
+ workers = getProperty(null, "workers");
+ }
+
+ _workers = NumbersUtil.parseInt(workers, 5);
+
+ if (host == null) {
+ host = getProperty(null, "host");
+ }
+
+ if (host == null) {
+ host = "localhost";
+ }
+ _host = host;
+
+ if (zone != null)
+ _zone = zone;
+ else
+ _zone = getProperty(null, "zone");
+ if (_zone == null || (_zone.startsWith("@") && _zone.endsWith("@"))) {
+ _zone = "default";
+ }
+
+ if (pod != null)
+ _pod = pod;
+ else
+ _pod = getProperty(null, "pod");
+ if (_pod == null || (_pod.startsWith("@") && _pod.endsWith("@"))) {
+ _pod = "default";
+ }
+
+ if (_host == null || (_host.startsWith("@") && _host.endsWith("@"))) {
+ throw new ConfigurationException(
+ "Host is not configured correctly: " + _host);
+ }
+
+ final String retries = getProperty(null, "ping.retries");
+ _pingRetries = NumbersUtil.parseInt(retries, 5);
+
+ String value = getProperty(null, "developer");
+ boolean developer = Boolean.parseBoolean(value);
+
+ if (guid != null)
+ _guid = guid;
+ else
+ _guid = getProperty(null, "guid");
+ if (_guid == null) {
+ if (!developer) {
+ throw new ConfigurationException("Unable to find the guid");
+ }
+ _guid = UUID.randomUUID().toString();
+ }
+
+ return true;
+ }
+
+ private void init(String[] args) throws ConfigurationException {
+
+ final ComponentLocator locator = ComponentLocator.getLocator("agent");
+
+ final Class<?> c = this.getClass();
+ _version = c.getPackage().getImplementationVersion();
+ if (_version == null) {
+ throw new CloudRuntimeException(
+ "Unable to find the implementation version of this agent");
+ }
+ s_logger.info("Implementation Version is " + _version);
+
+ parseCommand(args);
+
+ _storage = locator.getManager(StorageComponent.class);
+ if (_storage == null) {
+ s_logger.info("Defaulting to using properties file for storage");
+ _storage = new PropertiesStorage();
+ _storage.configure("Storage", new HashMap<String, Object>());
+ }
+
+ // merge with properties from command line to let resource access
+ // command line parameters
+ for (Map.Entry<String, Object> cmdLineProp : getCmdLineProperties()
+ .entrySet()) {
+ _properties.put(cmdLineProp.getKey(), cmdLineProp.getValue());
+ }
+
+ final Adapters adapters = locator.getAdapters(BackoffAlgorithm.class);
+ final Enumeration en = adapters.enumeration();
+ while (en.hasMoreElements()) {
+ _backoff = (BackoffAlgorithm) en.nextElement();
+ break;
+ }
+ if (en.hasMoreElements()) {
+ s_logger.info("More than one backoff algorithm specified. Using the first one ");
+ }
+
+ if (_backoff == null) {
+ s_logger.info("Defaulting to the constant time backoff algorithm");
+ _backoff = new ConstantTimeBackoff();
+ _backoff.configure("ConstantTimeBackoff",
+ new HashMap<String, Object>());
+ }
+ }
+
+ private void launchAgent() throws ConfigurationException {
+ String resourceClassNames = getProperty(null, "resource");
+ s_logger.trace("resource=" + resourceClassNames);
+ if (resourceClassNames != null) {
+ launchAgentFromClassInfo(resourceClassNames);
+ return;
+ }
+
+ launchAgentFromTypeInfo();
+ }
+
+ private boolean needConsoleProxy() {
+ for (Agent agent : _agents) {
+ if (agent.getResource().getType().equals(Host.Type.ConsoleProxy)
+ || agent.getResource().getType().equals(Host.Type.Routing))
+ return true;
+ }
+ return false;
+ }
+
+ private int getConsoleProxyPort() {
+ int port = NumbersUtil.parseInt(
+ getProperty(null, "consoleproxy.httpListenPort"), 443);
+ return port;
+ }
+
+ private void openPortWithIptables(int port) {
+ // TODO
+ }
+
+ private void launchConsoleProxy() throws ConfigurationException {
+ if (!needConsoleProxy()) {
+ if (s_logger.isInfoEnabled())
+ s_logger.info("Storage only agent, no need to start console proxy on it");
+ return;
+ }
+
+ int port = getConsoleProxyPort();
+ openPortWithIptables(port);
+
+ _consoleProxyMain = new Thread(new Runnable() {
+ public void run() {
+ try {
+ Class<?> consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy");
+
+ try {
+ Method method = consoleProxyClazz.getMethod("start",
+ Properties.class);
+ method.invoke(null, _properties);
+ } catch (SecurityException e) {
+ s_logger.error("Unable to launch console proxy due to SecurityException");
+ System.exit(ExitStatus.Error.value());
+ } catch (NoSuchMethodException e) {
+ s_logger.error("Unable to launch console proxy due to NoSuchMethodException");
+ System.exit(ExitStatus.Error.value());
+ } catch (IllegalArgumentException e) {
+ s_logger.error("Unable to launch console proxy due to IllegalArgumentException");
+ System.exit(ExitStatus.Error.value());
+ } catch (IllegalAccessException e) {
+ s_logger.error("Unable to launch console proxy due to IllegalAccessException");
+ System.exit(ExitStatus.Error.value());
+ } catch (InvocationTargetException e) {
+ s_logger.error("Unable to launch console proxy due to InvocationTargetException");
+ System.exit(ExitStatus.Error.value());
+ }
+ } catch (final ClassNotFoundException e) {
+ s_logger.error("Unable to launch console proxy due to ClassNotFoundException");
+ System.exit(ExitStatus.Error.value());
+ }
+ }
+ }, "Console-Proxy-Main");
+ _consoleProxyMain.setDaemon(true);
+ _consoleProxyMain.start();
+ }
+
+ private void launchAgentFromClassInfo(String resourceClassNames)
+ throws ConfigurationException {
+ String[] names = resourceClassNames.split("\\|");
+ for (String name : names) {
+ Class<?> impl;
+ try {
+ impl = Class.forName(name);
+ final Constructor<?> constructor = impl
+ .getDeclaredConstructor();
+ constructor.setAccessible(true);
+ ServerResource resource = (ServerResource) constructor
+ .newInstance();
+ launchAgent(getNextAgentId(), resource);
+ } catch (final ClassNotFoundException e) {
+ throw new ConfigurationException("Resource class not found: "
+ + name + " due to: " + e.toString());
+ } catch (final SecurityException e) {
+ throw new ConfigurationException(
+ "Security excetion when loading resource: " + name
+ + " due to: " + e.toString());
+ } catch (final NoSuchMethodException e) {
+ throw new ConfigurationException(
+ "Method not found excetion when loading resource: "
+ + name + " due to: " + e.toString());
+ } catch (final IllegalArgumentException e) {
+ throw new ConfigurationException(
+ "Illegal argument excetion when loading resource: "
+ + name + " due to: " + e.toString());
+ } catch (final InstantiationException e) {
+ throw new ConfigurationException(
+ "Instantiation excetion when loading resource: " + name
+ + " due to: " + e.toString());
+ } catch (final IllegalAccessException e) {
+ throw new ConfigurationException(
+ "Illegal access exception when loading resource: "
+ + name + " due to: " + e.toString());
+ } catch (final InvocationTargetException e) {
+ throw new ConfigurationException(
+ "Invocation target exception when loading resource: "
+ + name + " due to: " + e.toString());
+ }
+ }
+ }
+
+ private void launchAgentFromTypeInfo() throws ConfigurationException {
+ String typeInfo = getProperty(null, "type");
+ if (typeInfo == null) {
+ s_logger.error("Unable to retrieve the type");
+ throw new ConfigurationException(
+ "Unable to retrieve the type of this agent.");
+ }
+ s_logger.trace("Launching agent based on type=" + typeInfo);
+ }
+
+ private void launchAgent(int localAgentId, ServerResource resource)
+ throws ConfigurationException {
+ // we don't track agent after it is launched for now
+ Agent agent = new Agent(this, localAgentId, resource);
+ _agents.add(agent);
+ agent.start();
+ }
+
+ public synchronized int getNextAgentId() {
+ return _nextAgentId++;
+ }
+
+ private void run(String[] args) {
+ try {
+ System.setProperty("java.net.preferIPv4Stack", "true");
+
+ loadProperties();
+ init(args);
+
+ String instance = getProperty(null, "instance");
+ if (instance == null) {
+ if (Boolean.parseBoolean(getProperty(null, "developer"))) {
+ instance = UUID.randomUUID().toString();
+ } else {
+ instance = "";
+ }
+ } else {
+ instance += ".";
+ }
+
+ String pidDir = getProperty(null, "piddir");
+
+ final String run = "agent." + instance + "pid";
+ s_logger.debug("Checking to see if " + run + "exists.");
+ ProcessUtil.pidCheck(pidDir, run);
+
+ launchAgent();
+
+ //
+ // For both KVM & Xen-Server hypervisor, we have switched to
+ // VM-based console proxy solution, disable launching
+ // of console proxy here
+ //
+ // launchConsoleProxy();
+ //
+
+ try {
+ while (!_exit)
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ }
+
+ } catch (final ConfigurationException e) {
+ s_logger.error("Unable to start agent: " + e.getMessage());
+ System.out.println("Unable to start agent: " + e.getMessage());
+ System.exit(ExitStatus.Configuration.value());
+ } catch (final Exception e) {
+ s_logger.error("Unable to start agent: ", e);
+ System.out.println("Unable to start agent: " + e.getMessage());
+ System.exit(ExitStatus.Error.value());
+ }
+ }
+
+ public void stop() {
+ _exit = true;
+ if (_consoleProxyMain != null) {
+ _consoleProxyMain.interrupt();
+ }
+ }
+
+ public static void main(String[] args) {
+ AgentShell shell = new AgentShell();
+ Runtime.getRuntime().addShutdownHook(new ShutdownThread(shell));
+ shell.run(args);
+ }
+
+ private static class ShutdownThread extends Thread {
+ AgentShell _shell;
+
+ public ShutdownThread(AgentShell shell) {
+ this._shell = shell;
+ }
+
+ @Override
+ public void run() {
+ _shell.stop();
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/IAgentShell.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/IAgentShell.java b/agent/src/com/cloud/agent/IAgentShell.java
index bd0b976..93aaa00 100644
--- a/agent/src/com/cloud/agent/IAgentShell.java
+++ b/agent/src/com/cloud/agent/IAgentShell.java
@@ -22,35 +22,35 @@ import java.util.Properties;
import com.cloud.utils.backoff.BackoffAlgorithm;
public interface IAgentShell {
- public Map<String, Object> getCmdLineProperties();
+ public Map<String, Object> getCmdLineProperties();
- public Properties getProperties();
+ public Properties getProperties();
- public String getPersistentProperty(String prefix, String name);
+ public String getPersistentProperty(String prefix, String name);
- public void setPersistentProperty(String prefix, String name, String value);
+ public void setPersistentProperty(String prefix, String name, String value);
- public String getHost();
+ public String getHost();
- public String getPrivateIp();
+ public String getPrivateIp();
- public int getPort();
+ public int getPort();
- public int getWorkers();
+ public int getWorkers();
- public int getProxyPort();
+ public int getProxyPort();
- public String getGuid();
+ public String getGuid();
- public String getZone();
+ public String getZone();
- public String getPod();
+ public String getPod();
- public BackoffAlgorithm getBackoffAlgorithm();
+ public BackoffAlgorithm getBackoffAlgorithm();
- public int getPingRetries();
+ public int getPingRetries();
- public void upgradeAgent(final String url);
+ public void upgradeAgent(final String url);
- public String getVersion();
+ public String getVersion();
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java b/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java
index b058834..058aefa 100755
--- a/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java
+++ b/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java
@@ -27,50 +27,50 @@ import com.cloud.utils.component.PluggableService;
import com.cloud.utils.db.GenericDao;
public class AgentComponentLibraryBase extends ComponentLibraryBase {
- @Override
- public Map<String, ComponentInfo<GenericDao<?, ?>>> getDaos() {
- return null;
- }
+ @Override
+ public Map<String, ComponentInfo<GenericDao<?, ?>>> getDaos() {
+ return null;
+ }
- @Override
- public Map<String, ComponentInfo<Manager>> getManagers() {
- if (_managers.size() == 0) {
- populateManagers();
- }
- return _managers;
- }
+ @Override
+ public Map<String, ComponentInfo<Manager>> getManagers() {
+ if (_managers.size() == 0) {
+ populateManagers();
+ }
+ return _managers;
+ }
- @Override
- public Map<String, List<ComponentInfo<Adapter>>> getAdapters() {
- if (_adapters.size() == 0) {
- populateAdapters();
- }
- return _adapters;
- }
+ @Override
+ public Map<String, List<ComponentInfo<Adapter>>> getAdapters() {
+ if (_adapters.size() == 0) {
+ populateAdapters();
+ }
+ return _adapters;
+ }
- @Override
- public Map<Class<?>, Class<?>> getFactories() {
- return null;
- }
+ @Override
+ public Map<Class<?>, Class<?>> getFactories() {
+ return null;
+ }
- protected void populateManagers() {
- // addManager("StackMaidManager", StackMaidManagerImpl.class);
- }
+ protected void populateManagers() {
+ // addManager("StackMaidManager", StackMaidManagerImpl.class);
+ }
- protected void populateAdapters() {
+ protected void populateAdapters() {
- }
+ }
- protected void populateServices() {
+ protected void populateServices() {
- }
+ }
- @Override
- public Map<String, ComponentInfo<PluggableService>> getPluggableServices() {
- if (_pluggableServices.size() == 0) {
- populateServices();
- }
- return _pluggableServices;
- }
+ @Override
+ public Map<String, ComponentInfo<PluggableService>> getPluggableServices() {
+ if (_pluggableServices.size() == 0) {
+ populateServices();
+ }
+ return _pluggableServices;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/dao/StorageComponent.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/dao/StorageComponent.java b/agent/src/com/cloud/agent/dao/StorageComponent.java
index 576982f..afb9467 100755
--- a/agent/src/com/cloud/agent/dao/StorageComponent.java
+++ b/agent/src/com/cloud/agent/dao/StorageComponent.java
@@ -22,7 +22,7 @@ import com.cloud.utils.component.Manager;
*
*/
public interface StorageComponent extends Manager {
- String get(String key);
+ String get(String key);
- void persist(String key, String value);
+ void persist(String key, String value);
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java b/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java
index e3598a9..b94ae83 100755
--- a/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java
+++ b/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java
@@ -39,92 +39,92 @@ import com.cloud.utils.PropertiesUtil;
**/
@Local(value = { StorageComponent.class })
public class PropertiesStorage implements StorageComponent {
- private static final Logger s_logger = Logger
- .getLogger(PropertiesStorage.class);
- Properties _properties = new Properties();
- File _file;
- String _name;
+ private static final Logger s_logger = Logger
+ .getLogger(PropertiesStorage.class);
+ Properties _properties = new Properties();
+ File _file;
+ String _name;
- @Override
- public synchronized String get(String key) {
- return _properties.getProperty(key);
- }
+ @Override
+ public synchronized String get(String key) {
+ return _properties.getProperty(key);
+ }
- @Override
- public synchronized void persist(String key, String value) {
- _properties.setProperty(key, value);
- FileOutputStream output = null;
- try {
- output = new FileOutputStream(_file);
- _properties.store(output, _name);
- output.flush();
- output.close();
- } catch (FileNotFoundException e) {
- s_logger.error("Who deleted the file? ", e);
- } catch (IOException e) {
- s_logger.error("Uh-oh: ", e);
- } finally {
- if (output != null) {
- try {
- output.close();
- } catch (IOException e) {
- // ignore.
- }
- }
- }
- }
+ @Override
+ public synchronized void persist(String key, String value) {
+ _properties.setProperty(key, value);
+ FileOutputStream output = null;
+ try {
+ output = new FileOutputStream(_file);
+ _properties.store(output, _name);
+ output.flush();
+ output.close();
+ } catch (FileNotFoundException e) {
+ s_logger.error("Who deleted the file? ", e);
+ } catch (IOException e) {
+ s_logger.error("Uh-oh: ", e);
+ } finally {
+ if (output != null) {
+ try {
+ output.close();
+ } catch (IOException e) {
+ // ignore.
+ }
+ }
+ }
+ }
- @Override
- public boolean configure(String name, Map<String, Object> params) {
- _name = name;
- String path = (String) params.get("path");
- if (path == null) {
- path = "agent.properties";
- }
+ @Override
+ public boolean configure(String name, Map<String, Object> params) {
+ _name = name;
+ String path = (String) params.get("path");
+ if (path == null) {
+ path = "agent.properties";
+ }
- File file = PropertiesUtil.findConfigFile(path);
- if (file == null) {
- file = new File(path);
- try {
- if (!file.createNewFile()) {
- s_logger.error("Unable to create _file: "
- + file.getAbsolutePath());
- return false;
- }
- } catch (IOException e) {
- s_logger.error(
- "Unable to create _file: " + file.getAbsolutePath(), e);
- return false;
- }
- }
+ File file = PropertiesUtil.findConfigFile(path);
+ if (file == null) {
+ file = new File(path);
+ try {
+ if (!file.createNewFile()) {
+ s_logger.error("Unable to create _file: "
+ + file.getAbsolutePath());
+ return false;
+ }
+ } catch (IOException e) {
+ s_logger.error(
+ "Unable to create _file: " + file.getAbsolutePath(), e);
+ return false;
+ }
+ }
- try {
- _properties.load(new FileInputStream(file));
- _file = file;
- } catch (FileNotFoundException e) {
- s_logger.error("How did we get here? ", e);
- return false;
- } catch (IOException e) {
- s_logger.error("IOException: ", e);
- return false;
- }
+ try {
+ _properties.load(new FileInputStream(file));
+ _file = file;
+ } catch (FileNotFoundException e) {
+ s_logger.error("How did we get here? ", e);
+ return false;
+ } catch (IOException e) {
+ s_logger.error("IOException: ", e);
+ return false;
+ }
- return true;
- }
+ return true;
+ }
- @Override
- public String getName() {
- return _name;
- }
+ @Override
+ public String getName() {
+ return _name;
+ }
- @Override
- public boolean start() {
- return true;
- }
+ @Override
+ public boolean start() {
+ return true;
+ }
- @Override
- public boolean stop() {
- return true;
- }
+ @Override
+ public boolean stop() {
+ return true;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java b/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java
index 53856b6..94aa274 100644
--- a/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java
+++ b/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java
@@ -31,36 +31,36 @@ import org.apache.log4j.Logger;
import com.cloud.utils.concurrency.NamedThreadFactory;
public class DhcpProtocolParserServer extends Thread {
- private static final Logger s_logger = Logger
- .getLogger(DhcpProtocolParserServer.class);;
- protected ExecutorService _executor;
- private int dhcpServerPort = 67;
- private int bufferSize = 300;
- protected boolean _running = false;
+ private static final Logger s_logger = Logger
+ .getLogger(DhcpProtocolParserServer.class);;
+ protected ExecutorService _executor;
+ private int dhcpServerPort = 67;
+ private int bufferSize = 300;
+ protected boolean _running = false;
- public DhcpProtocolParserServer(int workers) {
- _executor = new ThreadPoolExecutor(workers, 10 * workers, 1,
- TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
- new NamedThreadFactory("DhcpListener"));
- _running = true;
- }
+ public DhcpProtocolParserServer(int workers) {
+ _executor = new ThreadPoolExecutor(workers, 10 * workers, 1,
+ TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
+ new NamedThreadFactory("DhcpListener"));
+ _running = true;
+ }
- public void run() {
- while (_running) {
- try {
- DatagramSocket dhcpSocket = new DatagramSocket(dhcpServerPort,
- InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }));
- dhcpSocket.setBroadcast(true);
+ public void run() {
+ while (_running) {
+ try {
+ DatagramSocket dhcpSocket = new DatagramSocket(dhcpServerPort,
+ InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }));
+ dhcpSocket.setBroadcast(true);
- while (true) {
- byte[] buf = new byte[bufferSize];
- DatagramPacket dgp = new DatagramPacket(buf, buf.length);
- dhcpSocket.receive(dgp);
- // _executor.execute(new DhcpPacketParser(buf));
- }
- } catch (IOException e) {
- s_logger.debug(e.getMessage());
- }
- }
- }
+ while (true) {
+ byte[] buf = new byte[bufferSize];
+ DatagramPacket dgp = new DatagramPacket(buf, buf.length);
+ dhcpSocket.receive(dgp);
+ // _executor.execute(new DhcpPacketParser(buf));
+ }
+ } catch (IOException e) {
+ s_logger.debug(e.getMessage());
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java b/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java
index 36b9c24..e25e2cf 100644
--- a/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java
+++ b/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java
@@ -25,16 +25,16 @@ import com.cloud.utils.component.Adapter;
public interface DhcpSnooper extends Adapter {
- public InetAddress getIPAddr(String macAddr, String vmName);
+ public InetAddress getIPAddr(String macAddr, String vmName);
- public InetAddress getDhcpServerIP();
+ public InetAddress getDhcpServerIP();
- public void cleanup(String macAddr, String vmName);
+ public void cleanup(String macAddr, String vmName);
- public Map<String, InetAddress> syncIpAddr();
+ public Map<String, InetAddress> syncIpAddr();
- public boolean stop();
+ public boolean stop();
- public void initializeMacTable(List<Pair<String, String>> macVmNameList);
+ public void initializeMacTable(List<Pair<String, String>> macVmNameList);
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java b/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java
index 27c08f3..11ea824 100644
--- a/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java
+++ b/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java
@@ -39,104 +39,104 @@ import com.cloud.utils.net.NetUtils;
@Local(value = { DhcpSnooper.class })
public class FakeDhcpSnooper implements DhcpSnooper {
- private static final Logger s_logger = Logger
- .getLogger(FakeDhcpSnooper.class);
- private Queue<String> _ipAddresses = new ConcurrentLinkedQueue<String>();
- private Map<String, String> _macIpMap = new ConcurrentHashMap<String, String>();
- private Map<String, InetAddress> _vmIpMap = new ConcurrentHashMap<String, InetAddress>();
-
- @Override
- public boolean configure(String name, Map<String, Object> params)
- throws ConfigurationException {
- String guestIpRange = (String) params.get("guest.ip.range");
- if (guestIpRange != null) {
- String[] guestIps = guestIpRange.split("-");
- if (guestIps.length == 2) {
- long start = NetUtils.ip2Long(guestIps[0]);
- long end = NetUtils.ip2Long(guestIps[1]);
- while (start <= end) {
- _ipAddresses.offer(NetUtils.long2Ip(start++));
- }
- }
- }
- return true;
- }
-
- @Override
- public boolean start() {
- return true;
- }
-
- @Override
- public String getName() {
- return "FakeDhcpSnooper";
- }
-
- @Override
- public InetAddress getIPAddr(String macAddr, String vmName) {
- String ipAddr = _ipAddresses.poll();
- if (ipAddr == null) {
- s_logger.warn("No ip addresses left in queue");
- return null;
- }
- try {
- InetAddress inetAddr = InetAddress.getByName(ipAddr);
- _macIpMap.put(macAddr.toLowerCase(), ipAddr);
- _vmIpMap.put(vmName, inetAddr);
- s_logger.info("Got ip address " + ipAddr + " for vm " + vmName
- + " mac=" + macAddr.toLowerCase());
- return inetAddr;
- } catch (UnknownHostException e) {
- s_logger.warn("Failed to get InetAddress for " + ipAddr);
- return null;
- }
- }
-
- @Override
- public void cleanup(String macAddr, String vmName) {
- try {
- if (macAddr == null) {
- return;
- }
- InetAddress inetAddr = _vmIpMap.remove(vmName);
- String ipAddr = inetAddr.getHostName();
- for (Map.Entry<String, String> entry : _macIpMap.entrySet()) {
- if (entry.getValue().equalsIgnoreCase(ipAddr)) {
- macAddr = entry.getKey();
- break;
- }
- }
- ipAddr = _macIpMap.remove(macAddr);
-
- s_logger.info("Cleaning up for mac address: " + macAddr + " ip="
- + ipAddr + " inetAddr=" + inetAddr);
- if (ipAddr != null) {
- _ipAddresses.offer(ipAddr);
- }
- } catch (Exception e) {
- s_logger.debug("Failed to cleanup: " + e.toString());
- }
- }
-
- @Override
- public Map<String, InetAddress> syncIpAddr() {
- return _vmIpMap;
- }
-
- @Override
- public boolean stop() {
- return false;
- }
-
- @Override
- public void initializeMacTable(List<Pair<String, String>> macVmNameList) {
-
- }
-
- @Override
- public InetAddress getDhcpServerIP() {
- // TODO Auto-generated method stub
- return null;
- }
+ private static final Logger s_logger = Logger
+ .getLogger(FakeDhcpSnooper.class);
+ private Queue<String> _ipAddresses = new ConcurrentLinkedQueue<String>();
+ private Map<String, String> _macIpMap = new ConcurrentHashMap<String, String>();
+ private Map<String, InetAddress> _vmIpMap = new ConcurrentHashMap<String, InetAddress>();
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params)
+ throws ConfigurationException {
+ String guestIpRange = (String) params.get("guest.ip.range");
+ if (guestIpRange != null) {
+ String[] guestIps = guestIpRange.split("-");
+ if (guestIps.length == 2) {
+ long start = NetUtils.ip2Long(guestIps[0]);
+ long end = NetUtils.ip2Long(guestIps[1]);
+ while (start <= end) {
+ _ipAddresses.offer(NetUtils.long2Ip(start++));
+ }
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean start() {
+ return true;
+ }
+
+ @Override
+ public String getName() {
+ return "FakeDhcpSnooper";
+ }
+
+ @Override
+ public InetAddress getIPAddr(String macAddr, String vmName) {
+ String ipAddr = _ipAddresses.poll();
+ if (ipAddr == null) {
+ s_logger.warn("No ip addresses left in queue");
+ return null;
+ }
+ try {
+ InetAddress inetAddr = InetAddress.getByName(ipAddr);
+ _macIpMap.put(macAddr.toLowerCase(), ipAddr);
+ _vmIpMap.put(vmName, inetAddr);
+ s_logger.info("Got ip address " + ipAddr + " for vm " + vmName
+ + " mac=" + macAddr.toLowerCase());
+ return inetAddr;
+ } catch (UnknownHostException e) {
+ s_logger.warn("Failed to get InetAddress for " + ipAddr);
+ return null;
+ }
+ }
+
+ @Override
+ public void cleanup(String macAddr, String vmName) {
+ try {
+ if (macAddr == null) {
+ return;
+ }
+ InetAddress inetAddr = _vmIpMap.remove(vmName);
+ String ipAddr = inetAddr.getHostName();
+ for (Map.Entry<String, String> entry : _macIpMap.entrySet()) {
+ if (entry.getValue().equalsIgnoreCase(ipAddr)) {
+ macAddr = entry.getKey();
+ break;
+ }
+ }
+ ipAddr = _macIpMap.remove(macAddr);
+
+ s_logger.info("Cleaning up for mac address: " + macAddr + " ip="
+ + ipAddr + " inetAddr=" + inetAddr);
+ if (ipAddr != null) {
+ _ipAddresses.offer(ipAddr);
+ }
+ } catch (Exception e) {
+ s_logger.debug("Failed to cleanup: " + e.toString());
+ }
+ }
+
+ @Override
+ public Map<String, InetAddress> syncIpAddr() {
+ return _vmIpMap;
+ }
+
+ @Override
+ public boolean stop() {
+ return false;
+ }
+
+ @Override
+ public void initializeMacTable(List<Pair<String, String>> macVmNameList) {
+
+ }
+
+ @Override
+ public InetAddress getDhcpServerIP() {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/mockvm/MockVm.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/mockvm/MockVm.java b/agent/src/com/cloud/agent/mockvm/MockVm.java
index 1589a8f..306a6c4 100644
--- a/agent/src/com/cloud/agent/mockvm/MockVm.java
+++ b/agent/src/com/cloud/agent/mockvm/MockVm.java
@@ -21,61 +21,61 @@ import com.cloud.vm.VirtualMachine.State;
// As storage is mapped from storage device, can virtually treat that VM here does
public class MockVm {
- private String vmName;
- private State state = State.Stopped;
+ private String vmName;
+ private State state = State.Stopped;
- private long ramSize; // unit of Mbytes
- private int cpuCount;
- private int utilization; // in percentage
- private int vncPort; // 0-based allocation, real port number needs to be
- // applied with base
+ private long ramSize; // unit of Mbytes
+ private int cpuCount;
+ private int utilization; // in percentage
+ private int vncPort; // 0-based allocation, real port number needs to be
+ // applied with base
- public MockVm() {
- }
+ public MockVm() {
+ }
- public MockVm(String vmName, State state, long ramSize, int cpuCount,
- int utilization, int vncPort) {
- this.vmName = vmName;
- this.state = state;
- this.ramSize = ramSize;
- this.cpuCount = cpuCount;
- this.utilization = utilization;
- this.vncPort = vncPort;
- }
+ public MockVm(String vmName, State state, long ramSize, int cpuCount,
+ int utilization, int vncPort) {
+ this.vmName = vmName;
+ this.state = state;
+ this.ramSize = ramSize;
+ this.cpuCount = cpuCount;
+ this.utilization = utilization;
+ this.vncPort = vncPort;
+ }
- public String getName() {
- return vmName;
- }
+ public String getName() {
+ return vmName;
+ }
- public State getState() {
- return state;
- }
+ public State getState() {
+ return state;
+ }
- public void setState(State state) {
- this.state = state;
- }
+ public void setState(State state) {
+ this.state = state;
+ }
- public long getRamSize() {
- return ramSize;
- }
+ public long getRamSize() {
+ return ramSize;
+ }
- public int getCpuCount() {
- return cpuCount;
- }
+ public int getCpuCount() {
+ return cpuCount;
+ }
- public int getUtilization() {
- return utilization;
- }
+ public int getUtilization() {
+ return utilization;
+ }
- public int getVncPort() {
- return vncPort;
- }
+ public int getVncPort() {
+ return vncPort;
+ }
- public static void main(String[] args) {
- long i = 10;
- Long l = null;
- if (i == l) {
- System.out.print("fdfd");
- }
- }
+ public static void main(String[] args) {
+ long i = 10;
+ Long l = null;
+ if (i == l) {
+ System.out.print("fdfd");
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/mockvm/MockVmMgr.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/mockvm/MockVmMgr.java b/agent/src/com/cloud/agent/mockvm/MockVmMgr.java
index 68713ab..c89a135 100644
--- a/agent/src/com/cloud/agent/mockvm/MockVmMgr.java
+++ b/agent/src/com/cloud/agent/mockvm/MockVmMgr.java
@@ -29,295 +29,295 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine.State;
public class MockVmMgr implements VmMgr {
- private static final Logger s_logger = Logger.getLogger(MockVmMgr.class);
-
- private static final int DEFAULT_DOM0_MEM_MB = 128;
- private static final Random randSeed = new Random();
-
- private final Map<String, MockVm> vms = new HashMap<String, MockVm>();
- private long vncPortMap = 0;
-
- private Map<String, Object> _params = null;
-
- public MockVmMgr() {
- }
-
- @Override
- public Set<String> getCurrentVMs() {
- HashSet<String> vmNameSet = new HashSet<String>();
- synchronized (this) {
- for (String vmName : vms.keySet())
- vmNameSet.add(vmName);
- }
- return vmNameSet;
- }
-
- @Override
- public String startVM(String vmName, String vnetId, String gateway,
- String dns, String privateIP, String privateMac,
- String privateMask, String publicIP, String publicMac,
- String publicMask, int cpuCount, int cpuUtilization, long ramSize,
- String localPath, String vncPassword) {
-
- if (s_logger.isInfoEnabled()) {
- StringBuffer sb = new StringBuffer();
- sb.append("Start VM. name: " + vmName + ", vnet: " + vnetId
- + ", dns: " + dns);
- sb.append(", privateIP: " + privateIP + ", privateMac: "
- + privateMac + ", privateMask: " + privateMask);
- sb.append(", publicIP: " + publicIP + ", publicMac: " + publicMac
- + ", publicMask: " + publicMask);
- sb.append(", cpu count: " + cpuCount + ", cpuUtilization: "
- + cpuUtilization + ", ram : " + ramSize);
- sb.append(", localPath: " + localPath);
- s_logger.info(sb.toString());
- }
-
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm == null) {
- if (ramSize > getHostFreeMemory())
- return "Out of memory";
-
- int vncPort = allocVncPort();
- if (vncPort < 0)
- return "Unable to allocate VNC port";
-
- vm = new MockVm(vmName, State.Running, ramSize, cpuCount,
- cpuUtilization, vncPort);
- vms.put(vmName, vm);
- }
- }
-
- return null;
- }
-
- @Override
- public String stopVM(String vmName, boolean force) {
- if (s_logger.isInfoEnabled())
- s_logger.info("Stop VM. name: " + vmName);
-
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm != null) {
- vm.setState(State.Stopped);
- freeVncPort(vm.getVncPort());
- }
- }
-
- return null;
- }
-
- @Override
- public String rebootVM(String vmName) {
- if (s_logger.isInfoEnabled())
- s_logger.info("Reboot VM. name: " + vmName);
-
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm != null)
- vm.setState(State.Running);
- }
- return null;
- }
-
- @Override
- public boolean migrate(String vmName, String params) {
- if (s_logger.isInfoEnabled())
- s_logger.info("Migrate VM. name: " + vmName);
-
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm != null) {
- vm.setState(State.Stopped);
- freeVncPort(vm.getVncPort());
-
- vms.remove(vmName);
- return true;
- }
- }
-
- return false;
- }
-
- public MockVm getVm(String vmName) {
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- return vm;
- }
- }
-
- @Override
- public State checkVmState(String vmName) {
-
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm != null)
- return vm.getState();
- }
- return State.Unknown;
- }
-
- @Override
- public Map<String, State> getVmStates() {
- Map<String, State> states = new HashMap<String, State>();
-
- synchronized (this) {
- for (MockVm vm : vms.values()) {
- states.put(vm.getName(), vm.getState());
- }
- }
- return states;
- }
-
- @Override
- public void cleanupVM(String vmName, String local, String vnet) {
- synchronized (this) {
- MockVm vm = vms.get(vmName);
- if (vm != null) {
- freeVncPort(vm.getVncPort());
- }
- vms.remove(vmName);
- }
- }
-
- @Override
- public double getHostCpuUtilization() {
- return 0.0d;
- }
-
- @Override
- public int getHostCpuCount() {
-
- return getConfiguredProperty("cpus", 4);
- }
-
- @Override
- public long getHostCpuSpeed() {
- return getConfiguredProperty("cpuspeed", 4000L);
-
- }
-
- @Override
- public long getHostTotalMemory() { // total memory in bytes
- return getConfiguredProperty("memory", 16000L);
-
- }
-
- @Override
- public long getHostFreeMemory() { // free memory in bytes
- long memSize = getHostTotalMemory();
- memSize -= getHostDom0Memory();
-
- synchronized (this) {
- for (MockVm vm : vms.values()) {
- if (vm.getState() != State.Stopped)
- memSize -= vm.getRamSize();
- }
- }
-
- return memSize;
- }
-
- @Override
- public long getHostDom0Memory() { // memory size in bytes
- return DEFAULT_DOM0_MEM_MB * 1024 * 1024L;
- }
-
- @Override
- public String cleanupVnet(String vnetId) {
- return null;
- }
-
- @Override
- public Integer getVncPort(String name) {
- synchronized (this) {
- MockVm vm = vms.get(name);
- if (vm != null)
- return vm.getVncPort();
- }
-
- return new Integer(-1);
- }
-
- public int allocVncPort() {
- for (int i = 0; i < 64; i++) {
- if (((1L << i) & vncPortMap) == 0) {
- vncPortMap |= (1L << i);
- return i;
- }
- }
- return -1;
- }
-
- public void freeVncPort(int port) {
- vncPortMap &= ~(1L << port);
- }
-
- @Override
- public MockVm createVmFromSpec(VirtualMachineTO vmSpec) {
- String vmName = vmSpec.getName();
- long ramSize = vmSpec.getMinRam();
- int utilizationPercent = randSeed.nextInt() % 100;
- MockVm vm = null;
-
- synchronized (this) {
- vm = vms.get(vmName);
- if (vm == null) {
- if (ramSize > getHostFreeMemory()) {
- s_logger.debug("host is out of memory");
- throw new CloudRuntimeException("Host is out of Memory");
- }
-
- int vncPort = allocVncPort();
- if (vncPort < 0) {
- s_logger.debug("Unable to allocate VNC port");
- throw new CloudRuntimeException(
- "Unable to allocate vnc port");
- }
-
- vm = new MockVm(vmName, State.Running, ramSize,
- vmSpec.getCpus(), utilizationPercent, vncPort);
- vms.put(vmName, vm);
- }
- }
- return vm;
- }
-
- @Override
- public void createVbd(VirtualMachineTO vmSpec, String vmName, MockVm vm) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void createVif(VirtualMachineTO vmSpec, String vmName, MockVm vm) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void configure(Map<String, Object> params) {
- _params = params;
- }
-
- protected Long getConfiguredProperty(String key, Long defaultValue) {
- String val = (String) _params.get(key);
-
- if (val != null) {
- Long result = Long.parseLong(val);
- return result;
- }
- return defaultValue;
- }
-
- protected Integer getConfiguredProperty(String key, Integer defaultValue) {
- String val = (String) _params.get(key);
-
- if (val != null) {
- Integer result = Integer.parseInt(val);
- return result;
- }
- return defaultValue;
- }
+ private static final Logger s_logger = Logger.getLogger(MockVmMgr.class);
+
+ private static final int DEFAULT_DOM0_MEM_MB = 128;
+ private static final Random randSeed = new Random();
+
+ private final Map<String, MockVm> vms = new HashMap<String, MockVm>();
+ private long vncPortMap = 0;
+
+ private Map<String, Object> _params = null;
+
+ public MockVmMgr() {
+ }
+
+ @Override
+ public Set<String> getCurrentVMs() {
+ HashSet<String> vmNameSet = new HashSet<String>();
+ synchronized (this) {
+ for (String vmName : vms.keySet())
+ vmNameSet.add(vmName);
+ }
+ return vmNameSet;
+ }
+
+ @Override
+ public String startVM(String vmName, String vnetId, String gateway,
+ String dns, String privateIP, String privateMac,
+ String privateMask, String publicIP, String publicMac,
+ String publicMask, int cpuCount, int cpuUtilization, long ramSize,
+ String localPath, String vncPassword) {
+
+ if (s_logger.isInfoEnabled()) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("Start VM. name: " + vmName + ", vnet: " + vnetId
+ + ", dns: " + dns);
+ sb.append(", privateIP: " + privateIP + ", privateMac: "
+ + privateMac + ", privateMask: " + privateMask);
+ sb.append(", publicIP: " + publicIP + ", publicMac: " + publicMac
+ + ", publicMask: " + publicMask);
+ sb.append(", cpu count: " + cpuCount + ", cpuUtilization: "
+ + cpuUtilization + ", ram : " + ramSize);
+ sb.append(", localPath: " + localPath);
+ s_logger.info(sb.toString());
+ }
+
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm == null) {
+ if (ramSize > getHostFreeMemory())
+ return "Out of memory";
+
+ int vncPort = allocVncPort();
+ if (vncPort < 0)
+ return "Unable to allocate VNC port";
+
+ vm = new MockVm(vmName, State.Running, ramSize, cpuCount,
+ cpuUtilization, vncPort);
+ vms.put(vmName, vm);
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public String stopVM(String vmName, boolean force) {
+ if (s_logger.isInfoEnabled())
+ s_logger.info("Stop VM. name: " + vmName);
+
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm != null) {
+ vm.setState(State.Stopped);
+ freeVncPort(vm.getVncPort());
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public String rebootVM(String vmName) {
+ if (s_logger.isInfoEnabled())
+ s_logger.info("Reboot VM. name: " + vmName);
+
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm != null)
+ vm.setState(State.Running);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean migrate(String vmName, String params) {
+ if (s_logger.isInfoEnabled())
+ s_logger.info("Migrate VM. name: " + vmName);
+
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm != null) {
+ vm.setState(State.Stopped);
+ freeVncPort(vm.getVncPort());
+
+ vms.remove(vmName);
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public MockVm getVm(String vmName) {
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ return vm;
+ }
+ }
+
+ @Override
+ public State checkVmState(String vmName) {
+
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm != null)
+ return vm.getState();
+ }
+ return State.Unknown;
+ }
+
+ @Override
+ public Map<String, State> getVmStates() {
+ Map<String, State> states = new HashMap<String, State>();
+
+ synchronized (this) {
+ for (MockVm vm : vms.values()) {
+ states.put(vm.getName(), vm.getState());
+ }
+ }
+ return states;
+ }
+
+ @Override
+ public void cleanupVM(String vmName, String local, String vnet) {
+ synchronized (this) {
+ MockVm vm = vms.get(vmName);
+ if (vm != null) {
+ freeVncPort(vm.getVncPort());
+ }
+ vms.remove(vmName);
+ }
+ }
+
+ @Override
+ public double getHostCpuUtilization() {
+ return 0.0d;
+ }
+
+ @Override
+ public int getHostCpuCount() {
+
+ return getConfiguredProperty("cpus", 4);
+ }
+
+ @Override
+ public long getHostCpuSpeed() {
+ return getConfiguredProperty("cpuspeed", 4000L);
+
+ }
+
+ @Override
+ public long getHostTotalMemory() { // total memory in bytes
+ return getConfiguredProperty("memory", 16000L);
+
+ }
+
+ @Override
+ public long getHostFreeMemory() { // free memory in bytes
+ long memSize = getHostTotalMemory();
+ memSize -= getHostDom0Memory();
+
+ synchronized (this) {
+ for (MockVm vm : vms.values()) {
+ if (vm.getState() != State.Stopped)
+ memSize -= vm.getRamSize();
+ }
+ }
+
+ return memSize;
+ }
+
+ @Override
+ public long getHostDom0Memory() { // memory size in bytes
+ return DEFAULT_DOM0_MEM_MB * 1024 * 1024L;
+ }
+
+ @Override
+ public String cleanupVnet(String vnetId) {
+ return null;
+ }
+
+ @Override
+ public Integer getVncPort(String name) {
+ synchronized (this) {
+ MockVm vm = vms.get(name);
+ if (vm != null)
+ return vm.getVncPort();
+ }
+
+ return new Integer(-1);
+ }
+
+ public int allocVncPort() {
+ for (int i = 0; i < 64; i++) {
+ if (((1L << i) & vncPortMap) == 0) {
+ vncPortMap |= (1L << i);
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ public void freeVncPort(int port) {
+ vncPortMap &= ~(1L << port);
+ }
+
+ @Override
+ public MockVm createVmFromSpec(VirtualMachineTO vmSpec) {
+ String vmName = vmSpec.getName();
+ long ramSize = vmSpec.getMinRam();
+ int utilizationPercent = randSeed.nextInt() % 100;
+ MockVm vm = null;
+
+ synchronized (this) {
+ vm = vms.get(vmName);
+ if (vm == null) {
+ if (ramSize > getHostFreeMemory()) {
+ s_logger.debug("host is out of memory");
+ throw new CloudRuntimeException("Host is out of Memory");
+ }
+
+ int vncPort = allocVncPort();
+ if (vncPort < 0) {
+ s_logger.debug("Unable to allocate VNC port");
+ throw new CloudRuntimeException(
+ "Unable to allocate vnc port");
+ }
+
+ vm = new MockVm(vmName, State.Running, ramSize,
+ vmSpec.getCpus(), utilizationPercent, vncPort);
+ vms.put(vmName, vm);
+ }
+ }
+ return vm;
+ }
+
+ @Override
+ public void createVbd(VirtualMachineTO vmSpec, String vmName, MockVm vm) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void createVif(VirtualMachineTO vmSpec, String vmName, MockVm vm) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void configure(Map<String, Object> params) {
+ _params = params;
+ }
+
+ protected Long getConfiguredProperty(String key, Long defaultValue) {
+ String val = (String) _params.get(key);
+
+ if (val != null) {
+ Long result = Long.parseLong(val);
+ return result;
+ }
+ return defaultValue;
+ }
+
+ protected Integer getConfiguredProperty(String key, Integer defaultValue) {
+ String val = (String) _params.get(key);
+
+ if (val != null) {
+ Integer result = Integer.parseInt(val);
+ return result;
+ }
+ return defaultValue;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/5e9a193f/agent/src/com/cloud/agent/mockvm/VmMgr.java
----------------------------------------------------------------------
diff --git a/agent/src/com/cloud/agent/mockvm/VmMgr.java b/agent/src/com/cloud/agent/mockvm/VmMgr.java
index 55e5990..1a7050c 100644
--- a/agent/src/com/cloud/agent/mockvm/VmMgr.java
+++ b/agent/src/com/cloud/agent/mockvm/VmMgr.java
@@ -23,49 +23,49 @@ import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.vm.VirtualMachine.State;
public interface VmMgr {
- public Set<String> getCurrentVMs();
+ public Set<String> getCurrentVMs();
- public String startVM(String vmName, String vnetId, String gateway,
- String dns, String privateIP, String privateMac,
- String privateMask, String publicIP, String publicMac,
- String publicMask, int cpuCount, int cpuUtilization, long ramSize,
- String localPath, String vncPassword);
+ public String startVM(String vmName, String vnetId, String gateway,
+ String dns, String privateIP, String privateMac,
+ String privateMask, String publicIP, String publicMac,
+ String publicMask, int cpuCount, int cpuUtilization, long ramSize,
+ String localPath, String vncPassword);
- public String stopVM(String vmName, boolean force);
+ public String stopVM(String vmName, boolean force);
- public String rebootVM(String vmName);
+ public String rebootVM(String vmName);
- public void cleanupVM(String vmName, String local, String vnet);
+ public void cleanupVM(String vmName, String local, String vnet);
- public boolean migrate(String vmName, String params);
+ public boolean migrate(String vmName, String params);
- public MockVm getVm(String vmName);
+ public MockVm getVm(String vmName);
- public State checkVmState(String vmName);
+ public State checkVmState(String vmName);
- public Map<String, State> getVmStates();
+ public Map<String, State> getVmStates();
- public Integer getVncPort(String name);
+ public Integer getVncPort(String name);
- public String cleanupVnet(String vnetId);
+ public String cleanupVnet(String vnetId);
- public double getHostCpuUtilization();
+ public double getHostCpuUtilization();
- public int getHostCpuCount();
+ public int getHostCpuCount();
- public long getHostCpuSpeed();
+ public long getHostCpuSpeed();
- public long getHostTotalMemory();
+ public long getHostTotalMemory();
- public long getHostFreeMemory();
+ public long getHostFreeMemory();
- public long getHostDom0Memory();
+ public long getHostDom0Memory();
- public MockVm createVmFromSpec(VirtualMachineTO vmSpec);
+ public MockVm createVmFromSpec(VirtualMachineTO vmSpec);
- public void createVbd(VirtualMachineTO vmSpec, String vmName, MockVm vm);
+ public void createVbd(VirtualMachineTO vmSpec, String vmName, MockVm vm);
- public void createVif(VirtualMachineTO vmSpec, String vmName, MockVm vm);
+ public void createVif(VirtualMachineTO vmSpec, String vmName, MockVm vm);
- public void configure(Map<String, Object> params);
+ public void configure(Map<String, Object> params);
}