From 5e9a193f2c66dd4901f182cc1f9cf01be7b1a79c Mon Sep 17 00:00:00 2001 From: Wido den Hollander Date: Sat, 23 Jun 2012 11:16:16 +0200 Subject: [PATCH] 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. --- agent/src/com/cloud/agent/Agent.java | 30 +- agent/src/com/cloud/agent/AgentShell.java | 1152 +-- agent/src/com/cloud/agent/IAgentShell.java | 32 +- .../AgentComponentLibraryBase.java | 72 +- .../com/cloud/agent/dao/StorageComponent.java | 4 +- .../agent/dao/impl/PropertiesStorage.java | 156 +- .../agent/dhcp/DhcpProtocolParserServer.java | 58 +- .../src/com/cloud/agent/dhcp/DhcpSnooper.java | 12 +- .../com/cloud/agent/dhcp/FakeDhcpSnooper.java | 176 +- agent/src/com/cloud/agent/mockvm/MockVm.java | 92 +- .../src/com/cloud/agent/mockvm/MockVmMgr.java | 472 +- agent/src/com/cloud/agent/mockvm/VmMgr.java | 50 +- .../cloud/agent/resource/DummyResource.java | 294 +- .../computing/FakeComputingResource.java | 1064 +-- .../resource/computing/KVMGuestOsMapper.java | 284 +- .../agent/resource/computing/KVMHABase.java | 314 +- .../resource/computing/KVMHAChecker.java | 98 +- .../resource/computing/KVMHAMonitor.java | 156 +- .../computing/LibvirtCapXMLParser.java | 302 +- .../computing/LibvirtComputingResource.java | 7710 ++++++++--------- .../resource/computing/LibvirtConnection.java | 42 +- .../computing/LibvirtDomainXMLParser.java | 360 +- .../resource/computing/LibvirtNetworkDef.java | 308 +- .../computing/LibvirtStoragePoolDef.java | 120 +- .../LibvirtStoragePoolXMLParser.java | 128 +- .../computing/LibvirtStorageVolumeDef.java | 126 +- .../LibvirtStorageVolumeXMLParser.java | 120 +- .../resource/computing/LibvirtVMDef.java | 1748 ++-- .../resource/computing/LibvirtXMLParser.java | 66 +- .../ConsoleProxyAuthenticationResult.java | 96 +- .../consoleproxy/ConsoleProxyResource.java | 738 +- .../cloud/agent/storage/KVMPhysicalDisk.java | 96 +- .../cloud/agent/storage/KVMStoragePool.java | 32 +- .../agent/storage/KVMStoragePoolManager.java | 126 +- .../agent/storage/LibvirtStorageAdaptor.java | 1304 +-- .../agent/storage/LibvirtStoragePool.java | 212 +- .../cloud/agent/storage/StorageAdaptor.java | 52 +- .../cloud/agent/vmdata/JettyVmDataServer.java | 530 +- .../com/cloud/agent/vmdata/VmDataServer.java | 6 +- .../test/com/cloud/agent/TestAgentShell.java | 12 +- 40 files changed, 9375 insertions(+), 9375 deletions(-) diff --git a/agent/src/com/cloud/agent/Agent.java b/agent/src/com/cloud/agent/Agent.java index 9f97213aef4..babf0b396d4 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 "); diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 49073e19e70..941f09498b4 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 _cmdLineProperties = new HashMap(); - 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 _agents = new ArrayList(); - - 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 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()); - } - - // merge with properties from command line to let resource access - // command line parameters - for (Map.Entry 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()); - } - } - - 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 _cmdLineProperties = new HashMap(); + 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 _agents = new ArrayList(); + + 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 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()); + } + + // merge with properties from command line to let resource access + // command line parameters + for (Map.Entry 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()); + } + } + + 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(); + } + } } diff --git a/agent/src/com/cloud/agent/IAgentShell.java b/agent/src/com/cloud/agent/IAgentShell.java index bd0b976354d..93aaa00c733 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 getCmdLineProperties(); + public Map 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(); } diff --git a/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java b/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java index b05883446b2..058aefa9252 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>> getDaos() { - return null; - } + @Override + public Map>> getDaos() { + return null; + } - @Override - public Map> getManagers() { - if (_managers.size() == 0) { - populateManagers(); - } - return _managers; - } + @Override + public Map> getManagers() { + if (_managers.size() == 0) { + populateManagers(); + } + return _managers; + } - @Override - public Map>> getAdapters() { - if (_adapters.size() == 0) { - populateAdapters(); - } - return _adapters; - } + @Override + public Map>> getAdapters() { + if (_adapters.size() == 0) { + populateAdapters(); + } + return _adapters; + } - @Override - public Map, Class> getFactories() { - return null; - } + @Override + public Map, 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> getPluggableServices() { - if (_pluggableServices.size() == 0) { - populateServices(); - } - return _pluggableServices; - } + @Override + public Map> getPluggableServices() { + if (_pluggableServices.size() == 0) { + populateServices(); + } + return _pluggableServices; + } } diff --git a/agent/src/com/cloud/agent/dao/StorageComponent.java b/agent/src/com/cloud/agent/dao/StorageComponent.java index 576982f7078..afb9467ee50 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); } diff --git a/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java b/agent/src/com/cloud/agent/dao/impl/PropertiesStorage.java index e3598a90f90..b94ae83fdc2 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 params) { - _name = name; - String path = (String) params.get("path"); - if (path == null) { - path = "agent.properties"; - } + @Override + public boolean configure(String name, Map 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; + } } diff --git a/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java b/agent/src/com/cloud/agent/dhcp/DhcpProtocolParserServer.java index 53856b665a3..94aa2748cfe 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(), - new NamedThreadFactory("DhcpListener")); - _running = true; - } + public DhcpProtocolParserServer(int workers) { + _executor = new ThreadPoolExecutor(workers, 10 * workers, 1, + TimeUnit.DAYS, new LinkedBlockingQueue(), + 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()); + } + } + } } diff --git a/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java b/agent/src/com/cloud/agent/dhcp/DhcpSnooper.java index 36b9c24f493..e25e2cf1f4d 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 syncIpAddr(); + public Map syncIpAddr(); - public boolean stop(); + public boolean stop(); - public void initializeMacTable(List> macVmNameList); + public void initializeMacTable(List> macVmNameList); } diff --git a/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java b/agent/src/com/cloud/agent/dhcp/FakeDhcpSnooper.java index 27c08f3e77a..11ea824902b 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 _ipAddresses = new ConcurrentLinkedQueue(); - private Map _macIpMap = new ConcurrentHashMap(); - private Map _vmIpMap = new ConcurrentHashMap(); + private static final Logger s_logger = Logger + .getLogger(FakeDhcpSnooper.class); + private Queue _ipAddresses = new ConcurrentLinkedQueue(); + private Map _macIpMap = new ConcurrentHashMap(); + private Map _vmIpMap = new ConcurrentHashMap(); - @Override - public boolean configure(String name, Map 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 configure(String name, Map 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 boolean start() { + return true; + } - @Override - public String getName() { - return "FakeDhcpSnooper"; - } + @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 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 entry : _macIpMap.entrySet()) { - if (entry.getValue().equalsIgnoreCase(ipAddr)) { - macAddr = entry.getKey(); - break; - } - } - ipAddr = _macIpMap.remove(macAddr); + @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 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()); - } - } + 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 syncIpAddr() { - return _vmIpMap; - } + @Override + public Map syncIpAddr() { + return _vmIpMap; + } - @Override - public boolean stop() { - return false; - } + @Override + public boolean stop() { + return false; + } - @Override - public void initializeMacTable(List> macVmNameList) { + @Override + public void initializeMacTable(List> macVmNameList) { - } + } - @Override - public InetAddress getDhcpServerIP() { - // TODO Auto-generated method stub - return null; - } + @Override + public InetAddress getDhcpServerIP() { + // TODO Auto-generated method stub + return null; + } } diff --git a/agent/src/com/cloud/agent/mockvm/MockVm.java b/agent/src/com/cloud/agent/mockvm/MockVm.java index 1589a8f60e2..306a6c40786 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"); + } + } } diff --git a/agent/src/com/cloud/agent/mockvm/MockVmMgr.java b/agent/src/com/cloud/agent/mockvm/MockVmMgr.java index 68713ab3e6c..c89a1352aa2 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 Logger s_logger = Logger.getLogger(MockVmMgr.class); - private static final int DEFAULT_DOM0_MEM_MB = 128; - private static final Random randSeed = new Random(); + private static final int DEFAULT_DOM0_MEM_MB = 128; + private static final Random randSeed = new Random(); - private final Map vms = new HashMap(); - private long vncPortMap = 0; + private final Map vms = new HashMap(); + private long vncPortMap = 0; - private Map _params = null; + private Map _params = null; - public MockVmMgr() { - } + public MockVmMgr() { + } - @Override - public Set getCurrentVMs() { - HashSet vmNameSet = new HashSet(); - synchronized (this) { - for (String vmName : vms.keySet()) - vmNameSet.add(vmName); - } - return vmNameSet; - } + @Override + public Set getCurrentVMs() { + HashSet vmNameSet = new HashSet(); + 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) { + @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()); - } + 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"; + 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"; + 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); - } - } + vm = new MockVm(vmName, State.Running, ramSize, cpuCount, + cpuUtilization, vncPort); + vms.put(vmName, vm); + } + } - return null; - } + return null; + } - @Override - public String stopVM(String vmName, boolean force) { - if (s_logger.isInfoEnabled()) - s_logger.info("Stop VM. name: " + vmName); + @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()); - } - } + synchronized (this) { + MockVm vm = vms.get(vmName); + if (vm != null) { + vm.setState(State.Stopped); + freeVncPort(vm.getVncPort()); + } + } - return null; - } + return null; + } - @Override - public String rebootVM(String vmName) { - if (s_logger.isInfoEnabled()) - s_logger.info("Reboot VM. name: " + vmName); + @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; - } + 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); + @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()); + synchronized (this) { + MockVm vm = vms.get(vmName); + if (vm != null) { + vm.setState(State.Stopped); + freeVncPort(vm.getVncPort()); - vms.remove(vmName); - return true; - } - } + vms.remove(vmName); + return true; + } + } - return false; - } + return false; + } - public MockVm getVm(String vmName) { - synchronized (this) { - MockVm vm = vms.get(vmName); - return vm; - } - } + public MockVm getVm(String vmName) { + synchronized (this) { + MockVm vm = vms.get(vmName); + return vm; + } + } - @Override - public State checkVmState(String vmName) { + @Override + public State checkVmState(String vmName) { - synchronized (this) { - MockVm vm = vms.get(vmName); - if (vm != null) - return vm.getState(); - } - return State.Unknown; - } + synchronized (this) { + MockVm vm = vms.get(vmName); + if (vm != null) + return vm.getState(); + } + return State.Unknown; + } - @Override - public Map getVmStates() { - Map states = new HashMap(); + @Override + public Map getVmStates() { + Map states = new HashMap(); - synchronized (this) { - for (MockVm vm : vms.values()) { - states.put(vm.getName(), vm.getState()); - } - } - return states; - } + 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 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 double getHostCpuUtilization() { + return 0.0d; + } - @Override - public int getHostCpuCount() { + @Override + public int getHostCpuCount() { - return getConfiguredProperty("cpus", 4); - } + return getConfiguredProperty("cpus", 4); + } - @Override - public long getHostCpuSpeed() { - return getConfiguredProperty("cpuspeed", 4000L); + @Override + public long getHostCpuSpeed() { + return getConfiguredProperty("cpuspeed", 4000L); - } + } - @Override - public long getHostTotalMemory() { // total memory in bytes - return getConfiguredProperty("memory", 16000L); + @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(); + @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(); - } - } + synchronized (this) { + for (MockVm vm : vms.values()) { + if (vm.getState() != State.Stopped) + memSize -= vm.getRamSize(); + } + } - return memSize; - } + return memSize; + } - @Override - public long getHostDom0Memory() { // memory size in bytes - return DEFAULT_DOM0_MEM_MB * 1024 * 1024L; - } + @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 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(); - } + @Override + public Integer getVncPort(String name) { + synchronized (this) { + MockVm vm = vms.get(name); + if (vm != null) + return vm.getVncPort(); + } - return new Integer(-1); - } + 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 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); - } + 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; + @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"); - } + 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"); - } + 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; - } + 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 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 createVif(VirtualMachineTO vmSpec, String vmName, MockVm vm) { + // TODO Auto-generated method stub - } + } - @Override - public void configure(Map params) { - _params = params; - } + @Override + public void configure(Map params) { + _params = params; + } - protected Long getConfiguredProperty(String key, Long defaultValue) { - String val = (String) _params.get(key); + 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; - } + 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); + 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; - } + if (val != null) { + Integer result = Integer.parseInt(val); + return result; + } + return defaultValue; + } } diff --git a/agent/src/com/cloud/agent/mockvm/VmMgr.java b/agent/src/com/cloud/agent/mockvm/VmMgr.java index 55e59909259..1a7050c2376 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 getCurrentVMs(); + public Set 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 getVmStates(); + public Map 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 params); + public void configure(Map params); } diff --git a/agent/src/com/cloud/agent/resource/DummyResource.java b/agent/src/com/cloud/agent/resource/DummyResource.java index 26256d2db3b..573f639b06d 100755 --- a/agent/src/com/cloud/agent/resource/DummyResource.java +++ b/agent/src/com/cloud/agent/resource/DummyResource.java @@ -45,183 +45,183 @@ import com.cloud.storage.Storage.StoragePoolType; @Local(value = { ServerResource.class }) public class DummyResource implements ServerResource { - String _name; - Host.Type _type; - boolean _negative; - IAgentControl _agentControl; - private Map _params; + String _name; + Host.Type _type; + boolean _negative; + IAgentControl _agentControl; + private Map _params; - @Override - public void disconnected() { - } + @Override + public void disconnected() { + } - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof CheckNetworkCommand) { - return new CheckNetworkAnswer((CheckNetworkCommand) cmd, true, null); - } - System.out.println("Received Command: " + cmd.toString()); - Answer answer = new Answer(cmd, !_negative, "response"); - System.out.println("Replying with: " + answer.toString()); - return answer; - } + @Override + public Answer executeRequest(Command cmd) { + if (cmd instanceof CheckNetworkCommand) { + return new CheckNetworkAnswer((CheckNetworkCommand) cmd, true, null); + } + System.out.println("Received Command: " + cmd.toString()); + Answer answer = new Answer(cmd, !_negative, "response"); + System.out.println("Replying with: " + answer.toString()); + return answer; + } - @Override - public PingCommand getCurrentStatus(long id) { - return new PingCommand(_type, id); - } + @Override + public PingCommand getCurrentStatus(long id) { + return new PingCommand(_type, id); + } - @Override - public Type getType() { - return _type; - } + @Override + public Type getType() { + return _type; + } - protected String getConfiguredProperty(String key, String defaultValue) { - String val = (String) _params.get(key); - return val == null ? defaultValue : val; - } + protected String getConfiguredProperty(String key, String defaultValue) { + String val = (String) _params.get(key); + return val == null ? defaultValue : val; + } - protected Long getConfiguredProperty(String key, Long defaultValue) { - String val = (String) _params.get(key); + 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; - } + if (val != null) { + Long result = Long.parseLong(val); + return result; + } + return defaultValue; + } - protected List getHostInfo() { - final ArrayList info = new ArrayList(); - long speed = getConfiguredProperty("cpuspeed", 4000L); - long cpus = getConfiguredProperty("cpus", 4L); - long ram = getConfiguredProperty("memory", 16000L * 1024L * 1024L); - long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L); + protected List getHostInfo() { + final ArrayList info = new ArrayList(); + long speed = getConfiguredProperty("cpuspeed", 4000L); + long cpus = getConfiguredProperty("cpus", 4L); + long ram = getConfiguredProperty("memory", 16000L * 1024L * 1024L); + long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L); - String cap = getConfiguredProperty("capabilities", "hvm"); - info.add((int) cpus); - info.add(speed); - info.add(ram); - info.add(cap); - info.add(dom0ram); - return info; + String cap = getConfiguredProperty("capabilities", "hvm"); + info.add((int) cpus); + info.add(speed); + info.add(ram); + info.add(cap); + info.add(dom0ram); + return info; - } + } - protected void fillNetworkInformation(final StartupCommand cmd) { + protected void fillNetworkInformation(final StartupCommand cmd) { - cmd.setPrivateIpAddress((String) getConfiguredProperty( - "private.ip.address", "127.0.0.1")); - cmd.setPrivateMacAddress((String) getConfiguredProperty( - "private.mac.address", "8A:D2:54:3F:7C:C3")); - cmd.setPrivateNetmask((String) getConfiguredProperty( - "private.ip.netmask", "255.255.255.0")); + cmd.setPrivateIpAddress((String) getConfiguredProperty( + "private.ip.address", "127.0.0.1")); + cmd.setPrivateMacAddress((String) getConfiguredProperty( + "private.mac.address", "8A:D2:54:3F:7C:C3")); + cmd.setPrivateNetmask((String) getConfiguredProperty( + "private.ip.netmask", "255.255.255.0")); - cmd.setStorageIpAddress((String) getConfiguredProperty( - "private.ip.address", "127.0.0.1")); - cmd.setStorageMacAddress((String) getConfiguredProperty( - "private.mac.address", "8A:D2:54:3F:7C:C3")); - cmd.setStorageNetmask((String) getConfiguredProperty( - "private.ip.netmask", "255.255.255.0")); - cmd.setGatewayIpAddress((String) getConfiguredProperty( - "gateway.ip.address", "127.0.0.1")); + cmd.setStorageIpAddress((String) getConfiguredProperty( + "private.ip.address", "127.0.0.1")); + cmd.setStorageMacAddress((String) getConfiguredProperty( + "private.mac.address", "8A:D2:54:3F:7C:C3")); + cmd.setStorageNetmask((String) getConfiguredProperty( + "private.ip.netmask", "255.255.255.0")); + cmd.setGatewayIpAddress((String) getConfiguredProperty( + "gateway.ip.address", "127.0.0.1")); - } + } - private Map getVersionStrings() { - Map result = new HashMap(); - String hostOs = (String) _params.get("Host.OS"); - String hostOsVer = (String) _params.get("Host.OS.Version"); - String hostOsKernVer = (String) _params.get("Host.OS.Kernel.Version"); - result.put("Host.OS", hostOs == null ? "Fedora" : hostOs); - result.put("Host.OS.Version", hostOsVer == null ? "14" : hostOsVer); - result.put("Host.OS.Kernel.Version", - hostOsKernVer == null ? "2.6.35.6-45.fc14.x86_64" - : hostOsKernVer); - return result; - } + private Map getVersionStrings() { + Map result = new HashMap(); + String hostOs = (String) _params.get("Host.OS"); + String hostOsVer = (String) _params.get("Host.OS.Version"); + String hostOsKernVer = (String) _params.get("Host.OS.Kernel.Version"); + result.put("Host.OS", hostOs == null ? "Fedora" : hostOs); + result.put("Host.OS.Version", hostOsVer == null ? "14" : hostOsVer); + result.put("Host.OS.Kernel.Version", + hostOsKernVer == null ? "2.6.35.6-45.fc14.x86_64" + : hostOsKernVer); + return result; + } - protected StoragePoolInfo initializeLocalStorage() { - String hostIp = (String) getConfiguredProperty("private.ip.address", - "127.0.0.1"); - String localStoragePath = (String) getConfiguredProperty( - "local.storage.path", "/mnt"); - String lh = hostIp + localStoragePath; - String uuid = UUID.nameUUIDFromBytes(lh.getBytes()).toString(); + protected StoragePoolInfo initializeLocalStorage() { + String hostIp = (String) getConfiguredProperty("private.ip.address", + "127.0.0.1"); + String localStoragePath = (String) getConfiguredProperty( + "local.storage.path", "/mnt"); + String lh = hostIp + localStoragePath; + String uuid = UUID.nameUUIDFromBytes(lh.getBytes()).toString(); - String capacity = (String) getConfiguredProperty( - "local.storage.capacity", "1000000000"); - String available = (String) getConfiguredProperty( - "local.storage.avail", "10000000"); + String capacity = (String) getConfiguredProperty( + "local.storage.capacity", "1000000000"); + String available = (String) getConfiguredProperty( + "local.storage.avail", "10000000"); - return new StoragePoolInfo(uuid, hostIp, localStoragePath, - localStoragePath, StoragePoolType.Filesystem, - Long.parseLong(capacity), Long.parseLong(available)); + return new StoragePoolInfo(uuid, hostIp, localStoragePath, + localStoragePath, StoragePoolType.Filesystem, + Long.parseLong(capacity), Long.parseLong(available)); - } + } - @Override - public StartupCommand[] initialize() { - Map changes = null; + @Override + public StartupCommand[] initialize() { + Map changes = null; - final List info = getHostInfo(); + final List info = getHostInfo(); - final StartupRoutingCommand cmd = new StartupRoutingCommand( - (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), - (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, - RouterPrivateIpStrategy.HostLocal, changes); - fillNetworkInformation(cmd); - cmd.getHostDetails().putAll(getVersionStrings()); - cmd.setCluster(getConfiguredProperty("cluster", "1")); - StoragePoolInfo pi = initializeLocalStorage(); - StartupStorageCommand sscmd = new StartupStorageCommand(); - sscmd.setPoolInfo(pi); - sscmd.setGuid(pi.getUuid()); - sscmd.setDataCenter((String) _params.get("zone")); - sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); + final StartupRoutingCommand cmd = new StartupRoutingCommand( + (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), + (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, + RouterPrivateIpStrategy.HostLocal, changes); + fillNetworkInformation(cmd); + cmd.getHostDetails().putAll(getVersionStrings()); + cmd.setCluster(getConfiguredProperty("cluster", "1")); + StoragePoolInfo pi = initializeLocalStorage(); + StartupStorageCommand sscmd = new StartupStorageCommand(); + sscmd.setPoolInfo(pi); + sscmd.setGuid(pi.getUuid()); + sscmd.setDataCenter((String) _params.get("zone")); + sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); - return new StartupCommand[] { cmd, sscmd }; - } + return new StartupCommand[] { cmd, sscmd }; + } - @Override - public boolean configure(String name, Map params) { - _name = name; + @Override + public boolean configure(String name, Map params) { + _name = name; - String value = (String) params.get("type"); - _type = Host.Type.valueOf(value); + String value = (String) params.get("type"); + _type = Host.Type.valueOf(value); - value = (String) params.get("negative.reply"); - _negative = Boolean.parseBoolean(value); - setParams(params); - return true; - } + value = (String) params.get("negative.reply"); + _negative = Boolean.parseBoolean(value); + setParams(params); + return true; + } - public void setParams(Map _params) { - this._params = _params; - } + public void setParams(Map _params) { + this._params = _params; + } - @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; + } - @Override - public IAgentControl getAgentControl() { - return _agentControl; - } + @Override + public IAgentControl getAgentControl() { + return _agentControl; + } - @Override - public void setAgentControl(IAgentControl agentControl) { - _agentControl = agentControl; - } + @Override + public void setAgentControl(IAgentControl agentControl) { + _agentControl = agentControl; + } } diff --git a/agent/src/com/cloud/agent/resource/computing/FakeComputingResource.java b/agent/src/com/cloud/agent/resource/computing/FakeComputingResource.java index b7e9cb08aa3..d9b5d949c44 100644 --- a/agent/src/com/cloud/agent/resource/computing/FakeComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/FakeComputingResource.java @@ -110,536 +110,536 @@ import com.cloud.vm.VirtualMachine.State; */ @Local(value = { ServerResource.class }) public class FakeComputingResource extends ServerResourceBase implements - ServerResource { - private static final Logger s_logger = Logger - .getLogger(FakeComputingResource.class); - private Map _params; - private VmMgr _vmManager = new MockVmMgr(); - protected HashMap _vms = new HashMap(20); - protected DhcpSnooper _dhcpSnooper = new FakeDhcpSnooper(); - protected VmDataServer _vmDataServer = new JettyVmDataServer(); - - @Override - public Type getType() { - return Type.Routing; - } - - @Override - public StartupCommand[] initialize() { - Map changes = null; - - final List info = getHostInfo(); - - final StartupRoutingCommand cmd = new StartupRoutingCommand( - (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), - (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, - RouterPrivateIpStrategy.HostLocal, changes); - fillNetworkInformation(cmd); - cmd.getHostDetails().putAll(getVersionStrings()); - cmd.setCluster(getConfiguredProperty("cluster", "1")); - StoragePoolInfo pi = initializeLocalStorage(); - StartupStorageCommand sscmd = new StartupStorageCommand(); - sscmd.setPoolInfo(pi); - sscmd.setGuid(pi.getUuid()); - sscmd.setDataCenter((String) _params.get("zone")); - sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); - - return new StartupCommand[] { cmd, sscmd }; - - } - - private Map getVersionStrings() { - Map result = new HashMap(); - String hostOs = (String) _params.get("Host.OS"); - String hostOsVer = (String) _params.get("Host.OS.Version"); - String hostOsKernVer = (String) _params.get("Host.OS.Kernel.Version"); - result.put("Host.OS", hostOs == null ? "Fedora" : hostOs); - result.put("Host.OS.Version", hostOsVer == null ? "14" : hostOsVer); - result.put("Host.OS.Kernel.Version", - hostOsKernVer == null ? "2.6.35.6-45.fc14.x86_64" - : hostOsKernVer); - return result; - } - - protected void fillNetworkInformation(final StartupCommand cmd) { - - cmd.setPrivateIpAddress((String) _params.get("private.ip.address")); - cmd.setPrivateMacAddress((String) _params.get("private.mac.address")); - cmd.setPrivateNetmask((String) _params.get("private.ip.netmask")); - - cmd.setStorageIpAddress((String) _params.get("private.ip.address")); - cmd.setStorageMacAddress((String) _params.get("private.mac.address")); - cmd.setStorageNetmask((String) _params.get("private.ip.netmask")); - cmd.setGatewayIpAddress((String) _params.get("gateway.ip.address")); - - } - - protected StoragePoolInfo initializeLocalStorage() { - String hostIp = (String) _params.get("private.ip.address"); - String localStoragePath = (String) _params.get("local.storage.path"); - String lh = hostIp + localStoragePath; - String uuid = UUID.nameUUIDFromBytes(lh.getBytes()).toString(); - - String capacity = (String) _params.get("local.storage.capacity"); - String available = (String) _params.get("local.storage.avail"); - - return new StoragePoolInfo(uuid, hostIp, localStoragePath, - localStoragePath, StoragePoolType.Filesystem, - Long.parseLong(capacity), Long.parseLong(available)); - - } - - @Override - public PingCommand getCurrentStatus(long id) { - final HashMap newStates = new HashMap(); - _dhcpSnooper.syncIpAddr(); - return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, - newStates); - } - - @Override - public Answer executeRequest(Command cmd) { - try { - if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand) cmd); - } else if (cmd instanceof ModifySshKeysCommand) { - return execute((ModifySshKeysCommand) cmd);// TODO: remove - } else if (cmd instanceof GetHostStatsCommand) { - return execute((GetHostStatsCommand) cmd); - } else if (cmd instanceof PrimaryStorageDownloadCommand) { - return execute((PrimaryStorageDownloadCommand) cmd); - - } else if (cmd instanceof StopCommand) { - return execute((StopCommand) cmd); - } else if (cmd instanceof GetVmStatsCommand) { - return execute((GetVmStatsCommand) cmd); - } else if (cmd instanceof RebootCommand) { - return execute((RebootCommand) cmd); - } else if (cmd instanceof CheckStateCommand) { - return executeRequest(cmd); - } else if (cmd instanceof CheckHealthCommand) { - return execute((CheckHealthCommand) cmd); - } else if (cmd instanceof PingTestCommand) { - return execute((PingTestCommand) cmd); - } else if (cmd instanceof CheckVirtualMachineCommand) { - return execute((CheckVirtualMachineCommand) cmd); - } else if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand) cmd); - } else if (cmd instanceof StopCommand) { - return execute((StopCommand) cmd); - } else if (cmd instanceof CreateCommand) { - return execute((CreateCommand) cmd); - } else if (cmd instanceof DestroyCommand) { - return execute((DestroyCommand) cmd); - } else if (cmd instanceof PrimaryStorageDownloadCommand) { - return execute((PrimaryStorageDownloadCommand) cmd); - } else if (cmd instanceof GetStorageStatsCommand) { - return execute((GetStorageStatsCommand) cmd); - } else if (cmd instanceof ModifyStoragePoolCommand) { - return execute((ModifyStoragePoolCommand) cmd); - } else if (cmd instanceof SecurityGroupRulesCmd) { - return execute((SecurityGroupRulesCmd) cmd); - } else if (cmd instanceof StartCommand) { - return execute((StartCommand) cmd); - } else if (cmd instanceof CleanupNetworkRulesCmd) { - return execute((CleanupNetworkRulesCmd) cmd); - } else if (cmd instanceof SavePasswordCommand) { - return execute((SavePasswordCommand) cmd); - } else if (cmd instanceof VmDataCommand) { - return execute((VmDataCommand) cmd); - } else { - s_logger.warn("Unsupported command "); - return Answer.createUnsupportedCommandAnswer(cmd); - } - } catch (final IllegalArgumentException e) { - return new Answer(cmd, false, e.getMessage()); - } - } - - private Answer execute(CleanupNetworkRulesCmd cmd) { - return new Answer(cmd); - } - - private Answer execute(SecurityGroupRulesCmd cmd) { - s_logger.info("Programmed network rules for vm " + cmd.getVmName() - + " guestIp=" + cmd.getGuestIp() + ",ingress numrules=" - + cmd.getIngressRuleSet().length + ",egress numrules=" - + cmd.getEgressRuleSet().length); - return new SecurityGroupRuleAnswer(cmd); - } - - private Answer execute(ModifyStoragePoolCommand cmd) { - long capacity = getConfiguredProperty("local.storage.capacity", - 10000000000L); - long used = 10000000L; - long available = capacity - used; - if (cmd.getAdd()) { - - ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, - capacity, used, new HashMap()); - - if (s_logger.isInfoEnabled()) - s_logger.info("Sending ModifyStoragePoolCommand answer with capacity: " - + capacity - + ", used: " - + used - + ", available: " - + available); - return answer; - } else { - if (s_logger.isInfoEnabled()) - s_logger.info("ModifyNetfsStoragePoolCmd is not add command, cmd: " - + cmd.toString()); - return new Answer(cmd); - } - } - - private Answer execute(GetStorageStatsCommand cmd) { - return new GetStorageStatsAnswer(cmd, getConfiguredProperty( - "local.storage.capacity", 100000000000L), 0L); - } - - protected synchronized ReadyAnswer execute(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer execute(PrimaryStorageDownloadCommand cmd) { - return new PrimaryStorageDownloadAnswer(cmd.getLocalPath(), 16000000L); - } - - private Answer execute(ModifySshKeysCommand cmd) { - return new Answer(cmd, true, null); - } - - @Override - protected String getDefaultScriptsDir() { - return null; - } - - protected String getConfiguredProperty(String key, String defaultValue) { - String val = (String) _params.get(key); - return val == null ? defaultValue : val; - } - - 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 List getHostInfo() { - final ArrayList info = new ArrayList(); - long speed = getConfiguredProperty("cpuspeed", 4000L); - long cpus = getConfiguredProperty("cpus", 4L); - long ram = getConfiguredProperty("memory", 16000L * 1024L * 1024L); - long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L); - - String cap = getConfiguredProperty("capabilities", "hvm"); - info.add((int) cpus); - info.add(speed); - info.add(ram); - info.add(cap); - info.add(dom0ram); - return info; - - } - - private Map getSimulatorProperties() - throws ConfigurationException { - final File file = PropertiesUtil.findConfigFile("simulator.properties"); - if (file == null) { - throw new ConfigurationException( - "Unable to find simulator.properties."); - } - - s_logger.info("simulator.properties found at " + file.getAbsolutePath()); - Properties properties = new Properties(); - try { - properties.load(new FileInputStream(file)); - - final Map params = PropertiesUtil.toMap(properties); - - return params; - } 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); - } - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - Map simProps = getSimulatorProperties(); - params.putAll(simProps); - setParams(params); - _vmManager.configure(params); - _dhcpSnooper.configure(name, params); - _vmDataServer.configure(name, params); - return true; - } - - public void setParams(Map _params) { - this._params = _params; - } - - public Map getParams() { - return _params; - } - - protected synchronized StartAnswer execute(StartCommand cmd) { - VmMgr vmMgr = getVmManager(); - - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); - String vmName = vmSpec.getName(); - State state = State.Stopped; - - try { - if (!_vms.containsKey(vmName)) { - synchronized (_vms) { - _vms.put(vmName, State.Starting); - } - - MockVm vm = vmMgr.createVmFromSpec(vmSpec); - vmMgr.createVbd(vmSpec, vmName, vm); - vmMgr.createVif(vmSpec, vmName, vm); - - state = State.Running; - for (NicTO nic : cmd.getVirtualMachine().getNics()) { - if (nic.getType() == TrafficType.Guest) { - InetAddress addr = _dhcpSnooper.getIPAddr(nic.getMac(), - vmName); - nic.setIp(addr.getHostAddress()); - } - } - _vmDataServer.handleVmStarted(cmd.getVirtualMachine()); - return new StartAnswer(cmd); - } else { - String msg = "There is already a VM having the same name " - + vmName; - s_logger.warn(msg); - return new StartAnswer(cmd, msg); - } - } catch (Exception ex) { - - } finally { - synchronized (_vms) { - _vms.put(vmName, state); - } - } - return new StartAnswer(cmd); - } - - protected synchronized StopAnswer execute(StopCommand cmd) { - VmMgr vmMgr = getVmManager(); - - StopAnswer answer = null; - String vmName = cmd.getVmName(); - - Integer port = vmMgr.getVncPort(vmName); - Long bytesReceived = null; - Long bytesSent = null; - - State state = null; - synchronized (_vms) { - state = _vms.get(vmName); - _vms.put(vmName, State.Stopping); - } - try { - String result = vmMgr.stopVM(vmName, false); - if (result != null) { - s_logger.info("Trying destroy on " + vmName); - if (result == Script.ERR_TIMEOUT) { - result = vmMgr.stopVM(vmName, true); - } - - s_logger.warn("Couldn't stop " + vmName); - - if (result != null) { - return new StopAnswer(cmd, result); - } - } - - answer = new StopAnswer(cmd, null, port, bytesSent, bytesReceived); - - String result2 = vmMgr.cleanupVnet(cmd.getVnet()); - if (result2 != null) { - result = result2 + (result != null ? ("\n" + result) : ""); - answer = new StopAnswer(cmd, result, port, bytesSent, - bytesReceived); - } - - _dhcpSnooper.cleanup(vmName, null); - - return answer; - } finally { - if (answer == null || !answer.getResult()) { - synchronized (_vms) { - _vms.put(vmName, state); - } - } - } - } - - protected Answer execute(final VmDataCommand cmd) { - return _vmDataServer.handleVmDataCommand(cmd); - } - - protected Answer execute(final SavePasswordCommand cmd) { - return new Answer(cmd); - } - - protected Answer execute(RebootCommand cmd) { - VmMgr vmMgr = getVmManager(); - vmMgr.rebootVM(cmd.getVmName()); - return new RebootAnswer(cmd, "success", 0L, 0L); - } - - private Answer execute(PingTestCommand cmd) { - return new Answer(cmd); - } - - protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { - return null; - } - - private VmMgr getVmManager() { - return _vmManager; - } - - protected Answer execute(GetHostStatsCommand cmd) { - VmMgr vmMgr = getVmManager(); - return new GetHostStatsAnswer(cmd, vmMgr.getHostCpuUtilization(), - vmMgr.getHostFreeMemory(), vmMgr.getHostTotalMemory(), 0, 0, - "SimulatedHost"); - } - - protected CheckStateAnswer execute(CheckStateCommand cmd) { - State state = getVmManager().checkVmState(cmd.getVmName()); - return new CheckStateAnswer(cmd, state); - } - - protected CheckHealthAnswer execute(CheckHealthCommand cmd) { - return new CheckHealthAnswer(cmd, true); - } - - protected CheckVirtualMachineAnswer execute( - final CheckVirtualMachineCommand cmd) { - VmMgr vmMgr = getVmManager(); - final String vmName = cmd.getVmName(); - - final State state = vmMgr.checkVmState(vmName); - Integer vncPort = null; - if (state == State.Running) { - vncPort = vmMgr.getVncPort(vmName); - synchronized (_vms) { - _vms.put(vmName, State.Running); - } - } - return new CheckVirtualMachineAnswer(cmd, state, vncPort); - } - - protected Answer execute(final AttachVolumeCommand cmd) { - return new Answer(cmd); - } - - protected Answer execute(final AttachIsoCommand cmd) { - return new Answer(cmd); - } - - protected CreateAnswer execute(final CreateCommand cmd) { - try { - - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), Volume.Type.ROOT, - com.cloud.storage.Storage.StoragePoolType.LVM, cmd - .getPool().getUuid(), "dummy", "/mountpoint", - "dummyPath", 1000L, null); - return new CreateAnswer(cmd, vol); - } catch (Throwable th) { - return new CreateAnswer(cmd, new Exception("Unexpected exception")); - } - } - - protected HashMap sync() { - Map newStates; - Map oldStates = null; - - HashMap changes = new HashMap(); - - synchronized (_vms) { - newStates = getVmManager().getVmStates(); - oldStates = new HashMap(_vms.size()); - oldStates.putAll(_vms); - - for (Map.Entry entry : newStates.entrySet()) { - String vm = entry.getKey(); - - State newState = entry.getValue(); - State oldState = oldStates.remove(vm); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("VM " + vm + ": xen has state " + newState - + " and we have state " - + (oldState != null ? oldState.toString() : "null")); - } - - if (oldState == null) { - _vms.put(vm, newState); - changes.put(vm, newState); - } else if (oldState == State.Starting) { - if (newState == State.Running) { - _vms.put(vm, newState); - } else if (newState == State.Stopped) { - s_logger.debug("Ignoring vm " + vm - + " because of a lag in starting the vm."); - } - } else if (oldState == State.Stopping) { - if (newState == State.Stopped) { - _vms.put(vm, newState); - } else if (newState == State.Running) { - s_logger.debug("Ignoring vm " + vm - + " because of a lag in stopping the vm. "); - } - } else if (oldState != newState) { - _vms.put(vm, newState); - changes.put(vm, newState); - } - } - - for (Map.Entry entry : oldStates.entrySet()) { - String vm = entry.getKey(); - State oldState = entry.getValue(); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("VM " + vm - + " is now missing from xen so reporting stopped"); - } - - if (oldState == State.Stopping) { - s_logger.debug("Ignoring VM " + vm - + " in transition state stopping."); - _vms.remove(vm); - } else if (oldState == State.Starting) { - s_logger.debug("Ignoring VM " + vm - + " in transition state starting."); - } else if (oldState == State.Stopped) { - _vms.remove(vm); - } else { - changes.put(entry.getKey(), State.Stopped); - } - } - } - - return changes; - } - - protected Answer execute(DestroyCommand cmd) { - return new Answer(cmd, true, null); - } + ServerResource { + private static final Logger s_logger = Logger + .getLogger(FakeComputingResource.class); + private Map _params; + private VmMgr _vmManager = new MockVmMgr(); + protected HashMap _vms = new HashMap(20); + protected DhcpSnooper _dhcpSnooper = new FakeDhcpSnooper(); + protected VmDataServer _vmDataServer = new JettyVmDataServer(); + + @Override + public Type getType() { + return Type.Routing; + } + + @Override + public StartupCommand[] initialize() { + Map changes = null; + + final List info = getHostInfo(); + + final StartupRoutingCommand cmd = new StartupRoutingCommand( + (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), + (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, + RouterPrivateIpStrategy.HostLocal, changes); + fillNetworkInformation(cmd); + cmd.getHostDetails().putAll(getVersionStrings()); + cmd.setCluster(getConfiguredProperty("cluster", "1")); + StoragePoolInfo pi = initializeLocalStorage(); + StartupStorageCommand sscmd = new StartupStorageCommand(); + sscmd.setPoolInfo(pi); + sscmd.setGuid(pi.getUuid()); + sscmd.setDataCenter((String) _params.get("zone")); + sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); + + return new StartupCommand[] { cmd, sscmd }; + + } + + private Map getVersionStrings() { + Map result = new HashMap(); + String hostOs = (String) _params.get("Host.OS"); + String hostOsVer = (String) _params.get("Host.OS.Version"); + String hostOsKernVer = (String) _params.get("Host.OS.Kernel.Version"); + result.put("Host.OS", hostOs == null ? "Fedora" : hostOs); + result.put("Host.OS.Version", hostOsVer == null ? "14" : hostOsVer); + result.put("Host.OS.Kernel.Version", + hostOsKernVer == null ? "2.6.35.6-45.fc14.x86_64" + : hostOsKernVer); + return result; + } + + protected void fillNetworkInformation(final StartupCommand cmd) { + + cmd.setPrivateIpAddress((String) _params.get("private.ip.address")); + cmd.setPrivateMacAddress((String) _params.get("private.mac.address")); + cmd.setPrivateNetmask((String) _params.get("private.ip.netmask")); + + cmd.setStorageIpAddress((String) _params.get("private.ip.address")); + cmd.setStorageMacAddress((String) _params.get("private.mac.address")); + cmd.setStorageNetmask((String) _params.get("private.ip.netmask")); + cmd.setGatewayIpAddress((String) _params.get("gateway.ip.address")); + + } + + protected StoragePoolInfo initializeLocalStorage() { + String hostIp = (String) _params.get("private.ip.address"); + String localStoragePath = (String) _params.get("local.storage.path"); + String lh = hostIp + localStoragePath; + String uuid = UUID.nameUUIDFromBytes(lh.getBytes()).toString(); + + String capacity = (String) _params.get("local.storage.capacity"); + String available = (String) _params.get("local.storage.avail"); + + return new StoragePoolInfo(uuid, hostIp, localStoragePath, + localStoragePath, StoragePoolType.Filesystem, + Long.parseLong(capacity), Long.parseLong(available)); + + } + + @Override + public PingCommand getCurrentStatus(long id) { + final HashMap newStates = new HashMap(); + _dhcpSnooper.syncIpAddr(); + return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, + newStates); + } + + @Override + public Answer executeRequest(Command cmd) { + try { + if (cmd instanceof ReadyCommand) { + return execute((ReadyCommand) cmd); + } else if (cmd instanceof ModifySshKeysCommand) { + return execute((ModifySshKeysCommand) cmd);// TODO: remove + } else if (cmd instanceof GetHostStatsCommand) { + return execute((GetHostStatsCommand) cmd); + } else if (cmd instanceof PrimaryStorageDownloadCommand) { + return execute((PrimaryStorageDownloadCommand) cmd); + + } else if (cmd instanceof StopCommand) { + return execute((StopCommand) cmd); + } else if (cmd instanceof GetVmStatsCommand) { + return execute((GetVmStatsCommand) cmd); + } else if (cmd instanceof RebootCommand) { + return execute((RebootCommand) cmd); + } else if (cmd instanceof CheckStateCommand) { + return executeRequest(cmd); + } else if (cmd instanceof CheckHealthCommand) { + return execute((CheckHealthCommand) cmd); + } else if (cmd instanceof PingTestCommand) { + return execute((PingTestCommand) cmd); + } else if (cmd instanceof CheckVirtualMachineCommand) { + return execute((CheckVirtualMachineCommand) cmd); + } else if (cmd instanceof ReadyCommand) { + return execute((ReadyCommand) cmd); + } else if (cmd instanceof StopCommand) { + return execute((StopCommand) cmd); + } else if (cmd instanceof CreateCommand) { + return execute((CreateCommand) cmd); + } else if (cmd instanceof DestroyCommand) { + return execute((DestroyCommand) cmd); + } else if (cmd instanceof PrimaryStorageDownloadCommand) { + return execute((PrimaryStorageDownloadCommand) cmd); + } else if (cmd instanceof GetStorageStatsCommand) { + return execute((GetStorageStatsCommand) cmd); + } else if (cmd instanceof ModifyStoragePoolCommand) { + return execute((ModifyStoragePoolCommand) cmd); + } else if (cmd instanceof SecurityGroupRulesCmd) { + return execute((SecurityGroupRulesCmd) cmd); + } else if (cmd instanceof StartCommand) { + return execute((StartCommand) cmd); + } else if (cmd instanceof CleanupNetworkRulesCmd) { + return execute((CleanupNetworkRulesCmd) cmd); + } else if (cmd instanceof SavePasswordCommand) { + return execute((SavePasswordCommand) cmd); + } else if (cmd instanceof VmDataCommand) { + return execute((VmDataCommand) cmd); + } else { + s_logger.warn("Unsupported command "); + return Answer.createUnsupportedCommandAnswer(cmd); + } + } catch (final IllegalArgumentException e) { + return new Answer(cmd, false, e.getMessage()); + } + } + + private Answer execute(CleanupNetworkRulesCmd cmd) { + return new Answer(cmd); + } + + private Answer execute(SecurityGroupRulesCmd cmd) { + s_logger.info("Programmed network rules for vm " + cmd.getVmName() + + " guestIp=" + cmd.getGuestIp() + ",ingress numrules=" + + cmd.getIngressRuleSet().length + ",egress numrules=" + + cmd.getEgressRuleSet().length); + return new SecurityGroupRuleAnswer(cmd); + } + + private Answer execute(ModifyStoragePoolCommand cmd) { + long capacity = getConfiguredProperty("local.storage.capacity", + 10000000000L); + long used = 10000000L; + long available = capacity - used; + if (cmd.getAdd()) { + + ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, + capacity, used, new HashMap()); + + if (s_logger.isInfoEnabled()) + s_logger.info("Sending ModifyStoragePoolCommand answer with capacity: " + + capacity + + ", used: " + + used + + ", available: " + + available); + return answer; + } else { + if (s_logger.isInfoEnabled()) + s_logger.info("ModifyNetfsStoragePoolCmd is not add command, cmd: " + + cmd.toString()); + return new Answer(cmd); + } + } + + private Answer execute(GetStorageStatsCommand cmd) { + return new GetStorageStatsAnswer(cmd, getConfiguredProperty( + "local.storage.capacity", 100000000000L), 0L); + } + + protected synchronized ReadyAnswer execute(ReadyCommand cmd) { + return new ReadyAnswer(cmd); + } + + private Answer execute(PrimaryStorageDownloadCommand cmd) { + return new PrimaryStorageDownloadAnswer(cmd.getLocalPath(), 16000000L); + } + + private Answer execute(ModifySshKeysCommand cmd) { + return new Answer(cmd, true, null); + } + + @Override + protected String getDefaultScriptsDir() { + return null; + } + + protected String getConfiguredProperty(String key, String defaultValue) { + String val = (String) _params.get(key); + return val == null ? defaultValue : val; + } + + 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 List getHostInfo() { + final ArrayList info = new ArrayList(); + long speed = getConfiguredProperty("cpuspeed", 4000L); + long cpus = getConfiguredProperty("cpus", 4L); + long ram = getConfiguredProperty("memory", 16000L * 1024L * 1024L); + long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L); + + String cap = getConfiguredProperty("capabilities", "hvm"); + info.add((int) cpus); + info.add(speed); + info.add(ram); + info.add(cap); + info.add(dom0ram); + return info; + + } + + private Map getSimulatorProperties() + throws ConfigurationException { + final File file = PropertiesUtil.findConfigFile("simulator.properties"); + if (file == null) { + throw new ConfigurationException( + "Unable to find simulator.properties."); + } + + s_logger.info("simulator.properties found at " + file.getAbsolutePath()); + Properties properties = new Properties(); + try { + properties.load(new FileInputStream(file)); + + final Map params = PropertiesUtil.toMap(properties); + + return params; + } 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); + } + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + Map simProps = getSimulatorProperties(); + params.putAll(simProps); + setParams(params); + _vmManager.configure(params); + _dhcpSnooper.configure(name, params); + _vmDataServer.configure(name, params); + return true; + } + + public void setParams(Map _params) { + this._params = _params; + } + + public Map getParams() { + return _params; + } + + protected synchronized StartAnswer execute(StartCommand cmd) { + VmMgr vmMgr = getVmManager(); + + VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + String vmName = vmSpec.getName(); + State state = State.Stopped; + + try { + if (!_vms.containsKey(vmName)) { + synchronized (_vms) { + _vms.put(vmName, State.Starting); + } + + MockVm vm = vmMgr.createVmFromSpec(vmSpec); + vmMgr.createVbd(vmSpec, vmName, vm); + vmMgr.createVif(vmSpec, vmName, vm); + + state = State.Running; + for (NicTO nic : cmd.getVirtualMachine().getNics()) { + if (nic.getType() == TrafficType.Guest) { + InetAddress addr = _dhcpSnooper.getIPAddr(nic.getMac(), + vmName); + nic.setIp(addr.getHostAddress()); + } + } + _vmDataServer.handleVmStarted(cmd.getVirtualMachine()); + return new StartAnswer(cmd); + } else { + String msg = "There is already a VM having the same name " + + vmName; + s_logger.warn(msg); + return new StartAnswer(cmd, msg); + } + } catch (Exception ex) { + + } finally { + synchronized (_vms) { + _vms.put(vmName, state); + } + } + return new StartAnswer(cmd); + } + + protected synchronized StopAnswer execute(StopCommand cmd) { + VmMgr vmMgr = getVmManager(); + + StopAnswer answer = null; + String vmName = cmd.getVmName(); + + Integer port = vmMgr.getVncPort(vmName); + Long bytesReceived = null; + Long bytesSent = null; + + State state = null; + synchronized (_vms) { + state = _vms.get(vmName); + _vms.put(vmName, State.Stopping); + } + try { + String result = vmMgr.stopVM(vmName, false); + if (result != null) { + s_logger.info("Trying destroy on " + vmName); + if (result == Script.ERR_TIMEOUT) { + result = vmMgr.stopVM(vmName, true); + } + + s_logger.warn("Couldn't stop " + vmName); + + if (result != null) { + return new StopAnswer(cmd, result); + } + } + + answer = new StopAnswer(cmd, null, port, bytesSent, bytesReceived); + + String result2 = vmMgr.cleanupVnet(cmd.getVnet()); + if (result2 != null) { + result = result2 + (result != null ? ("\n" + result) : ""); + answer = new StopAnswer(cmd, result, port, bytesSent, + bytesReceived); + } + + _dhcpSnooper.cleanup(vmName, null); + + return answer; + } finally { + if (answer == null || !answer.getResult()) { + synchronized (_vms) { + _vms.put(vmName, state); + } + } + } + } + + protected Answer execute(final VmDataCommand cmd) { + return _vmDataServer.handleVmDataCommand(cmd); + } + + protected Answer execute(final SavePasswordCommand cmd) { + return new Answer(cmd); + } + + protected Answer execute(RebootCommand cmd) { + VmMgr vmMgr = getVmManager(); + vmMgr.rebootVM(cmd.getVmName()); + return new RebootAnswer(cmd, "success", 0L, 0L); + } + + private Answer execute(PingTestCommand cmd) { + return new Answer(cmd); + } + + protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { + return null; + } + + private VmMgr getVmManager() { + return _vmManager; + } + + protected Answer execute(GetHostStatsCommand cmd) { + VmMgr vmMgr = getVmManager(); + return new GetHostStatsAnswer(cmd, vmMgr.getHostCpuUtilization(), + vmMgr.getHostFreeMemory(), vmMgr.getHostTotalMemory(), 0, 0, + "SimulatedHost"); + } + + protected CheckStateAnswer execute(CheckStateCommand cmd) { + State state = getVmManager().checkVmState(cmd.getVmName()); + return new CheckStateAnswer(cmd, state); + } + + protected CheckHealthAnswer execute(CheckHealthCommand cmd) { + return new CheckHealthAnswer(cmd, true); + } + + protected CheckVirtualMachineAnswer execute( + final CheckVirtualMachineCommand cmd) { + VmMgr vmMgr = getVmManager(); + final String vmName = cmd.getVmName(); + + final State state = vmMgr.checkVmState(vmName); + Integer vncPort = null; + if (state == State.Running) { + vncPort = vmMgr.getVncPort(vmName); + synchronized (_vms) { + _vms.put(vmName, State.Running); + } + } + return new CheckVirtualMachineAnswer(cmd, state, vncPort); + } + + protected Answer execute(final AttachVolumeCommand cmd) { + return new Answer(cmd); + } + + protected Answer execute(final AttachIsoCommand cmd) { + return new Answer(cmd); + } + + protected CreateAnswer execute(final CreateCommand cmd) { + try { + + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), Volume.Type.ROOT, + com.cloud.storage.Storage.StoragePoolType.LVM, cmd + .getPool().getUuid(), "dummy", "/mountpoint", + "dummyPath", 1000L, null); + return new CreateAnswer(cmd, vol); + } catch (Throwable th) { + return new CreateAnswer(cmd, new Exception("Unexpected exception")); + } + } + + protected HashMap sync() { + Map newStates; + Map oldStates = null; + + HashMap changes = new HashMap(); + + synchronized (_vms) { + newStates = getVmManager().getVmStates(); + oldStates = new HashMap(_vms.size()); + oldStates.putAll(_vms); + + for (Map.Entry entry : newStates.entrySet()) { + String vm = entry.getKey(); + + State newState = entry.getValue(); + State oldState = oldStates.remove(vm); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("VM " + vm + ": xen has state " + newState + + " and we have state " + + (oldState != null ? oldState.toString() : "null")); + } + + if (oldState == null) { + _vms.put(vm, newState); + changes.put(vm, newState); + } else if (oldState == State.Starting) { + if (newState == State.Running) { + _vms.put(vm, newState); + } else if (newState == State.Stopped) { + s_logger.debug("Ignoring vm " + vm + + " because of a lag in starting the vm."); + } + } else if (oldState == State.Stopping) { + if (newState == State.Stopped) { + _vms.put(vm, newState); + } else if (newState == State.Running) { + s_logger.debug("Ignoring vm " + vm + + " because of a lag in stopping the vm. "); + } + } else if (oldState != newState) { + _vms.put(vm, newState); + changes.put(vm, newState); + } + } + + for (Map.Entry entry : oldStates.entrySet()) { + String vm = entry.getKey(); + State oldState = entry.getValue(); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("VM " + vm + + " is now missing from xen so reporting stopped"); + } + + if (oldState == State.Stopping) { + s_logger.debug("Ignoring VM " + vm + + " in transition state stopping."); + _vms.remove(vm); + } else if (oldState == State.Starting) { + s_logger.debug("Ignoring VM " + vm + + " in transition state starting."); + } else if (oldState == State.Stopped) { + _vms.remove(vm); + } else { + changes.put(entry.getKey(), State.Stopped); + } + } + } + + return changes; + } + + protected Answer execute(DestroyCommand cmd) { + return new Answer(cmd, true, null); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/KVMGuestOsMapper.java b/agent/src/com/cloud/agent/resource/computing/KVMGuestOsMapper.java index fceece42ce4..22f3935c59c 100644 --- a/agent/src/com/cloud/agent/resource/computing/KVMGuestOsMapper.java +++ b/agent/src/com/cloud/agent/resource/computing/KVMGuestOsMapper.java @@ -22,148 +22,148 @@ import java.util.Map; import org.apache.log4j.Logger; public class KVMGuestOsMapper { - private static final Logger s_logger = Logger - .getLogger(KVMGuestOsMapper.class); - private static Map s_mapper = new HashMap(); - static { - s_mapper.put("CentOS 4.5 (32-bit)", "CentOS 4.5"); - s_mapper.put("CentOS 4.6 (32-bit)", "CentOS 4.6"); - s_mapper.put("CentOS 4.7 (32-bit)", "CentOS 4.7"); - s_mapper.put("CentOS 4.8 (32-bit)", "CentOS 4.8"); - s_mapper.put("CentOS 5.0 (32-bit)", "CentOS 5.0"); - s_mapper.put("CentOS 5.0 (64-bit)", "CentOS 5.0"); - s_mapper.put("CentOS 5.1 (32-bit)", "CentOS 5.1"); - s_mapper.put("CentOS 5.1 (64-bit)", "CentOS 5.1"); - s_mapper.put("CentOS 5.2 (32-bit)", "CentOS 5.2"); - s_mapper.put("CentOS 5.2 (64-bit)", "CentOS 5.2"); - s_mapper.put("CentOS 5.3 (32-bit)", "CentOS 5.3"); - s_mapper.put("CentOS 5.3 (64-bit)", "CentOS 5.3"); - s_mapper.put("CentOS 5.4 (32-bit)", "CentOS 5.4"); - s_mapper.put("CentOS 5.4 (64-bit)", "CentOS 5.4"); - s_mapper.put("CentOS 5.5 (32-bit)", "CentOS 5.5"); - s_mapper.put("CentOS 5.5 (64-bit)", "CentOS 5.5"); - s_mapper.put("Red Hat Enterprise Linux 2", "Red Hat Enterprise Linux 2"); - s_mapper.put("Red Hat Enterprise Linux 3 (32-bit)", - "Red Hat Enterprise Linux 3"); - s_mapper.put("Red Hat Enterprise Linux 3 (64-bit)", - "Red Hat Enterprise Linux 3"); - s_mapper.put("Red Hat Enterprise Linux 4(64-bit)", - "Red Hat Enterprise Linux 4"); - s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)", - "Red Hat Enterprise Linux 4.5"); - s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)", - "Red Hat Enterprise Linux 4.6"); - s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)", - "Red Hat Enterprise Linux 4.7"); - s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)", - "Red Hat Enterprise Linux 4.8"); - s_mapper.put("Red Hat Enterprise Linux 5.0 (32-bit)", - "Red Hat Enterprise Linux 5.0"); - s_mapper.put("Red Hat Enterprise Linux 5.0 (64-bit)", - "Red Hat Enterprise Linux 5.0"); - s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", - "Red Hat Enterprise Linux 5.1"); - s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", - "Red Hat Enterprise Linux 5.1"); - s_mapper.put("Red Hat Enterprise Linux 5.2 (32-bit)", - "Red Hat Enterprise Linux 5.2"); - s_mapper.put("Red Hat Enterprise Linux 5.2 (64-bit)", - "Red Hat Enterprise Linux 5.2"); - s_mapper.put("Red Hat Enterprise Linux 5.3 (32-bit)", - "Red Hat Enterprise Linux 5.3"); - s_mapper.put("Red Hat Enterprise Linux 5.3 (64-bit)", - "Red Hat Enterprise Linux 5.3"); - s_mapper.put("Red Hat Enterprise Linux 5.4 (32-bit)", - "Red Hat Enterprise Linux 5.4"); - s_mapper.put("Red Hat Enterprise Linux 5.4 (64-bit)", - "Red Hat Enterprise Linux 5.4"); - s_mapper.put("Red Hat Enterprise Linux 5.5 (32-bit)", - "Red Hat Enterprise Linux 5.5"); - s_mapper.put("Red Hat Enterprise Linux 5.5 (64-bit)", - "Red Hat Enterprise Linux 5.5"); - s_mapper.put("Red Hat Enterprise Linux 6.0 (32-bit)", - "Red Hat Enterprise Linux 6.0"); - s_mapper.put("Red Hat Enterprise Linux 6.0 (64-bit)", - "Red Hat Enterprise Linux 6.0"); - s_mapper.put("Fedora 13", "Fedora 13"); - s_mapper.put("Fedora 12", "Fedora 12"); - s_mapper.put("Fedora 11", "Fedora 11"); - s_mapper.put("Fedora 10", "Fedora 10"); - s_mapper.put("Fedora 9", "Fedora 9"); - s_mapper.put("Fedora 8", "Fedora 8"); - s_mapper.put("Ubuntu 10.04 (32-bit)", "Ubuntu 10.04"); - s_mapper.put("Ubuntu 10.04 (64-bit)", "Ubuntu 10.04"); - s_mapper.put("Ubuntu 10.10 (32-bit)", "Ubuntu 10.10"); - s_mapper.put("Ubuntu 10.10 (64-bit)", "Ubuntu 10.10"); - s_mapper.put("Ubuntu 9.10 (32-bit)", "Ubuntu 9.10"); - s_mapper.put("Ubuntu 9.10 (64-bit)", "Ubuntu 9.10"); - s_mapper.put("Ubuntu 9.04 (32-bit)", "Ubuntu 9.04"); - s_mapper.put("Ubuntu 9.04 (64-bit)", "Ubuntu 9.04"); - s_mapper.put("Ubuntu 8.10 (32-bit)", "Ubuntu 8.10"); - s_mapper.put("Ubuntu 8.10 (64-bit)", "Ubuntu 8.10"); - s_mapper.put("Ubuntu 8.04 (32-bit)", "Other Linux"); - s_mapper.put("Ubuntu 8.04 (64-bit)", "Other Linux"); - s_mapper.put("Debian GNU/Linux 5(32-bit)", "Debian GNU/Linux 5"); - s_mapper.put("Debian GNU/Linux 5(64-bit)", "Debian GNU/Linux 5"); - s_mapper.put("Debian GNU/Linux 4(32-bit)", "Debian GNU/Linux 4"); - s_mapper.put("Debian GNU/Linux 4(64-bit)", "Debian GNU/Linux 4"); - s_mapper.put("Debian GNU/Linux 6(64-bit)", "Debian GNU/Linux 6"); - s_mapper.put("Debian GNU/Linux 6(32-bit)", "Debian GNU/Linux 6"); - s_mapper.put("Other 2.6x Linux (32-bit)", "Other 2.6x Linux"); - s_mapper.put("Other 2.6x Linux (64-bit)", "Other 2.6x Linux"); - s_mapper.put("Other Linux (32-bit)", "Other Linux"); - s_mapper.put("Other Linux (64-bit)", "Other Linux"); - s_mapper.put("Other Ubuntu (32-bit)", "Other Linux"); - s_mapper.put("Other Ubuntu (64-bit)", "Other Linux"); - s_mapper.put("Asianux 3(32-bit)", "Other Linux"); - s_mapper.put("Asianux 3(64-bit)", "Other Linux"); - s_mapper.put("Windows 7 (32-bit)", "Windows 7"); - s_mapper.put("Windows 7 (64-bit)", "Windows 7"); - s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 Standard Edition(32-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 Standard Edition(64-bit)", - "Windows Server 2003"); - s_mapper.put("Windows Server 2003 Web Edition", "Windows Server 2003"); - s_mapper.put("Microsoft Small Bussiness Server 2003", - "Windows Server 2003"); - s_mapper.put("Windows Server 2008 (32-bit)", "Windows Server 2008"); - s_mapper.put("Windows Server 2008 (64-bit)", "Windows Server 2008"); - s_mapper.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008"); - s_mapper.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000"); - s_mapper.put("Windows 2000 Server", "Windows 2000"); - s_mapper.put("Windows 2000 Advanced Server", "Windows 2000"); - s_mapper.put("Windows 2000 Professional", "Windows 2000"); - s_mapper.put("Windows Vista (32-bit)", "Windows Vista"); - s_mapper.put("Windows Vista (64-bit)", "Windows Vista"); - s_mapper.put("Windows XP SP2 (32-bit)", "Windows XP"); - s_mapper.put("Windows XP SP3 (32-bit)", "Windows XP"); - s_mapper.put("Windows XP (32-bit)", "Windows XP"); - s_mapper.put("Windows XP (64-bit)", "Windows XP"); - s_mapper.put("Windows 98", "Windows 98"); - s_mapper.put("Windows 95", "Windows 95"); - s_mapper.put("Windows NT 4", "Windows NT"); - s_mapper.put("Windows 3.1", "Windows 3.1"); - s_mapper.put("Windows PV", "Other PV"); - s_mapper.put("Other PV (32-bit)", "Other PV"); - s_mapper.put("Other PV (64-bit)", "Other PV"); + private static final Logger s_logger = Logger + .getLogger(KVMGuestOsMapper.class); + private static Map s_mapper = new HashMap(); + static { + s_mapper.put("CentOS 4.5 (32-bit)", "CentOS 4.5"); + s_mapper.put("CentOS 4.6 (32-bit)", "CentOS 4.6"); + s_mapper.put("CentOS 4.7 (32-bit)", "CentOS 4.7"); + s_mapper.put("CentOS 4.8 (32-bit)", "CentOS 4.8"); + s_mapper.put("CentOS 5.0 (32-bit)", "CentOS 5.0"); + s_mapper.put("CentOS 5.0 (64-bit)", "CentOS 5.0"); + s_mapper.put("CentOS 5.1 (32-bit)", "CentOS 5.1"); + s_mapper.put("CentOS 5.1 (64-bit)", "CentOS 5.1"); + s_mapper.put("CentOS 5.2 (32-bit)", "CentOS 5.2"); + s_mapper.put("CentOS 5.2 (64-bit)", "CentOS 5.2"); + s_mapper.put("CentOS 5.3 (32-bit)", "CentOS 5.3"); + s_mapper.put("CentOS 5.3 (64-bit)", "CentOS 5.3"); + s_mapper.put("CentOS 5.4 (32-bit)", "CentOS 5.4"); + s_mapper.put("CentOS 5.4 (64-bit)", "CentOS 5.4"); + s_mapper.put("CentOS 5.5 (32-bit)", "CentOS 5.5"); + s_mapper.put("CentOS 5.5 (64-bit)", "CentOS 5.5"); + s_mapper.put("Red Hat Enterprise Linux 2", "Red Hat Enterprise Linux 2"); + s_mapper.put("Red Hat Enterprise Linux 3 (32-bit)", + "Red Hat Enterprise Linux 3"); + s_mapper.put("Red Hat Enterprise Linux 3 (64-bit)", + "Red Hat Enterprise Linux 3"); + s_mapper.put("Red Hat Enterprise Linux 4(64-bit)", + "Red Hat Enterprise Linux 4"); + s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)", + "Red Hat Enterprise Linux 4.5"); + s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)", + "Red Hat Enterprise Linux 4.6"); + s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)", + "Red Hat Enterprise Linux 4.7"); + s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)", + "Red Hat Enterprise Linux 4.8"); + s_mapper.put("Red Hat Enterprise Linux 5.0 (32-bit)", + "Red Hat Enterprise Linux 5.0"); + s_mapper.put("Red Hat Enterprise Linux 5.0 (64-bit)", + "Red Hat Enterprise Linux 5.0"); + s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", + "Red Hat Enterprise Linux 5.1"); + s_mapper.put("Red Hat Enterprise Linux 5.1 (32-bit)", + "Red Hat Enterprise Linux 5.1"); + s_mapper.put("Red Hat Enterprise Linux 5.2 (32-bit)", + "Red Hat Enterprise Linux 5.2"); + s_mapper.put("Red Hat Enterprise Linux 5.2 (64-bit)", + "Red Hat Enterprise Linux 5.2"); + s_mapper.put("Red Hat Enterprise Linux 5.3 (32-bit)", + "Red Hat Enterprise Linux 5.3"); + s_mapper.put("Red Hat Enterprise Linux 5.3 (64-bit)", + "Red Hat Enterprise Linux 5.3"); + s_mapper.put("Red Hat Enterprise Linux 5.4 (32-bit)", + "Red Hat Enterprise Linux 5.4"); + s_mapper.put("Red Hat Enterprise Linux 5.4 (64-bit)", + "Red Hat Enterprise Linux 5.4"); + s_mapper.put("Red Hat Enterprise Linux 5.5 (32-bit)", + "Red Hat Enterprise Linux 5.5"); + s_mapper.put("Red Hat Enterprise Linux 5.5 (64-bit)", + "Red Hat Enterprise Linux 5.5"); + s_mapper.put("Red Hat Enterprise Linux 6.0 (32-bit)", + "Red Hat Enterprise Linux 6.0"); + s_mapper.put("Red Hat Enterprise Linux 6.0 (64-bit)", + "Red Hat Enterprise Linux 6.0"); + s_mapper.put("Fedora 13", "Fedora 13"); + s_mapper.put("Fedora 12", "Fedora 12"); + s_mapper.put("Fedora 11", "Fedora 11"); + s_mapper.put("Fedora 10", "Fedora 10"); + s_mapper.put("Fedora 9", "Fedora 9"); + s_mapper.put("Fedora 8", "Fedora 8"); + s_mapper.put("Ubuntu 10.04 (32-bit)", "Ubuntu 10.04"); + s_mapper.put("Ubuntu 10.04 (64-bit)", "Ubuntu 10.04"); + s_mapper.put("Ubuntu 10.10 (32-bit)", "Ubuntu 10.10"); + s_mapper.put("Ubuntu 10.10 (64-bit)", "Ubuntu 10.10"); + s_mapper.put("Ubuntu 9.10 (32-bit)", "Ubuntu 9.10"); + s_mapper.put("Ubuntu 9.10 (64-bit)", "Ubuntu 9.10"); + s_mapper.put("Ubuntu 9.04 (32-bit)", "Ubuntu 9.04"); + s_mapper.put("Ubuntu 9.04 (64-bit)", "Ubuntu 9.04"); + s_mapper.put("Ubuntu 8.10 (32-bit)", "Ubuntu 8.10"); + s_mapper.put("Ubuntu 8.10 (64-bit)", "Ubuntu 8.10"); + s_mapper.put("Ubuntu 8.04 (32-bit)", "Other Linux"); + s_mapper.put("Ubuntu 8.04 (64-bit)", "Other Linux"); + s_mapper.put("Debian GNU/Linux 5(32-bit)", "Debian GNU/Linux 5"); + s_mapper.put("Debian GNU/Linux 5(64-bit)", "Debian GNU/Linux 5"); + s_mapper.put("Debian GNU/Linux 4(32-bit)", "Debian GNU/Linux 4"); + s_mapper.put("Debian GNU/Linux 4(64-bit)", "Debian GNU/Linux 4"); + s_mapper.put("Debian GNU/Linux 6(64-bit)", "Debian GNU/Linux 6"); + s_mapper.put("Debian GNU/Linux 6(32-bit)", "Debian GNU/Linux 6"); + s_mapper.put("Other 2.6x Linux (32-bit)", "Other 2.6x Linux"); + s_mapper.put("Other 2.6x Linux (64-bit)", "Other 2.6x Linux"); + s_mapper.put("Other Linux (32-bit)", "Other Linux"); + s_mapper.put("Other Linux (64-bit)", "Other Linux"); + s_mapper.put("Other Ubuntu (32-bit)", "Other Linux"); + s_mapper.put("Other Ubuntu (64-bit)", "Other Linux"); + s_mapper.put("Asianux 3(32-bit)", "Other Linux"); + s_mapper.put("Asianux 3(64-bit)", "Other Linux"); + s_mapper.put("Windows 7 (32-bit)", "Windows 7"); + s_mapper.put("Windows 7 (64-bit)", "Windows 7"); + s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 Standard Edition(32-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 Standard Edition(64-bit)", + "Windows Server 2003"); + s_mapper.put("Windows Server 2003 Web Edition", "Windows Server 2003"); + s_mapper.put("Microsoft Small Bussiness Server 2003", + "Windows Server 2003"); + s_mapper.put("Windows Server 2008 (32-bit)", "Windows Server 2008"); + s_mapper.put("Windows Server 2008 (64-bit)", "Windows Server 2008"); + s_mapper.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008"); + s_mapper.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000"); + s_mapper.put("Windows 2000 Server", "Windows 2000"); + s_mapper.put("Windows 2000 Advanced Server", "Windows 2000"); + s_mapper.put("Windows 2000 Professional", "Windows 2000"); + s_mapper.put("Windows Vista (32-bit)", "Windows Vista"); + s_mapper.put("Windows Vista (64-bit)", "Windows Vista"); + s_mapper.put("Windows XP SP2 (32-bit)", "Windows XP"); + s_mapper.put("Windows XP SP3 (32-bit)", "Windows XP"); + s_mapper.put("Windows XP (32-bit)", "Windows XP"); + s_mapper.put("Windows XP (64-bit)", "Windows XP"); + s_mapper.put("Windows 98", "Windows 98"); + s_mapper.put("Windows 95", "Windows 95"); + s_mapper.put("Windows NT 4", "Windows NT"); + s_mapper.put("Windows 3.1", "Windows 3.1"); + s_mapper.put("Windows PV", "Other PV"); + s_mapper.put("Other PV (32-bit)", "Other PV"); + s_mapper.put("Other PV (64-bit)", "Other PV"); - } + } - public static String getGuestOsName(String guestOsName) { - String guestOS = s_mapper.get(guestOsName); - if (guestOS == null) { - s_logger.debug("Can't find the mapping of guest os: " + guestOsName); - return "Other"; - } else { - return guestOS; - } - } + public static String getGuestOsName(String guestOsName) { + String guestOS = s_mapper.get(guestOsName); + if (guestOS == null) { + s_logger.debug("Can't find the mapping of guest os: " + guestOsName); + return "Other"; + } else { + return guestOS; + } + } } diff --git a/agent/src/com/cloud/agent/resource/computing/KVMHABase.java b/agent/src/com/cloud/agent/resource/computing/KVMHABase.java index 0377efcc874..ed29a627468 100644 --- a/agent/src/com/cloud/agent/resource/computing/KVMHABase.java +++ b/agent/src/com/cloud/agent/resource/computing/KVMHABase.java @@ -34,187 +34,187 @@ import com.cloud.utils.script.OutputInterpreter.AllLinesParser; import com.cloud.utils.script.Script; public class KVMHABase { - private long _timeout = 60000; /* 1 minutes */ - protected static String _heartBeatPath; - protected long _heartBeatUpdateTimeout = 60000; - protected long _heartBeatUpdateFreq = 60000; - protected long _heartBeatUpdateMaxRetry = 3; + private long _timeout = 60000; /* 1 minutes */ + protected static String _heartBeatPath; + protected long _heartBeatUpdateTimeout = 60000; + protected long _heartBeatUpdateFreq = 60000; + protected long _heartBeatUpdateMaxRetry = 3; - public static enum PoolType { - PrimaryStorage, SecondaryStorage - } + public static enum PoolType { + PrimaryStorage, SecondaryStorage + } - public static class NfsStoragePool { - String _poolUUID; - String _poolIp; - String _poolMountSourcePath; - String _mountDestPath; - PoolType _type; + public static class NfsStoragePool { + String _poolUUID; + String _poolIp; + String _poolMountSourcePath; + String _mountDestPath; + PoolType _type; - public NfsStoragePool(String poolUUID, String poolIp, - String poolSourcePath, String mountDestPath, PoolType type) { - this._poolUUID = poolUUID; - this._poolIp = poolIp; - this._poolMountSourcePath = poolSourcePath; - this._mountDestPath = mountDestPath; - this._type = type; - } - } + public NfsStoragePool(String poolUUID, String poolIp, + String poolSourcePath, String mountDestPath, PoolType type) { + this._poolUUID = poolUUID; + this._poolIp = poolIp; + this._poolMountSourcePath = poolSourcePath; + this._mountDestPath = mountDestPath; + this._type = type; + } + } - protected String checkingMountPoint(NfsStoragePool pool, String poolName) { - String mountSource = pool._poolIp + ":" + pool._poolMountSourcePath; - String mountPaths = Script - .runSimpleBashScript("cat /proc/mounts | grep " + mountSource); - String destPath = pool._mountDestPath; + protected String checkingMountPoint(NfsStoragePool pool, String poolName) { + String mountSource = pool._poolIp + ":" + pool._poolMountSourcePath; + String mountPaths = Script + .runSimpleBashScript("cat /proc/mounts | grep " + mountSource); + String destPath = pool._mountDestPath; - if (mountPaths != null) { - String token[] = mountPaths.split(" "); - String mountType = token[2]; - String mountDestPath = token[1]; - if (mountType.equalsIgnoreCase("nfs")) { - if (poolName != null && !mountDestPath.startsWith(destPath)) { - /* we need to mount it under poolName */ - Script mount = new Script("/bin/bash", 60000); - mount.add("-c"); - mount.add("mount " + mountSource + " " + destPath); - String result = mount.execute(); - if (result != null) { - destPath = null; - } - destroyVMs(destPath); - } else if (poolName == null) { - destPath = mountDestPath; - } - } - } else { - /* Can't find the mount point? */ - /* we need to mount it under poolName */ - if (poolName != null) { - Script mount = new Script("/bin/bash", 60000); - mount.add("-c"); - mount.add("mount " + mountSource + " " + destPath); - String result = mount.execute(); - if (result != null) { - destPath = null; - } + if (mountPaths != null) { + String token[] = mountPaths.split(" "); + String mountType = token[2]; + String mountDestPath = token[1]; + if (mountType.equalsIgnoreCase("nfs")) { + if (poolName != null && !mountDestPath.startsWith(destPath)) { + /* we need to mount it under poolName */ + Script mount = new Script("/bin/bash", 60000); + mount.add("-c"); + mount.add("mount " + mountSource + " " + destPath); + String result = mount.execute(); + if (result != null) { + destPath = null; + } + destroyVMs(destPath); + } else if (poolName == null) { + destPath = mountDestPath; + } + } + } else { + /* Can't find the mount point? */ + /* we need to mount it under poolName */ + if (poolName != null) { + Script mount = new Script("/bin/bash", 60000); + mount.add("-c"); + mount.add("mount " + mountSource + " " + destPath); + String result = mount.execute(); + if (result != null) { + destPath = null; + } - destroyVMs(destPath); - } - } + destroyVMs(destPath); + } + } - return destPath; - } + return destPath; + } - protected String getMountPoint(NfsStoragePool storagePool) { + protected String getMountPoint(NfsStoragePool storagePool) { - StoragePool pool = null; - String poolName = null; - try { - pool = LibvirtConnection.getConnection() - .storagePoolLookupByUUIDString(storagePool._poolUUID); - if (pool != null) { - StoragePoolInfo spi = pool.getInfo(); - if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - pool.create(0); - } else { - /* - * Sometimes, the mount point is lost, even libvirt thinks - * the storage pool still running - */ - } - } - poolName = pool.getName(); - } catch (LibvirtException e) { + StoragePool pool = null; + String poolName = null; + try { + pool = LibvirtConnection.getConnection() + .storagePoolLookupByUUIDString(storagePool._poolUUID); + if (pool != null) { + StoragePoolInfo spi = pool.getInfo(); + if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + pool.create(0); + } else { + /* + * Sometimes, the mount point is lost, even libvirt thinks + * the storage pool still running + */ + } + } + poolName = pool.getName(); + } catch (LibvirtException e) { - } finally { - try { - if (pool != null) { - pool.free(); - } - } catch (LibvirtException e) { + } finally { + try { + if (pool != null) { + pool.free(); + } + } catch (LibvirtException e) { - } - } + } + } - return checkingMountPoint(storagePool, poolName); - } + return checkingMountPoint(storagePool, poolName); + } - protected void destroyVMs(String mountPath) { - /* if there are VMs using disks under this mount path, destroy them */ - Script cmd = new Script("/bin/bash", _timeout); - cmd.add("-c"); - cmd.add("ps axu|grep qemu|grep " + mountPath + "* |awk '{print $2}'"); - AllLinesParser parser = new OutputInterpreter.AllLinesParser(); - String result = cmd.execute(parser); + protected void destroyVMs(String mountPath) { + /* if there are VMs using disks under this mount path, destroy them */ + Script cmd = new Script("/bin/bash", _timeout); + cmd.add("-c"); + cmd.add("ps axu|grep qemu|grep " + mountPath + "* |awk '{print $2}'"); + AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = cmd.execute(parser); - if (result != null) { - return; - } + if (result != null) { + return; + } - String pids[] = parser.getLines().split("\n"); - for (String pid : pids) { - Script.runSimpleBashScript("kill -9 " + pid); - } - } + String pids[] = parser.getLines().split("\n"); + for (String pid : pids) { + Script.runSimpleBashScript("kill -9 " + pid); + } + } - protected String getHBFile(String mountPoint, String hostIP) { - return mountPoint + File.separator + "KVMHA" + File.separator + "hb-" - + hostIP; - } + protected String getHBFile(String mountPoint, String hostIP) { + return mountPoint + File.separator + "KVMHA" + File.separator + "hb-" + + hostIP; + } - protected String getHBFolder(String mountPoint) { - return mountPoint + File.separator + "KVMHA" + File.separator; - } + protected String getHBFolder(String mountPoint) { + return mountPoint + File.separator + "KVMHA" + File.separator; + } - protected String runScriptRetry(String cmdString, - OutputInterpreter interpreter) { - String result = null; - for (int i = 0; i < 3; i++) { - Script cmd = new Script("/bin/bash", _timeout); - cmd.add("-c"); - cmd.add(cmdString); - if (interpreter != null) - result = cmd.execute(interpreter); - else { - result = cmd.execute(); - } - if (result == Script.ERR_TIMEOUT) { - continue; - } else if (result == null) { - break; - } - } + protected String runScriptRetry(String cmdString, + OutputInterpreter interpreter) { + String result = null; + for (int i = 0; i < 3; i++) { + Script cmd = new Script("/bin/bash", _timeout); + cmd.add("-c"); + cmd.add(cmdString); + if (interpreter != null) + result = cmd.execute(interpreter); + else { + result = cmd.execute(); + } + if (result == Script.ERR_TIMEOUT) { + continue; + } else if (result == null) { + break; + } + } - return result; - } + return result; + } - public static void main(String[] args) { + public static void main(String[] args) { - NfsStoragePool pool = new KVMHAMonitor.NfsStoragePool(null, null, null, - null, PoolType.PrimaryStorage); + NfsStoragePool pool = new KVMHAMonitor.NfsStoragePool(null, null, null, + null, PoolType.PrimaryStorage); - KVMHAMonitor haWritter = new KVMHAMonitor(pool, "192.168.1.163", null); - Thread ha = new Thread(haWritter); - ha.start(); + KVMHAMonitor haWritter = new KVMHAMonitor(pool, "192.168.1.163", null); + Thread ha = new Thread(haWritter); + ha.start(); - KVMHAChecker haChecker = new KVMHAChecker(haWritter.getStoragePools(), - "192.168.1.163"); + KVMHAChecker haChecker = new KVMHAChecker(haWritter.getStoragePools(), + "192.168.1.163"); - ExecutorService exe = Executors.newFixedThreadPool(1); - Future future = exe.submit((Callable) haChecker); - try { - for (int i = 0; i < 10; i++) { - System.out.println(future.get()); - future = exe.submit((Callable) haChecker); - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ExecutionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + ExecutorService exe = Executors.newFixedThreadPool(1); + Future future = exe.submit((Callable) haChecker); + try { + for (int i = 0; i < 10; i++) { + System.out.println(future.get()); + future = exe.submit((Callable) haChecker); + } + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - } + } } diff --git a/agent/src/com/cloud/agent/resource/computing/KVMHAChecker.java b/agent/src/com/cloud/agent/resource/computing/KVMHAChecker.java index d9b4692ef83..b2df8c1736a 100644 --- a/agent/src/com/cloud/agent/resource/computing/KVMHAChecker.java +++ b/agent/src/com/cloud/agent/resource/computing/KVMHAChecker.java @@ -27,59 +27,59 @@ import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; public class KVMHAChecker extends KVMHABase implements Callable { - private static final Logger s_logger = Logger.getLogger(KVMHAChecker.class); - private List _pools; - private String _hostIP; - private long _heartBeatCheckerTimeout = 360000; /* 6 minutes */ + private static final Logger s_logger = Logger.getLogger(KVMHAChecker.class); + private List _pools; + private String _hostIP; + private long _heartBeatCheckerTimeout = 360000; /* 6 minutes */ - public KVMHAChecker(List pools, String host) { - this._pools = pools; - this._hostIP = host; - } + public KVMHAChecker(List pools, String host) { + this._pools = pools; + this._hostIP = host; + } - /* - * True means heartbeaing is on going, or we can't get it's status. False - * means heartbeating is stopped definitely - */ - private Boolean checkingHB() { - List results = new ArrayList(); - for (NfsStoragePool pool : _pools) { + /* + * True means heartbeaing is on going, or we can't get it's status. False + * means heartbeating is stopped definitely + */ + private Boolean checkingHB() { + List results = new ArrayList(); + for (NfsStoragePool pool : _pools) { - Script cmd = new Script(_heartBeatPath, _heartBeatCheckerTimeout, - s_logger); - cmd.add("-i", pool._poolIp); - cmd.add("-p", pool._poolMountSourcePath); - cmd.add("-m", pool._mountDestPath); - cmd.add("-h", _hostIP); - cmd.add("-r"); - cmd.add("-t", - String.valueOf((_heartBeatUpdateFreq + _heartBeatUpdateTimeout) / 1000 * 2)); - OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - String result = cmd.execute(parser); - s_logger.debug("pool: " + pool._poolIp); - s_logger.debug("reture: " + result); - s_logger.debug("parser: " + parser.getLine()); - if (result == null && parser.getLine().contains("> DEAD <")) { - s_logger.debug("read heartbeat failed: " + result); - results.add(false); - } else { - results.add(true); - } - } + Script cmd = new Script(_heartBeatPath, _heartBeatCheckerTimeout, + s_logger); + cmd.add("-i", pool._poolIp); + cmd.add("-p", pool._poolMountSourcePath); + cmd.add("-m", pool._mountDestPath); + cmd.add("-h", _hostIP); + cmd.add("-r"); + cmd.add("-t", + String.valueOf((_heartBeatUpdateFreq + _heartBeatUpdateTimeout) / 1000 * 2)); + OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); + String result = cmd.execute(parser); + s_logger.debug("pool: " + pool._poolIp); + s_logger.debug("reture: " + result); + s_logger.debug("parser: " + parser.getLine()); + if (result == null && parser.getLine().contains("> DEAD <")) { + s_logger.debug("read heartbeat failed: " + result); + results.add(false); + } else { + results.add(true); + } + } - for (Boolean r : results) { - if (r) { - return true; - } - } + for (Boolean r : results) { + if (r) { + return true; + } + } - return false; - } + return false; + } - @Override - public Boolean call() throws Exception { - // s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new - // org.apache.log4j.PatternLayout(), "System.out")); - return checkingHB(); - } + @Override + public Boolean call() throws Exception { + // s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new + // org.apache.log4j.PatternLayout(), "System.out")); + return checkingHB(); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/KVMHAMonitor.java b/agent/src/com/cloud/agent/resource/computing/KVMHAMonitor.java index 42f1a6bddf1..09d5c83928f 100644 --- a/agent/src/com/cloud/agent/resource/computing/KVMHAMonitor.java +++ b/agent/src/com/cloud/agent/resource/computing/KVMHAMonitor.java @@ -24,96 +24,96 @@ import org.apache.log4j.Logger; import com.cloud.utils.script.Script; public class KVMHAMonitor extends KVMHABase implements Runnable { - private static final Logger s_logger = Logger.getLogger(KVMHAMonitor.class); - private Map _storagePool = new ConcurrentHashMap(); + private static final Logger s_logger = Logger.getLogger(KVMHAMonitor.class); + private Map _storagePool = new ConcurrentHashMap(); - private String _hostIP; /* private ip address */ + private String _hostIP; /* private ip address */ - public KVMHAMonitor(NfsStoragePool pool, String host, String scriptPath) { - if (pool != null) { - this._storagePool.put(pool._poolUUID, pool); - } - this._hostIP = host; - this._heartBeatPath = scriptPath; - } + public KVMHAMonitor(NfsStoragePool pool, String host, String scriptPath) { + if (pool != null) { + this._storagePool.put(pool._poolUUID, pool); + } + this._hostIP = host; + this._heartBeatPath = scriptPath; + } - public void addStoragePool(NfsStoragePool pool) { - synchronized (_storagePool) { - this._storagePool.put(pool._poolUUID, pool); - } - } + public void addStoragePool(NfsStoragePool pool) { + synchronized (_storagePool) { + this._storagePool.put(pool._poolUUID, pool); + } + } - public void removeStoragePool(String uuid) { - synchronized (_storagePool) { - this._storagePool.remove(uuid); - } - } + public void removeStoragePool(String uuid) { + synchronized (_storagePool) { + this._storagePool.remove(uuid); + } + } - public List getStoragePools() { - synchronized (_storagePool) { - return new ArrayList(_storagePool.values()); - } - } + public List getStoragePools() { + synchronized (_storagePool) { + return new ArrayList(_storagePool.values()); + } + } - private class Monitor implements Runnable { + private class Monitor implements Runnable { - @Override - public void run() { - synchronized (_storagePool) { - for (NfsStoragePool primaryStoragePool : _storagePool.values()) { - String result = null; - for (int i = 0; i < 5; i++) { - Script cmd = new Script(_heartBeatPath, - _heartBeatUpdateTimeout, s_logger); - cmd.add("-i", primaryStoragePool._poolIp); - cmd.add("-p", primaryStoragePool._poolMountSourcePath); - cmd.add("-m", primaryStoragePool._mountDestPath); - cmd.add("-h", _hostIP); - result = cmd.execute(); - if (result != null) { - s_logger.warn("write heartbeat failed: " + result - + ", retry: " + i); - } else { - break; - } - } + @Override + public void run() { + synchronized (_storagePool) { + for (NfsStoragePool primaryStoragePool : _storagePool.values()) { + String result = null; + for (int i = 0; i < 5; i++) { + Script cmd = new Script(_heartBeatPath, + _heartBeatUpdateTimeout, s_logger); + cmd.add("-i", primaryStoragePool._poolIp); + cmd.add("-p", primaryStoragePool._poolMountSourcePath); + cmd.add("-m", primaryStoragePool._mountDestPath); + cmd.add("-h", _hostIP); + result = cmd.execute(); + if (result != null) { + s_logger.warn("write heartbeat failed: " + result + + ", retry: " + i); + } else { + break; + } + } - if (result != null) { - s_logger.warn("write heartbeat failed: " + result - + "; reboot the host"); - Script cmd = new Script(_heartBeatPath, - _heartBeatUpdateTimeout, s_logger); - cmd.add("-i", primaryStoragePool._poolIp); - cmd.add("-p", primaryStoragePool._poolMountSourcePath); - cmd.add("-m", primaryStoragePool._mountDestPath); - cmd.add("-c"); - result = cmd.execute(); - } - } - } + if (result != null) { + s_logger.warn("write heartbeat failed: " + result + + "; reboot the host"); + Script cmd = new Script(_heartBeatPath, + _heartBeatUpdateTimeout, s_logger); + cmd.add("-i", primaryStoragePool._poolIp); + cmd.add("-p", primaryStoragePool._poolMountSourcePath); + cmd.add("-m", primaryStoragePool._mountDestPath); + cmd.add("-c"); + result = cmd.execute(); + } + } + } - } - } + } + } - @Override - public void run() { - // s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new - // org.apache.log4j.PatternLayout(), "System.out")); - while (true) { - Thread monitorThread = new Thread(new Monitor()); - monitorThread.start(); - try { - monitorThread.join(); - } catch (InterruptedException e) { + @Override + public void run() { + // s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new + // org.apache.log4j.PatternLayout(), "System.out")); + while (true) { + Thread monitorThread = new Thread(new Monitor()); + monitorThread.start(); + try { + monitorThread.join(); + } catch (InterruptedException e) { - } + } - try { - Thread.sleep(_heartBeatUpdateFreq); - } catch (InterruptedException e) { + try { + Thread.sleep(_heartBeatUpdateFreq); + } catch (InterruptedException e) { - } - } - } + } + } + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtCapXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtCapXMLParser.java index 9e2e496978a..4c5fa29485c 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtCapXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtCapXMLParser.java @@ -30,165 +30,165 @@ import org.xml.sax.SAXException; * */ public class LibvirtCapXMLParser extends LibvirtXMLParser { - private boolean _host = false; - private boolean _guest = false; - private boolean _osType = false; - private boolean _domainTypeKVM = false; - private boolean _emulatorFlag = false; - private final StringBuffer _emulator = new StringBuffer(); - private final StringBuffer _capXML = new StringBuffer(); - private static final Logger s_logger = Logger - .getLogger(LibvirtCapXMLParser.class); - private final ArrayList guestOsTypes = new ArrayList(); + private boolean _host = false; + private boolean _guest = false; + private boolean _osType = false; + private boolean _domainTypeKVM = false; + private boolean _emulatorFlag = false; + private final StringBuffer _emulator = new StringBuffer(); + private final StringBuffer _capXML = new StringBuffer(); + private static final Logger s_logger = Logger + .getLogger(LibvirtCapXMLParser.class); + private final ArrayList guestOsTypes = new ArrayList(); - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - if (qName.equalsIgnoreCase("host")) { - _host = false; - } else if (qName.equalsIgnoreCase("os_type")) { - _osType = false; - } else if (qName.equalsIgnoreCase("guest")) { - _guest = false; - } else if (qName.equalsIgnoreCase("domain")) { - _domainTypeKVM = false; - } else if (qName.equalsIgnoreCase("emulator")) { - _emulatorFlag = false; + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + if (qName.equalsIgnoreCase("host")) { + _host = false; + } else if (qName.equalsIgnoreCase("os_type")) { + _osType = false; + } else if (qName.equalsIgnoreCase("guest")) { + _guest = false; + } else if (qName.equalsIgnoreCase("domain")) { + _domainTypeKVM = false; + } else if (qName.equalsIgnoreCase("emulator")) { + _emulatorFlag = false; - } else if (_host) { - _capXML.append("<").append("/").append(qName).append(">"); - } - } + } else if (_host) { + _capXML.append("<").append("/").append(qName).append(">"); + } + } - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - if (_host) { - _capXML.append(ch, start, length); - } else if (_osType) { - guestOsTypes.add(new String(ch, start, length)); - } else if (_emulatorFlag) { - _emulator.append(ch, start, length); - } - } + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + if (_host) { + _capXML.append(ch, start, length); + } else if (_osType) { + guestOsTypes.add(new String(ch, start, length)); + } else if (_emulatorFlag) { + _emulator.append(ch, start, length); + } + } - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - if (qName.equalsIgnoreCase("host")) { - _host = true; - } else if (qName.equalsIgnoreCase("guest")) { - _guest = true; - } else if (qName.equalsIgnoreCase("os_type")) { - if (_guest) { - _osType = true; - } - } else if (qName.equalsIgnoreCase("domain")) { - for (int i = 0; i < attributes.getLength(); i++) { - if (attributes.getQName(i).equalsIgnoreCase("type") - && attributes.getValue(i).equalsIgnoreCase("kvm")) { - _domainTypeKVM = true; - } - } - } else if (qName.equalsIgnoreCase("emulator") && _domainTypeKVM) { - _emulatorFlag = true; - _emulator.delete(0, _emulator.length()); - } else if (_host) { - _capXML.append("<").append(qName); - for (int i = 0; i < attributes.getLength(); i++) { - _capXML.append(" ").append(attributes.getQName(i)).append("=") - .append(attributes.getValue(i)); - } - _capXML.append(">"); - } + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + if (qName.equalsIgnoreCase("host")) { + _host = true; + } else if (qName.equalsIgnoreCase("guest")) { + _guest = true; + } else if (qName.equalsIgnoreCase("os_type")) { + if (_guest) { + _osType = true; + } + } else if (qName.equalsIgnoreCase("domain")) { + for (int i = 0; i < attributes.getLength(); i++) { + if (attributes.getQName(i).equalsIgnoreCase("type") + && attributes.getValue(i).equalsIgnoreCase("kvm")) { + _domainTypeKVM = true; + } + } + } else if (qName.equalsIgnoreCase("emulator") && _domainTypeKVM) { + _emulatorFlag = true; + _emulator.delete(0, _emulator.length()); + } else if (_host) { + _capXML.append("<").append(qName); + for (int i = 0; i < attributes.getLength(); i++) { + _capXML.append(" ").append(attributes.getQName(i)).append("=") + .append(attributes.getValue(i)); + } + _capXML.append(">"); + } - } + } - public String parseCapabilitiesXML(String capXML) { - if (!_initialized) { - return null; - } - try { - _sp.parse(new InputSource(new StringReader(capXML)), this); - return _capXML.toString(); - } catch (SAXException se) { - s_logger.warn(se.getMessage()); - } catch (IOException ie) { - s_logger.error(ie.getMessage()); - } - return null; - } + public String parseCapabilitiesXML(String capXML) { + if (!_initialized) { + return null; + } + try { + _sp.parse(new InputSource(new StringReader(capXML)), this); + return _capXML.toString(); + } catch (SAXException se) { + s_logger.warn(se.getMessage()); + } catch (IOException ie) { + s_logger.error(ie.getMessage()); + } + return null; + } - public ArrayList getGuestOsType() { - return guestOsTypes; - } + public ArrayList getGuestOsType() { + return guestOsTypes; + } - public String getEmulator() { - return _emulator.toString(); - } + public String getEmulator() { + return _emulator.toString(); + } - public static void main(String[] args) { - String capXML = "" + " " + " " - + " x86_64" + " core2duo" - + " " - + " " - + " " - + " " - + " " + " " - + " " - + " " - + " " + " " - + " " + " " - + " " + " " - + " " + " " + " " - + " " - + " tcp" - + " " + " " - + " " + " " - + " " + " " - + " " + " " - + " " + " " + " " - + " " + " " + "" + " " - + " hvm" + " " - + " 32" - + " /usr/bin/qemu" - + " pc-0.11" - + " pc" - + " pc-0.10" - + " isapc" - + " " + " " - + " " - + " /usr/bin/qemu-kvm" - + " pc-0.11" - + " pc" - + " pc-0.10" - + " isapc" + " " - + " " + " " + " " - + " " + " " - + " " - + " " + " " - + " " + " " + " hvm" - + " " + " 64" - + " /usr/bin/qemu-system-x86_64" - + " pc-0.11" - + " pc" - + " pc-0.10" - + " isapc" - + " " + " " - + " " - + " /usr/bin/qemu-kvm" - + " pc-0.11" - + " pc" - + " pc-0.10" - + " isapc" + " " - + " " + " " + " " - + " " - + " " + " " - + " " + ""; + public static void main(String[] args) { + String capXML = "" + " " + " " + + " x86_64" + " core2duo" + + " " + + " " + + " " + + " " + + " " + " " + + " " + + " " + + " " + " " + + " " + " " + + " " + " " + + " " + " " + " " + + " " + + " tcp" + + " " + " " + + " " + " " + + " " + " " + + " " + " " + + " " + " " + " " + + " " + " " + "" + " " + + " hvm" + " " + + " 32" + + " /usr/bin/qemu" + + " pc-0.11" + + " pc" + + " pc-0.10" + + " isapc" + + " " + " " + + " " + + " /usr/bin/qemu-kvm" + + " pc-0.11" + + " pc" + + " pc-0.10" + + " isapc" + " " + + " " + " " + " " + + " " + " " + + " " + + " " + " " + + " " + " " + " hvm" + + " " + " 64" + + " /usr/bin/qemu-system-x86_64" + + " pc-0.11" + + " pc" + + " pc-0.10" + + " isapc" + + " " + " " + + " " + + " /usr/bin/qemu-kvm" + + " pc-0.11" + + " pc" + + " pc-0.10" + + " isapc" + " " + + " " + " " + " " + + " " + + " " + " " + + " " + ""; - LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); - String cap = parser.parseCapabilitiesXML(capXML); - System.out.println(parser.getGuestOsType()); - System.out.println(parser.getEmulator()); - } + LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); + String cap = parser.parseCapabilitiesXML(capXML); + System.out.println(parser.getGuestOsType()); + System.out.println(parser.getEmulator()); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index c032e2c1912..112ab61e50b 100755 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -227,3861 +227,3861 @@ import com.cloud.vm.VirtualMachineName; **/ @Local(value = { ServerResource.class }) public class LibvirtComputingResource extends ServerResourceBase implements - ServerResource { - private static final Logger s_logger = Logger - .getLogger(LibvirtComputingResource.class); - - private String _modifyVlanPath; - private String _versionstringpath; - private String _patchdomrPath; - private String _createvmPath; - private String _manageSnapshotPath; - private String _createTmplPath; - private String _heartBeatPath; - private String _securityGroupPath; - private String _networkUsagePath; - private String _host; - private String _dcId; - private String _pod; - private String _clusterId; - private int _migrateSpeed; - - private long _hvVersion; - private KVMHAMonitor _monitor; - private final String _SSHKEYSPATH = "/root/.ssh"; - private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator - + "id_rsa.cloud"; - private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator - + "id_rsa.pub.cloud"; - private String _mountPoint = "/mnt"; - StorageLayer _storage; - private KVMStoragePoolManager _storagePoolMgr; - - private static final class KeyValueInterpreter extends OutputInterpreter { - private final Map map = new HashMap(); - - @Override - public String interpret(BufferedReader reader) throws IOException { - String line = null; - int numLines = 0; - while ((line = reader.readLine()) != null) { - String[] toks = line.trim().split("="); - if (toks.length < 2) { - s_logger.warn("Failed to parse Script output: " + line); - } else { - map.put(toks[0].trim(), toks[1].trim()); - } - numLines++; - } - if (numLines == 0) { - s_logger.warn("KeyValueInterpreter: no output lines?"); - } - return null; - } - - public Map getKeyValues() { - return map; - } - } - - @Override - protected String getDefaultScriptsDir() { - return null; - } - - protected static MessageFormat SnapshotXML = new MessageFormat( - " " + " {0}" + " " - + " {1}" + " " - + " "); - - protected String _hypervisorType; - protected String _hypervisorURI; - protected String _hypervisorPath; - protected String _sysvmISOPath; - protected String _privNwName; - protected String _privBridgeName; - protected String _linkLocalBridgeName; - protected String _publicBridgeName; - protected String _guestBridgeName; - protected String _privateIp; - protected String _pool; - protected String _localGateway; - private boolean _can_bridge_firewall; - protected String _localStoragePath; - protected String _localStorageUUID; - private Pair _pifs; - private final Map _vmStats = new ConcurrentHashMap(); - - protected boolean _disconnected = true; - protected int _timeout; - protected int _cmdsTimeout; - protected int _stopTimeout; - protected static HashMap s_statesTable; - static { - s_statesTable = new HashMap(); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF, - State.Stopped); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED, - State.Running); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING, - State.Running); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED, - State.Running); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE, - State.Unknown); - s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN, - State.Stopping); - } - - protected HashMap _vms = new HashMap(20); - protected List _vmsKilled = new ArrayList(); - - private VirtualRoutingResource _virtRouterResource; - - private String _pingTestPath; - - private int _dom0MinMem; - - protected enum defineOps { - UNDEFINE_VM, DEFINE_VM - } - - private String getEndIpFromStartIp(String startIp, int numIps) { - String[] tokens = startIp.split("[.]"); - assert (tokens.length == 4); - int lastbyte = Integer.parseInt(tokens[3]); - lastbyte = lastbyte + numIps; - tokens[3] = Integer.toString(lastbyte); - StringBuilder end = new StringBuilder(15); - end.append(tokens[0]).append(".").append(tokens[1]).append(".") - .append(tokens[2]).append(".").append(tokens[3]); - return end.toString(); - } - - private Map getDeveloperProperties() - throws ConfigurationException { - final File file = PropertiesUtil.findConfigFile("developer.properties"); - if (file == null) { - throw new ConfigurationException( - "Unable to find developer.properties."); - } - - s_logger.info("developer.properties found at " + file.getAbsolutePath()); - Properties properties = new Properties(); - try { - properties.load(new FileInputStream(file)); - - String startMac = (String) properties.get("private.macaddr.start"); - if (startMac == null) { - throw new ConfigurationException( - "Developers must specify start mac for private ip range"); - } - - String startIp = (String) properties.get("private.ipaddr.start"); - if (startIp == null) { - throw new ConfigurationException( - "Developers must specify start ip for private ip range"); - } - final Map params = PropertiesUtil.toMap(properties); - - String endIp = (String) properties.get("private.ipaddr.end"); - if (endIp == null) { - endIp = getEndIpFromStartIp(startIp, 16); - params.put("private.ipaddr.end", endIp); - } - return params; - } 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 String getDefaultNetworkScriptsDir() { - return "scripts/vm/network/vnet"; - } - - protected String getDefaultStorageScriptsDir() { - return "scripts/storage/qcow2"; - } - - private void saveProperties(Map params) - 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 _properties = new Properties(); - _properties.load(new FileInputStream(file)); - Set names = _properties.stringPropertyNames(); - for (String key : params.keySet()) { - if (!names.contains(key)) { - _properties.setProperty(key, (String) params.get(key)); - } - } - _properties.store(new FileOutputStream(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); - } - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - boolean success = super.configure(name, params); - if (!success) { - return false; - } - - try { - Class clazz = Class - .forName("com.cloud.storage.JavaStorageLayer"); - _storage = (StorageLayer) ComponentLocator.inject(clazz); - _storage.configure("StorageLayer", params); - } catch (ClassNotFoundException e) { - throw new ConfigurationException("Unable to find class " - + "com.cloud.storage.JavaStorageLayer"); - } - - _virtRouterResource = new VirtualRoutingResource(); - - // Set the domr scripts directory - params.put("domr.scripts.dir", "scripts/network/domr/kvm"); - - success = _virtRouterResource.configure(name, params); - - String kvmScriptsDir = (String) params.get("kvm.scripts.dir"); - if (kvmScriptsDir == null) { - kvmScriptsDir = "scripts/vm/hypervisor/kvm"; - } - - String networkScriptsDir = (String) params.get("network.scripts.dir"); - if (networkScriptsDir == null) { - networkScriptsDir = getDefaultNetworkScriptsDir(); - } - - String storageScriptsDir = (String) params.get("storage.scripts.dir"); - if (storageScriptsDir == null) { - storageScriptsDir = getDefaultStorageScriptsDir(); - } - - if (!success) { - return false; - } - - _host = (String) params.get("host"); - if (_host == null) { - _host = "localhost"; - } - - _dcId = (String) params.get("zone"); - if (_dcId == null) { - _dcId = "default"; - } - - _pod = (String) params.get("pod"); - if (_pod == null) { - _pod = "default"; - } - - _clusterId = (String) params.get("cluster"); - - _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); - if (_modifyVlanPath == null) { - throw new ConfigurationException("Unable to find modifyvlan.sh"); - } - - _versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh"); - if (_versionstringpath == null) { - throw new ConfigurationException("Unable to find versions.sh"); - } - - _patchdomrPath = Script.findScript(kvmScriptsDir + "/patch/", - "rundomrpre.sh"); - if (_patchdomrPath == null) { - throw new ConfigurationException("Unable to find rundomrpre.sh"); - } - - _heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh"); - if (_heartBeatPath == null) { - throw new ConfigurationException("Unable to find kvmheartbeat.sh"); - } - - _createvmPath = Script.findScript(storageScriptsDir, "createvm.sh"); - if (_createvmPath == null) { - throw new ConfigurationException("Unable to find the createvm.sh"); - } - - _manageSnapshotPath = Script.findScript(storageScriptsDir, - "managesnapshot.sh"); - if (_manageSnapshotPath == null) { - throw new ConfigurationException( - "Unable to find the managesnapshot.sh"); - } - - _createTmplPath = Script - .findScript(storageScriptsDir, "createtmplt.sh"); - if (_createTmplPath == null) { - throw new ConfigurationException( - "Unable to find the createtmplt.sh"); - } - - _securityGroupPath = Script.findScript(networkScriptsDir, - "security_group.py"); - if (_securityGroupPath == null) { - throw new ConfigurationException( - "Unable to find the security_group.py"); - } - - _networkUsagePath = Script.findScript("scripts/network/domr/", - "networkUsage.sh"); - if (_networkUsagePath == null) { - throw new ConfigurationException( - "Unable to find the networkUsage.sh"); - } - - String value = (String) params.get("developer"); - boolean isDeveloper = Boolean.parseBoolean(value); - - if (isDeveloper) { - params.putAll(getDeveloperProperties()); - } - - _pool = (String) params.get("pool"); - if (_pool == null) { - _pool = "/root"; - } - - String instance = (String) params.get("instance"); - - _hypervisorType = (String) params.get("hypervisor.type"); - if (_hypervisorType == null) { - _hypervisorType = "kvm"; - } - - _hypervisorURI = (String) params.get("hypervisor.uri"); - if (_hypervisorURI == null) { - _hypervisorURI = "qemu:///system"; - } - String startMac = (String) params.get("private.macaddr.start"); - if (startMac == null) { - startMac = "00:16:3e:77:e2:a0"; - } - - String startIp = (String) params.get("private.ipaddr.start"); - if (startIp == null) { - startIp = "192.168.166.128"; - } - - _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); - if (_pingTestPath == null) { - throw new ConfigurationException("Unable to find the pingtest.sh"); - } - - _linkLocalBridgeName = (String) params.get("private.bridge.name"); - if (_linkLocalBridgeName == null) { - if (isDeveloper) { - _linkLocalBridgeName = "cloud-" + instance + "-0"; - } else { - _linkLocalBridgeName = "cloud0"; - } - } - - _publicBridgeName = (String) params.get("public.network.device"); - if (_publicBridgeName == null) { - _publicBridgeName = "cloudbr0"; - } - - _privBridgeName = (String) params.get("private.network.device"); - if (_privBridgeName == null) { - _privBridgeName = "cloudbr1"; - } - - _guestBridgeName = (String) params.get("guest.network.device"); - if (_guestBridgeName == null) { - _guestBridgeName = _privBridgeName; - } - - _privNwName = (String) params.get("private.network.name"); - if (_privNwName == null) { - if (isDeveloper) { - _privNwName = "cloud-" + instance + "-private"; - } else { - _privNwName = "cloud-private"; - } - } - - _localStoragePath = (String) params.get("local.storage.path"); - if (_localStoragePath == null) { - _localStoragePath = "/var/lib/libvirt/images/"; - } - - _localStorageUUID = (String) params.get("local.storage.uuid"); - if (_localStorageUUID == null) { - _localStorageUUID = UUID.randomUUID().toString(); - params.put("local.storage.uuid", _localStorageUUID); - } - - value = (String) params.get("scripts.timeout"); - _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; - - value = (String) params.get("stop.script.timeout"); - _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000; - - value = (String) params.get("cmds.timeout"); - _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; - - value = (String) params.get("host.reserved.mem.mb"); - _dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024; - - value = (String) params.get("debug.mode"); - - LibvirtConnection.initialize(_hypervisorURI); - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.getMessage()); - } - - /* Does node support HVM guest? If not, exit */ - if (!IsHVMEnabled(conn)) { - throw new ConfigurationException( - "NO HVM support on this machine, pls make sure: " - + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. " - + "2. kvm modules is installed"); - } - - _hypervisorPath = getHypervisorPath(conn); - try { - _hvVersion = conn.getVersion(); - _hvVersion = (_hvVersion % 1000000) / 1000; - } catch (LibvirtException e) { - - } - - String[] info = NetUtils.getNetworkParams(_privateNic); - - _monitor = new KVMHAMonitor(null, info[0], _heartBeatPath); - Thread ha = new Thread(_monitor); - ha.start(); - - _storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor); - - _sysvmISOPath = (String) params.get("systemvm.iso.path"); - if (_sysvmISOPath == null) { - String[] isoPaths = { "/usr/lib64/cloud/agent/vms/systemvm.iso", - "/usr/lib/cloud/agent/vms/systemvm.iso" }; - for (String isoPath : isoPaths) { - if (_storage.exists(isoPath)) { - _sysvmISOPath = isoPath; - break; - } - } - if (_sysvmISOPath == null) { - s_logger.debug("Can't find system vm ISO"); - } - } - - try { - createControlNetwork(conn); - } catch (LibvirtException e) { - throw new ConfigurationException(e.getMessage()); - } - - _pifs = getPifs(); - if (_pifs.first() == null) { - s_logger.debug("Failed to get private nic name"); - throw new ConfigurationException("Failed to get private nic name"); - } - - if (_pifs.second() == null) { - s_logger.debug("Failed to get public nic name"); - throw new ConfigurationException("Failed to get public nic name"); - } - s_logger.debug("Found pif: " + _pifs.first() + " on " + _privBridgeName - + ", pif: " + _pifs.second() + " on " + _publicBridgeName); - - _can_bridge_firewall = can_bridge_firewall(_pifs.second()); - - _localGateway = Script - .runSimpleBashScript("ip route |grep default|awk '{print $3}'"); - if (_localGateway == null) { - s_logger.debug("Failed to found the local gateway"); - } - - _mountPoint = (String) params.get("mount.path"); - if (_mountPoint == null) { - _mountPoint = "/mnt"; - } - - value = (String) params.get("vm.migrate.speed"); - _migrateSpeed = NumbersUtil.parseInt(value, -1); - if (_migrateSpeed == -1) { - //get guest network device speed - _migrateSpeed = 0; - String speed = Script.runSimpleBashScript("ethtool " + _pifs.second() + " |grep Speed | cut -d \\ -f 2"); - if (speed != null) { - String[] tokens = speed.split("M"); - if (tokens.length == 2) { - try { - _migrateSpeed = Integer.parseInt(tokens[0]); - } catch (Exception e) { - - } - s_logger.debug("device " + _pifs.second() + " has speed: " + String.valueOf(_migrateSpeed)); - } - } - params.put("vm.migrate.speed", String.valueOf(_migrateSpeed)); - } - saveProperties(params); - - return true; - } - - private Pair getPifs() { - /* get pifs from bridge */ - String pubPif = null; - String privPif = null; - String vlan = null; - if (_publicBridgeName != null) { - pubPif = Script.runSimpleBashScript("brctl show | grep " - + _publicBridgeName + " | awk '{print $4}'"); - vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pubPif); - if (vlan != null && !vlan.isEmpty()) { - pubPif = Script - .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" - + pubPif + " | awk {'print $2'}"); - } - } - if (_guestBridgeName != null) { - privPif = Script.runSimpleBashScript("brctl show | grep " - + _guestBridgeName + " | awk '{print $4}'"); - vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + privPif); - if (vlan != null && !vlan.isEmpty()) { - privPif = Script - .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" - + privPif + " | awk {'print $2'}"); - } - } - return new Pair(privPif, pubPif); - } - - private boolean checkNetwork(String networkName) { - if (networkName == null) { - return true; - } - - String name = Script.runSimpleBashScript("brctl show | grep " - + networkName + " | awk '{print $4}'"); - if (name == null) { - return false; - } else { - return true; - } - } - - private String getVnetId(String vnetId) { - return vnetId; - } - - private void patchSystemVm(String cmdLine, String dataDiskPath, - String vmName) throws InternalErrorException { - String result; - final Script command = new Script(_patchdomrPath, _timeout, s_logger); - command.add("-l", vmName); - command.add("-t", "all"); - command.add("-d", dataDiskPath); - command.add("-p", cmdLine.replaceAll(" ", "%")); - result = command.execute(); - if (result != null) { - throw new InternalErrorException(result); - } - } - - boolean isDirectAttachedNetwork(String type) { - if ("untagged".equalsIgnoreCase(type)) { - return true; - } else { - try { - Long.valueOf(type); - } catch (NumberFormatException e) { - return true; - } - return false; - } - } - - protected String startDomain(Connect conn, String vmName, String domainXML) - throws LibvirtException, InternalErrorException { - /* No duplicated vm, we will success, or failed */ - boolean failed = false; - Domain dm = null; - try { - dm = conn.domainDefineXML(domainXML); - } catch (final LibvirtException e) { - /* Duplicated defined vm */ - s_logger.warn("Failed to define domain " + vmName + ": " - + e.getMessage()); - failed = true; - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (final LibvirtException e) { - - } - } - - /* If failed, undefine the vm */ - Domain dmOld = null; - Domain dmNew = null; - try { - if (failed) { - dmOld = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - dmOld.undefine(); - dmNew = conn.domainDefineXML(domainXML); - } - } catch (final LibvirtException e) { - s_logger.warn("Failed to define domain (second time) " + vmName - + ": " + e.getMessage()); - throw e; - } catch (Exception e) { - s_logger.warn("Failed to define domain (second time) " + vmName - + ": " + e.getMessage()); - throw new InternalErrorException(e.toString()); - } finally { - try { - if (dmOld != null) { - dmOld.free(); - } - if (dmNew != null) { - dmNew.free(); - } - } catch (final LibvirtException e) { - - } - } - - /* Start the VM */ - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - dm.create(); - } catch (LibvirtException e) { - s_logger.warn("Failed to start domain: " + vmName + ": " - + e.getMessage()); - throw e; - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (final LibvirtException e) { - - } - } - return null; - } - - @Override - public boolean stop() { - try { - Connect conn = LibvirtConnection.getConnection(); - conn.close(); - } catch (LibvirtException e) { - } - - return true; - } - - public static void main(String[] args) { - s_logger.addAppender(new org.apache.log4j.ConsoleAppender( - new org.apache.log4j.PatternLayout(), "System.out")); - LibvirtComputingResource test = new LibvirtComputingResource(); - Map params = new HashMap(); - try { - test.configure("test", params); - } catch (ConfigurationException e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - String result = null; - // String result = test.startDomainRouter("domr1", - // "/var/lib/images/centos.5-4.x86-64/centos-small.img", 128, "0064", - // "02:00:30:00:01:01", "00:16:3e:77:e2:a1", "02:00:30:00:64:01"); - boolean created = (result == null); - s_logger.info("Domain " + (created ? " " : " not ") + " created"); - - s_logger.info("Rule " + (created ? " " : " not ") + " created"); - test.stop(); - } - - @Override - public Answer executeRequest(Command cmd) { - - try { - if (cmd instanceof StopCommand) { - return execute((StopCommand) cmd); - } else if (cmd instanceof GetVmStatsCommand) { - return execute((GetVmStatsCommand) cmd); - } else if (cmd instanceof RebootRouterCommand) { - return execute((RebootRouterCommand) cmd); - } else if (cmd instanceof RebootCommand) { - return execute((RebootCommand) cmd); - } else if (cmd instanceof GetHostStatsCommand) { - return execute((GetHostStatsCommand) cmd); - } else if (cmd instanceof CheckStateCommand) { - return executeRequest(cmd); - } else if (cmd instanceof CheckHealthCommand) { - return execute((CheckHealthCommand) cmd); - } else if (cmd instanceof PrepareForMigrationCommand) { - return execute((PrepareForMigrationCommand) cmd); - } else if (cmd instanceof MigrateCommand) { - return execute((MigrateCommand) cmd); - } else if (cmd instanceof PingTestCommand) { - return execute((PingTestCommand) cmd); - } else if (cmd instanceof CheckVirtualMachineCommand) { - return execute((CheckVirtualMachineCommand) cmd); - } else if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand) cmd); - } else if (cmd instanceof AttachIsoCommand) { - return execute((AttachIsoCommand) cmd); - } else if (cmd instanceof AttachVolumeCommand) { - return execute((AttachVolumeCommand) cmd); - } else if (cmd instanceof StopCommand) { - return execute((StopCommand) cmd); - } else if (cmd instanceof CheckConsoleProxyLoadCommand) { - return execute((CheckConsoleProxyLoadCommand) cmd); - } else if (cmd instanceof WatchConsoleProxyLoadCommand) { - return execute((WatchConsoleProxyLoadCommand) cmd); - } else if (cmd instanceof GetVncPortCommand) { - return execute((GetVncPortCommand) cmd); - } else if (cmd instanceof ModifySshKeysCommand) { - return execute((ModifySshKeysCommand) cmd); - } else if (cmd instanceof MaintainCommand) { - return execute((MaintainCommand) cmd); - } else if (cmd instanceof CreateCommand) { - return execute((CreateCommand) cmd); - } else if (cmd instanceof DestroyCommand) { - return execute((DestroyCommand) cmd); - } else if (cmd instanceof PrimaryStorageDownloadCommand) { - return execute((PrimaryStorageDownloadCommand) cmd); - } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) { - return execute((CreatePrivateTemplateFromVolumeCommand) cmd); - } else if (cmd instanceof GetStorageStatsCommand) { - return execute((GetStorageStatsCommand) cmd); - } else if (cmd instanceof ManageSnapshotCommand) { - return execute((ManageSnapshotCommand) cmd); - } else if (cmd instanceof BackupSnapshotCommand) { - return execute((BackupSnapshotCommand) cmd); - } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { - return execute((CreateVolumeFromSnapshotCommand) cmd); - } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { - return execute((CreatePrivateTemplateFromSnapshotCommand) cmd); - } else if (cmd instanceof UpgradeSnapshotCommand) { - return execute((UpgradeSnapshotCommand) cmd); - } else if (cmd instanceof CreateStoragePoolCommand) { - return execute((CreateStoragePoolCommand) cmd); - } else if (cmd instanceof ModifyStoragePoolCommand) { - return execute((ModifyStoragePoolCommand) cmd); - } else if (cmd instanceof SecurityGroupRulesCmd) { - return execute((SecurityGroupRulesCmd) cmd); - } else if (cmd instanceof DeleteStoragePoolCommand) { - return execute((DeleteStoragePoolCommand) cmd); - } else if (cmd instanceof FenceCommand) { - return execute((FenceCommand) cmd); - } else if (cmd instanceof StartCommand) { - return execute((StartCommand) cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand) cmd); - } else if (cmd instanceof NetworkElementCommand) { - return _virtRouterResource.executeRequest(cmd); - } else if (cmd instanceof CheckSshCommand) { - return execute((CheckSshCommand) cmd); - } else if (cmd instanceof NetworkUsageCommand) { - return execute((NetworkUsageCommand) cmd); - } else if (cmd instanceof NetworkRulesSystemVmCommand) { - return execute((NetworkRulesSystemVmCommand) cmd); - } else if (cmd instanceof CleanupNetworkRulesCmd) { - return execute((CleanupNetworkRulesCmd) cmd); - } else if (cmd instanceof CopyVolumeCommand) { - return execute((CopyVolumeCommand) cmd); - } else if (cmd instanceof CheckNetworkCommand) { - return execute((CheckNetworkCommand) cmd); - } else { - s_logger.warn("Unsupported command "); - return Answer.createUnsupportedCommandAnswer(cmd); - } - } catch (final IllegalArgumentException e) { - return new Answer(cmd, false, e.getMessage()); - } - } - - private CheckNetworkAnswer execute(CheckNetworkCommand cmd) { - List phyNics = cmd - .getPhysicalNetworkInfoList(); - String errMsg = null; - for (PhysicalNetworkSetupInfo nic : phyNics) { - if (!checkNetwork(nic.getGuestNetworkName())) { - errMsg = "Can not find network: " + nic.getGuestNetworkName(); - break; - } else if (!checkNetwork(nic.getPrivateNetworkName())) { - errMsg = "Can not find network: " + nic.getPrivateNetworkName(); - break; - } else if (!checkNetwork(nic.getPublicNetworkName())) { - errMsg = "Can not find network: " + nic.getPublicNetworkName(); - break; - } - } - - if (errMsg != null) { - return new CheckNetworkAnswer(cmd, false, errMsg); - } else { - return new CheckNetworkAnswer(cmd, true, null); - } - } - - private CopyVolumeAnswer execute(CopyVolumeCommand cmd) { - boolean copyToSecondary = cmd.toSecondaryStorage(); - String volumePath = cmd.getVolumePath(); - StorageFilerTO pool = cmd.getPool(); - String secondaryStorageUrl = cmd.getSecondaryStorageURL(); - KVMStoragePool secondaryStoragePool = null; - try { - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool - .getUuid()); - String volumeName = UUID.randomUUID().toString(); - - if (copyToSecondary) { - String destVolumeName = volumeName + ".qcow2"; - KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd - .getVolumePath()); - String volumeDestPath = "/volumes/" + cmd.getVolumeId() - + File.separator; - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl); - secondaryStoragePool.createFolder(volumeDestPath); - secondaryStoragePool.delete(); - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl - + volumeDestPath); - _storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, - secondaryStoragePool); - return new CopyVolumeAnswer(cmd, true, null, null, volumeName); - } else { - volumePath = "/volumes/" + cmd.getVolumeId() + File.separator; - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl + volumePath); - KVMPhysicalDisk volume = secondaryStoragePool - .getPhysicalDisk(cmd.getVolumePath() + ".qcow2"); - _storagePoolMgr.copyPhysicalDisk(volume, volumeName, - primaryPool); - return new CopyVolumeAnswer(cmd, true, null, null, volumeName); - } - } catch (CloudRuntimeException e) { - return new CopyVolumeAnswer(cmd, false, e.toString(), null, null); - } finally { - if (secondaryStoragePool != null) { - secondaryStoragePool.delete(); - } - } - } - - protected Answer execute(DeleteStoragePoolCommand cmd) { - try { - _storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid()); - return new Answer(cmd); - } catch (CloudRuntimeException e) { - return new Answer(cmd, false, e.toString()); - } - } - - protected FenceAnswer execute(FenceCommand cmd) { - ExecutorService executors = Executors.newSingleThreadExecutor(); - List pools = _monitor.getStoragePools(); - KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp()); - Future future = executors.submit(ha); - try { - Boolean result = future.get(); - if (result) { - return new FenceAnswer(cmd, false, "Heart is still beating..."); - } else { - return new FenceAnswer(cmd); - } - } catch (InterruptedException e) { - s_logger.warn("Unable to fence", e); - return new FenceAnswer(cmd, false, e.getMessage()); - } catch (ExecutionException e) { - s_logger.warn("Unable to fence", e); - return new FenceAnswer(cmd, false, e.getMessage()); - } - - } - - protected Storage.StorageResourceType getStorageResourceType() { - return Storage.StorageResourceType.STORAGE_POOL; - } - - protected Answer execute(CreateCommand cmd) { - StorageFilerTO pool = cmd.getPool(); - DiskProfile dskch = cmd.getDiskCharacteristics(); - KVMPhysicalDisk BaseVol = null; - KVMStoragePool primaryPool = null; - KVMPhysicalDisk vol = null; - long disksize; - try { - primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid()); - - if (cmd.getTemplateUrl() != null) { - - BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl()); - vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID - .randomUUID().toString(), primaryPool); - - if (vol == null) { - return new Answer(cmd, false, - " Can't create storage volume on storage pool"); - } - disksize = vol.getSize(); - } else { - disksize = dskch.getSize(); - vol = primaryPool.createPhysicalDisk(UUID.randomUUID() - .toString(), dskch.getSize()); - } - VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(), - pool.getType(), pool.getUuid(), pool.getPath(), - vol.getName(), vol.getName(), disksize, null); - return new CreateAnswer(cmd, volume); - } catch (CloudRuntimeException e) { - s_logger.debug("Failed to create volume: " + e.toString()); - return new CreateAnswer(cmd, e); - } - } - - public Answer execute(DestroyCommand cmd) { - VolumeTO vol = cmd.getVolume(); - - try { - KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol - .getPoolUuid()); - pool.deletePhysicalDisk(vol.getPath()); - - return new Answer(cmd, true, "Success"); - } catch (CloudRuntimeException e) { - s_logger.debug("Failed to delete volume: " + e.toString()); - return new Answer(cmd, false, e.toString()); - } - } - - private String getVlanIdFromBridge(String brName) { - OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser(); - final Script cmd = new Script("/bin/bash", s_logger); - cmd.add("-c"); - cmd.add("vlanid=$(brctl show |grep " + brName - + " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid"); - String result = cmd.execute(vlanIdParser); - if (result != null) { - return null; - } - String vlanId = vlanIdParser.getLine(); - if (vlanId.equalsIgnoreCase("")) { - return null; - } else { - return vlanId; - } - } - - private void VifHotPlug(Connect conn, String vmName, String vlanId, - String macAddr) throws InternalErrorException, LibvirtException { - NicTO nicTO = new NicTO(); - nicTO.setMac(macAddr); - nicTO.setType(TrafficType.Public); - if (vlanId == null) { - nicTO.setBroadcastType(BroadcastDomainType.Native); - } else { - nicTO.setBroadcastType(BroadcastDomainType.Vlan); - nicTO.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanId)); - } - - InterfaceDef nic = createVif(conn, nicTO, InterfaceDef.nicModel.VIRTIO); - Domain vm = getDomain(conn, vmName); - vm.attachDevice(nic.toString()); - } - - public Answer execute(IpAssocCommand cmd) { - String routerName = cmd - .getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String[] results = new String[cmd.getIpAddresses().length]; - Connect conn; - try { - conn = LibvirtConnection.getConnection(); - List nics = getInterfaces(conn, routerName); - Map vlanAllocatedToVM = new HashMap(); - Integer nicPos = 0; - for (InterfaceDef nic : nics) { - if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) { - vlanAllocatedToVM.put("LinkLocal", nicPos); - } else { - String vlanId = getVlanIdFromBridge(nic.getBrName()); - if (vlanId != null) { - vlanAllocatedToVM.put(vlanId, nicPos); - } else { - vlanAllocatedToVM.put(Vlan.UNTAGGED, nicPos); - } - } - nicPos++; - } - IpAddressTO[] ips = cmd.getIpAddresses(); - int i = 0; - String result = null; - int nicNum = 0; - for (IpAddressTO ip : ips) { - if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) { - /* plug a vif into router */ - VifHotPlug(conn, routerName, ip.getVlanId(), - ip.getVifMacAddress()); - vlanAllocatedToVM.put(ip.getVlanId(), nicPos++); - } - nicNum = vlanAllocatedToVM.get(ip.getVlanId()); - networkUsage(routerIp, "addVif", "eth" + nicNum); - result = _virtRouterResource.assignPublicIpAddress(routerName, - routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), - ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), - ip.getVlanNetmask(), ip.getVifMacAddress(), - ip.getGuestIp(), nicNum); - - if (result != null) { - results[i++] = IpAssocAnswer.errorResult; - } else { - results[i++] = ip.getPublicIp() + " - success"; - ; - } - } - return new IpAssocAnswer(cmd, results); - } catch (LibvirtException e) { - return new IpAssocAnswer(cmd, results); - } catch (InternalErrorException e) { - return new IpAssocAnswer(cmd, results); - } - } - - protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { - String snapshotName = cmd.getSnapshotName(); - String snapshotPath = cmd.getSnapshotPath(); - String vmName = cmd.getVmName(); - try { - Connect conn = LibvirtConnection.getConnection(); - DomainInfo.DomainState state = null; - Domain vm = null; - if (vmName != null) { - try { - vm = getDomain(conn, cmd.getVmName()); - state = vm.getInfo().state; - } catch (LibvirtException e) { - - } - } - - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPool().getUuid()); - KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd - .getVolumePath()); - if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING - && !primaryPool.isExternalSnapshot()) { - String vmUuid = vm.getUUIDString(); - Object[] args = new Object[] { snapshotName, vmUuid }; - String snapshot = SnapshotXML.format(args); - s_logger.debug(snapshot); - if (cmd.getCommandSwitch().equalsIgnoreCase( - ManageSnapshotCommand.CREATE_SNAPSHOT)) { - vm.snapshotCreateXML(snapshot); - } else { - DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); - snap.delete(0); - } - - /* - * libvirt on RHEL6 doesn't handle resume event emitted from - * qemu - */ - vm = getDomain(conn, cmd.getVmName()); - state = vm.getInfo().state; - if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { - vm.resume(); - } - } else { - - /* VM is not running, create a snapshot by ourself */ - final Script command = new Script(_manageSnapshotPath, - _cmdsTimeout, s_logger); - if (cmd.getCommandSwitch().equalsIgnoreCase( - ManageSnapshotCommand.CREATE_SNAPSHOT)) { - command.add("-c", disk.getPath()); - } else { - command.add("-d", snapshotPath); - } - - command.add("-n", snapshotName); - String result = command.execute(); - if (result != null) { - s_logger.debug("Failed to manage snapshot: " + result); - return new ManageSnapshotAnswer(cmd, false, - "Failed to manage snapshot: " + result); - } - } - return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(), - disk.getPath() + File.separator + snapshotName, true, null); - } catch (LibvirtException e) { - s_logger.debug("Failed to manage snapshot: " + e.toString()); - return new ManageSnapshotAnswer(cmd, false, - "Failed to manage snapshot: " + e.toString()); - } - - } - - protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) { - Long dcId = cmd.getDataCenterId(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl(); - String snapshotName = cmd.getSnapshotName(); - String snapshotPath = cmd.getVolumePath(); - String snapshotDestPath = null; - String snapshotRelPath = null; - String vmName = cmd.getVmName(); - KVMStoragePool secondaryStoragePool = null; - try { - Connect conn = LibvirtConnection.getConnection(); - - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStoragePoolUrl); - - String ssPmountPath = secondaryStoragePool.getLocalPath(); - snapshotRelPath = File.separator + "snapshots" + File.separator - + dcId + File.separator + accountId + File.separator - + volumeId; - - snapshotDestPath = ssPmountPath + File.separator + "snapshots" - + File.separator + dcId + File.separator + accountId - + File.separator + volumeId; - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPrimaryStoragePoolNameLabel()); - KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd - .getVolumePath()); - Script command = new Script(_manageSnapshotPath, _cmdsTimeout, - s_logger); - command.add("-b", snapshotDisk.getPath()); - command.add("-n", snapshotName); - command.add("-p", snapshotDestPath); - command.add("-t", snapshotName); - String result = command.execute(); - if (result != null) { - s_logger.debug("Failed to backup snaptshot: " + result); - return new BackupSnapshotAnswer(cmd, false, result, null, true); - } - /* Delete the snapshot on primary */ - - DomainInfo.DomainState state = null; - Domain vm = null; - if (vmName != null) { - try { - vm = getDomain(conn, cmd.getVmName()); - state = vm.getInfo().state; - } catch (LibvirtException e) { - - } - } - - KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd - .getPool().getUuid()); - if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING - && !primaryStorage.isExternalSnapshot()) { - String vmUuid = vm.getUUIDString(); - Object[] args = new Object[] { snapshotName, vmUuid }; - String snapshot = SnapshotXML.format(args); - s_logger.debug(snapshot); - DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); - snap.delete(0); - - /* - * libvirt on RHEL6 doesn't handle resume event emitted from - * qemu - */ - vm = getDomain(conn, cmd.getVmName()); - state = vm.getInfo().state; - if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { - vm.resume(); - } - } else { - command = new Script(_manageSnapshotPath, _cmdsTimeout, - s_logger); - command.add("-d", snapshotDisk.getPath()); - command.add("-n", snapshotName); - result = command.execute(); - if (result != null) { - s_logger.debug("Failed to backup snapshot: " + result); - return new BackupSnapshotAnswer(cmd, false, - "Failed to backup snapshot: " + result, null, true); - } - } - } catch (LibvirtException e) { - return new BackupSnapshotAnswer(cmd, false, e.toString(), null, - true); - } catch (CloudRuntimeException e) { - return new BackupSnapshotAnswer(cmd, false, e.toString(), null, - true); - } finally { - if (secondaryStoragePool != null) { - secondaryStoragePool.delete(); - } - } - return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath - + File.separator + snapshotName, true); - } - - protected DeleteSnapshotBackupAnswer execute( - final DeleteSnapshotBackupCommand cmd) { - Long dcId = cmd.getDataCenterId(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - KVMStoragePool secondaryStoragePool = null; - try { - secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl()); - - String ssPmountPath = secondaryStoragePool.getLocalPath(); - String snapshotDestPath = ssPmountPath + File.separator - + "snapshots" + File.separator + dcId + File.separator - + accountId + File.separator + volumeId; - - final Script command = new Script(_manageSnapshotPath, - _cmdsTimeout, s_logger); - command.add("-d", snapshotDestPath); - command.add("-n", cmd.getSnapshotName()); - - command.execute(); - } catch (CloudRuntimeException e) { - return new DeleteSnapshotBackupAnswer(cmd, false, e.toString()); - } finally { - if (secondaryStoragePool != null) { - secondaryStoragePool.delete(); - } - } - return new DeleteSnapshotBackupAnswer(cmd, true, null); - } - - protected Answer execute(DeleteSnapshotsDirCommand cmd) { - Long dcId = cmd.getDcId(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - KVMStoragePool secondaryStoragePool = null; - try { - secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl()); - - String ssPmountPath = secondaryStoragePool.getLocalPath(); - String snapshotDestPath = ssPmountPath + File.separator - + "snapshots" + File.separator + dcId + File.separator - + accountId + File.separator + volumeId; - - final Script command = new Script(_manageSnapshotPath, - _cmdsTimeout, s_logger); - command.add("-d", snapshotDestPath); - command.add("-f"); - command.execute(); - } catch (CloudRuntimeException e) { - return new Answer(cmd, false, e.toString()); - } finally { - if (secondaryStoragePool != null) { - secondaryStoragePool.delete(); - } - - } - return new Answer(cmd, true, null); - } - - protected CreateVolumeFromSnapshotAnswer execute( - final CreateVolumeFromSnapshotCommand cmd) { - try { - - String snapshotPath = cmd.getSnapshotUuid(); - int index = snapshotPath.lastIndexOf("/"); - snapshotPath = snapshotPath.substring(0, index); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(cmd.getSecondaryStorageUrl() - + snapshotPath); - KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd - .getSnapshotName()); - - String primaryUuid = cmd.getPrimaryStoragePoolNameLabel(); - KVMStoragePool primaryPool = _storagePoolMgr - .getStoragePool(primaryUuid); - String volUuid = UUID.randomUUID().toString(); - KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot, - volUuid, primaryPool); - return new CreateVolumeFromSnapshotAnswer(cmd, true, "", - disk.getName()); - } catch (CloudRuntimeException e) { - return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(), - null); - } - } - - protected Answer execute(final UpgradeSnapshotCommand cmd) { - - return new Answer(cmd, true, "success"); - } - - protected CreatePrivateTemplateAnswer execute( - final CreatePrivateTemplateFromSnapshotCommand cmd) { - String templateFolder = cmd.getAccountId() + File.separator - + cmd.getNewTemplateId(); - String templateInstallFolder = "template/tmpl/" + templateFolder; - String tmplName = UUID.randomUUID().toString(); - String tmplFileName = tmplName + ".qcow2"; - KVMStoragePool secondaryPool = null; - KVMStoragePool snapshotPool = null; - try { - String snapshotPath = cmd.getSnapshotUuid(); - int index = snapshotPath.lastIndexOf("/"); - snapshotPath = snapshotPath.substring(0, index); - snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl() + snapshotPath); - KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd - .getSnapshotName()); - - secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl()); - - String templatePath = secondaryPool.getLocalPath() + File.separator - + templateInstallFolder; - - _storage.mkdirs(templatePath); - - String tmplPath = templateInstallFolder + File.separator - + tmplFileName; - Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger); - command.add("-t", templatePath); - command.add("-n", tmplFileName); - command.add("-f", snapshot.getPath()); - command.execute(); - - Map params = new HashMap(); - params.put(StorageLayer.InstanceConfigKey, _storage); - Processor qcow2Processor = new QCOW2Processor(); - qcow2Processor.configure("QCOW2 Processor", params); - FormatInfo info = qcow2Processor.process(templatePath, null, - tmplName); - - TemplateLocation loc = new TemplateLocation(_storage, templatePath); - loc.create(1, true, tmplName); - loc.addFormat(info); - loc.save(); - - return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath, - info.virtualSize, info.size, tmplName, info.format); - } catch (ConfigurationException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } catch (InternalErrorException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } catch (IOException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } catch (CloudRuntimeException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } finally { - if (secondaryPool != null) { - secondaryPool.delete(); - } - if (snapshotPool != null) { - snapshotPool.delete(); - } - } - } - - protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { - try { - KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd - .getStorageId()); - return new GetStorageStatsAnswer(cmd, sp.getCapacity(), - sp.getUsed()); - } catch (CloudRuntimeException e) { - return new GetStorageStatsAnswer(cmd, e.toString()); - } - } - - protected CreatePrivateTemplateAnswer execute( - CreatePrivateTemplateFromVolumeCommand cmd) { - String secondaryStorageURL = cmd.getSecondaryStorageUrl(); - - KVMStoragePool secondaryStorage = null; - try { - Connect conn = LibvirtConnection.getConnection(); - String templateFolder = cmd.getAccountId() + File.separator - + cmd.getTemplateId() + File.separator; - String templateInstallFolder = "/template/tmpl/" + templateFolder; - - secondaryStorage = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageURL); - - KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd - .getPrimaryStoragePoolNameLabel()); - KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); - String tmpltPath = secondaryStorage.getLocalPath() + File.separator - + templateInstallFolder; - _storage.mkdirs(tmpltPath); - - Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger); - command.add("-f", disk.getPath()); - command.add("-t", tmpltPath); - command.add("-n", cmd.getUniqueName() + ".qcow2"); - - String result = command.execute(); - - if (result != null) { - s_logger.debug("failed to create template: " + result); - return new CreatePrivateTemplateAnswer(cmd, false, result); - } - - Map params = new HashMap(); - params.put(StorageLayer.InstanceConfigKey, _storage); - Processor qcow2Processor = new QCOW2Processor(); - - qcow2Processor.configure("QCOW2 Processor", params); - - FormatInfo info = qcow2Processor.process(tmpltPath, null, - cmd.getUniqueName()); - - TemplateLocation loc = new TemplateLocation(_storage, tmpltPath); - loc.create(1, true, cmd.getUniqueName()); - loc.addFormat(info); - loc.save(); - - return new CreatePrivateTemplateAnswer(cmd, true, null, - templateInstallFolder + cmd.getUniqueName() + ".qcow2", - info.virtualSize, info.size, cmd.getUniqueName(), - ImageFormat.QCOW2); - } catch (LibvirtException e) { - s_logger.debug("Failed to get secondary storage pool: " - + e.toString()); - return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); - } catch (InternalErrorException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); - } catch (IOException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); - } catch (ConfigurationException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); - } catch (CloudRuntimeException e) { - return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); - } finally { - if (secondaryStorage != null) { - secondaryStorage.delete(); - } - } - } - - protected PrimaryStorageDownloadAnswer execute( - final PrimaryStorageDownloadCommand cmd) { - String tmplturl = cmd.getUrl(); - int index = tmplturl.lastIndexOf("/"); - String mountpoint = tmplturl.substring(0, index); - String tmpltname = null; - if (index < tmplturl.length() - 1) { - tmpltname = tmplturl.substring(index + 1); - } - - KVMPhysicalDisk tmplVol = null; - KVMStoragePool secondaryPool = null; - try { - secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint); - - /* Get template vol */ - if (tmpltname == null) { - secondaryPool.refresh(); - List disks = secondaryPool.listPhysicalDisks(); - if (disks == null || disks.isEmpty()) { - return new PrimaryStorageDownloadAnswer( - "Failed to get volumes from pool: " - + secondaryPool.getUuid()); - } - for (KVMPhysicalDisk disk : disks) { - if (disk.getName().endsWith("qcow2")) { - tmplVol = disk; - break; - } - } - if (tmplVol == null) { - return new PrimaryStorageDownloadAnswer( - "Failed to get template from pool: " - + secondaryPool.getUuid()); - } - } else { - tmplVol = secondaryPool.getPhysicalDisk(tmpltname); - } - - /* Copy volume to primary storage */ - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPoolUuid()); - - KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk( - tmplVol, UUID.randomUUID().toString(), primaryPool); - - return new PrimaryStorageDownloadAnswer(primaryVol.getName(), - primaryVol.getSize()); - } catch (CloudRuntimeException e) { - return new PrimaryStorageDownloadAnswer(e.toString()); - } finally { - if (secondaryPool != null) { - secondaryPool.delete(); - } - } - } - - protected Answer execute(CreateStoragePoolCommand cmd) { - return new Answer(cmd, true, "success"); - } - - protected Answer execute(ModifyStoragePoolCommand cmd) { - KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd - .getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool() - .getPath(), cmd.getPool().getType()); - if (storagepool == null) { - return new Answer(cmd, false, " Failed to create storage pool"); - } - - Map tInfo = new HashMap(); - ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, - storagepool.getCapacity(), storagepool.getUsed(), tInfo); - - return answer; - } - - private Answer execute(SecurityGroupRulesCmd cmd) { - String vif = null; - String brname = null; - try { - Connect conn = LibvirtConnection.getConnection(); - List nics = getInterfaces(conn, cmd.getVmName()); - vif = nics.get(0).getDevName(); - brname = nics.get(0).getBrName(); - } catch (LibvirtException e) { - return new SecurityGroupRuleAnswer(cmd, false, e.toString()); - } - - boolean result = add_network_rules(cmd.getVmName(), - Long.toString(cmd.getVmId()), cmd.getGuestIp(), - cmd.getSignature(), Long.toString(cmd.getSeqNum()), - cmd.getGuestMac(), cmd.stringifyRules(), vif, brname); - - if (!result) { - s_logger.warn("Failed to program network rules for vm " - + cmd.getVmName()); - return new SecurityGroupRuleAnswer(cmd, false, - "programming network rules failed"); - } else { - s_logger.debug("Programmed network rules for vm " + cmd.getVmName() - + " guestIp=" + cmd.getGuestIp() + ",ingress numrules=" - + cmd.getIngressRuleSet().length + ",egress numrules=" - + cmd.getEgressRuleSet().length); - return new SecurityGroupRuleAnswer(cmd); - } - } - - private Answer execute(CleanupNetworkRulesCmd cmd) { - boolean result = cleanup_rules(); - return new Answer(cmd, result, ""); - } - - protected GetVncPortAnswer execute(GetVncPortCommand cmd) { - try { - Connect conn = LibvirtConnection.getConnection(); - Integer vncPort = getVncPort(conn, cmd.getName()); - return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort); - } catch (Exception e) { - return new GetVncPortAnswer(cmd, e.toString()); - } - } - - protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), - cmd.getProxyVmName(), cmd.getProxyManagementIp(), - cmd.getProxyCmdPort()); - } - - protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), - cmd.getProxyVmName(), cmd.getProxyManagementIp(), - cmd.getProxyCmdPort()); - } - - protected MaintainAnswer execute(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private Answer executeProxyLoadScan(final Command cmd, - final long proxyVmId, final String proxyVmName, - final String proxyManagementIp, final int cmdPort) { - String result = null; - - final StringBuffer sb = new StringBuffer(); - sb.append("http://").append(proxyManagementIp).append(":" + cmdPort) - .append("/cmd/getstatus"); - - boolean success = true; - try { - final URL url = new URL(sb.toString()); - final URLConnection conn = url.openConnection(); - - final InputStream is = conn.getInputStream(); - final BufferedReader reader = new BufferedReader( - new InputStreamReader(is)); - final StringBuilder sb2 = new StringBuilder(); - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb2.append(line + "\n"); - } - result = sb2.toString(); - } catch (final IOException e) { - success = false; - } finally { - try { - is.close(); - } catch (final IOException e) { - s_logger.warn("Exception when closing , console proxy address : " - + proxyManagementIp); - success = false; - } - } - } catch (final IOException e) { - s_logger.warn("Unable to open console proxy command port url, console proxy address : " - + proxyManagementIp); - success = false; - } - - return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, - result); - } - - private Answer execute(AttachIsoCommand cmd) { - try { - Connect conn = LibvirtConnection.getConnection(); - attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(), - cmd.isAttach()); - } catch (LibvirtException e) { - return new Answer(cmd, false, e.toString()); - } catch (URISyntaxException e) { - return new Answer(cmd, false, e.toString()); - } catch (InternalErrorException e) { - return new Answer(cmd, false, e.toString()); - } - - return new Answer(cmd); - } - - private AttachVolumeAnswer execute(AttachVolumeCommand cmd) { - try { - Connect conn = LibvirtConnection.getConnection(); - KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd - .getPoolUuid()); - KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); - attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk, - cmd.getDeviceId().intValue()); - } catch (LibvirtException e) { - return new AttachVolumeAnswer(cmd, e.toString()); - } catch (InternalErrorException e) { - return new AttachVolumeAnswer(cmd, e.toString()); - } - - return new AttachVolumeAnswer(cmd, cmd.getDeviceId()); - } - - private Answer execute(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - protected State convertToState(DomainInfo.DomainState ps) { - final State state = s_statesTable.get(ps); - return state == null ? State.Unknown : state; - } - - protected State getVmState(Connect conn, final String vmName) { - int retry = 3; - Domain vms = null; - while (retry-- > 0) { - try { - vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - State s = convertToState(vms.getInfo().state); - return s; - } catch (final LibvirtException e) { - s_logger.warn("Can't get vm state " + vmName + e.getMessage() - + "retry:" + retry); - } catch (Exception e) { - s_logger.warn("Can't get vm state " + vmName + e.getMessage() - + "retry:" + retry); - } finally { - try { - if (vms != null) { - vms.free(); - } - } catch (final LibvirtException e) { - - } - } - } - return State.Stopped; - } - - private Answer execute(CheckVirtualMachineCommand cmd) { - try { - Connect conn = LibvirtConnection.getConnection(); - final State state = getVmState(conn, cmd.getVmName()); - Integer vncPort = null; - if (state == State.Running) { - vncPort = getVncPort(conn, cmd.getVmName()); - - synchronized (_vms) { - _vms.put(cmd.getVmName(), State.Running); - } - } - - return new CheckVirtualMachineAnswer(cmd, state, vncPort); - } catch (LibvirtException e) { - return new CheckVirtualMachineAnswer(cmd, e.getMessage()); - } - } - - private Answer execute(PingTestCommand cmd) { - String result = null; - final String computingHostIp = cmd.getComputingHostIp(); // TODO, split - // the - // command - // into 2 - // types - - if (computingHostIp != null) { - result = doPingTest(computingHostIp); - } else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) { - result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp()); - } else { - return new Answer(cmd, false, "routerip and private ip is null"); - } - - if (result != null) { - return new Answer(cmd, false, result); - } - return new Answer(cmd); - } - - private String doPingTest(final String computingHostIp) { - final Script command = new Script(_pingTestPath, 10000, s_logger); - command.add("-h", computingHostIp); - return command.execute(); - } - - private String doPingTest(final String domRIp, final String vmIp) { - final Script command = new Script(_pingTestPath, 10000, s_logger); - command.add("-i", domRIp); - command.add("-p", vmIp); - return command.execute(); - } - - private synchronized Answer execute(MigrateCommand cmd) { - String vmName = cmd.getVmName(); - - State state = null; - String result = null; - synchronized (_vms) { - state = _vms.get(vmName); - _vms.put(vmName, State.Stopping); - } - - Domain dm = null; - Connect dconn = null; - Domain destDomain = null; - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp() - + "/system"); - /* - * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and - * VIR_MIGRATE_PERSIST_DEST(1<<3) - */ - destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:" - + cmd.getDestinationIp(), _migrateSpeed); - } catch (LibvirtException e) { - s_logger.debug("Can't migrate domain: " + e.getMessage()); - result = e.getMessage(); - } catch (Exception e) { - s_logger.debug("Can't migrate domain: " + e.getMessage()); - result = e.getMessage(); - } finally { - try { - if (dm != null) { - dm.free(); - } - if (dconn != null) { - dconn.close(); - } - if (destDomain != null) { - destDomain.free(); - } - } catch (final LibvirtException e) { - - } - } - - if (result != null) { - synchronized (_vms) { - _vms.put(vmName, state); - } - } else { - destroy_network_rules_for_vm(conn, vmName); - cleanupVM(conn, vmName, - getVnetId(VirtualMachineName.getVnet(vmName))); - } - - return new MigrateAnswer(cmd, result == null, result, null); - } - - private synchronized Answer execute(PrepareForMigrationCommand cmd) { - - VirtualMachineTO vm = cmd.getVirtualMachine(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Preparing host for migrating " + vm); - } - - NicTO[] nics = vm.getNics(); - try { - Connect conn = LibvirtConnection.getConnection(); - for (NicTO nic : nics) { - String vlanId = null; - if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { - URI broadcastUri = nic.getBroadcastUri(); - vlanId = broadcastUri.getHost(); - } - if (nic.getType() == TrafficType.Guest) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan - && !vlanId.equalsIgnoreCase("untagged")) { - createVlanBr(vlanId, _pifs.first()); - } - } else if (nic.getType() == TrafficType.Control) { - /* Make sure the network is still there */ - createControlNetwork(conn); - } else if (nic.getType() == TrafficType.Public) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan - && !vlanId.equalsIgnoreCase("untagged")) { - createVlanBr(vlanId, _pifs.second()); - } - } - } - - /* setup disks, e.g for iso */ - VolumeTO[] volumes = vm.getDisks(); - for (VolumeTO volume : volumes) { - if (volume.getType() == Volume.Type.ISO) { - getVolumePath(conn, volume); - } - } - - synchronized (_vms) { - _vms.put(vm.getName(), State.Migrating); - } - - return new PrepareForMigrationAnswer(cmd); - } catch (LibvirtException e) { - return new PrepareForMigrationAnswer(cmd, e.toString()); - } catch (InternalErrorException e) { - return new PrepareForMigrationAnswer(cmd, e.toString()); - } catch (URISyntaxException e) { - return new PrepareForMigrationAnswer(cmd, e.toString()); - } - } - - public void createVnet(String vnetId, String pif) - throws InternalErrorException { - final Script command = new Script(_modifyVlanPath, _timeout, s_logger); - command.add("-v", vnetId); - command.add("-p", pif); - command.add("-o", "add"); - - final String result = command.execute(); - if (result != null) { - throw new InternalErrorException("Failed to create vnet " + vnetId - + ": " + result); - } - } - - private Answer execute(CheckHealthCommand cmd) { - return new CheckHealthAnswer(cmd, true); - } - - private Answer execute(GetHostStatsCommand cmd) { - final Script cpuScript = new Script("/bin/bash", s_logger); - cpuScript.add("-c"); - cpuScript - .add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle"); - - final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - String result = cpuScript.execute(parser); - if (result != null) { - s_logger.debug("Unable to get the host CPU state: " + result); - return new Answer(cmd, false, result); - } - double cpuUtil = (100.0D - Double.parseDouble(parser.getLine())); - - long freeMem = 0; - final Script memScript = new Script("/bin/bash", s_logger); - memScript.add("-c"); - memScript - .add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem"); - final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser(); - result = memScript.execute(Memparser); - if (result != null) { - s_logger.debug("Unable to get the host Mem state: " + result); - return new Answer(cmd, false, result); - } - freeMem = Long.parseLong(Memparser.getLine()); - - Script totalMem = new Script("/bin/bash", s_logger); - totalMem.add("-c"); - totalMem.add("free|grep Mem:|awk '{print $2}'"); - final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser(); - result = totalMem.execute(totMemparser); - if (result != null) { - s_logger.debug("Unable to get the host Mem state: " + result); - return new Answer(cmd, false, result); - } - long totMem = Long.parseLong(totMemparser.getLine()); - - Pair nicStats = getNicStats(_publicBridgeName); - - HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil, - nicStats.first() / 1000, nicStats.second() / 1000, "host", - totMem, freeMem, 0, 0); - return new GetHostStatsAnswer(cmd, hostStats); - } - - protected String networkUsage(final String privateIpAddress, - final String option, final String vif) { - Script getUsage = new Script(_networkUsagePath, s_logger); - if (option.equals("get")) { - getUsage.add("-g"); - } else if (option.equals("create")) { - getUsage.add("-c"); - } else if (option.equals("reset")) { - getUsage.add("-r"); - } else if (option.equals("addVif")) { - getUsage.add("-a", vif); - } else if (option.equals("deleteVif")) { - getUsage.add("-d", vif); - } - - getUsage.add("-i", privateIpAddress); - final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); - String result = getUsage.execute(usageParser); - if (result != null) { - s_logger.debug("Failed to execute networkUsage:" + result); - return null; - } - return usageParser.getLine(); - } - - protected long[] getNetworkStats(String privateIP) { - String result = networkUsage(privateIP, "get", null); - long[] stats = new long[2]; - if (result != null) { - String[] splitResult = result.split(":"); - int i = 0; - while (i < splitResult.length - 1) { - stats[0] += (new Long(splitResult[i++])).longValue(); - stats[1] += (new Long(splitResult[i++])).longValue(); - } - } - return stats; - } - - private Answer execute(NetworkUsageCommand cmd) { - if (cmd.getOption() != null && cmd.getOption().equals("create")) { - String result = networkUsage(cmd.getPrivateIP(), "create", null); - NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, - 0L); - return answer; - } - long[] stats = getNetworkStats(cmd.getPrivateIP()); - NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], - stats[1]); - return answer; - } - - private Answer execute(RebootCommand cmd) { - Long bytesReceived = null; - Long bytesSent = null; - - synchronized (_vms) { - _vms.put(cmd.getVmName(), State.Starting); - } - - try { - Connect conn = LibvirtConnection.getConnection(); - final String result = rebootVM(conn, cmd.getVmName()); - if (result == null) { - Integer vncPort = null; - try { - vncPort = getVncPort(conn, cmd.getVmName()); - } catch (Exception e) { - - } - get_rule_logs_for_vms(); - return new RebootAnswer(cmd, null, bytesSent, bytesReceived, - vncPort); - } else { - return new RebootAnswer(cmd, result); - } - } catch (LibvirtException e) { - return new RebootAnswer(cmd, e.getMessage()); - } finally { - synchronized (_vms) { - _vms.put(cmd.getVmName(), State.Running); - } - } - } - - protected Answer execute(RebootRouterCommand cmd) { - Long bytesSent = 0L; - Long bytesRcvd = 0L; - if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { - long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); - bytesSent = stats[0]; - bytesRcvd = stats[1]; - } - RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); - answer.setBytesSent(bytesSent); - answer.setBytesReceived(bytesRcvd); - String result = _virtRouterResource.connect(cmd.getPrivateIpAddress()); - if (result == null) { - networkUsage(cmd.getPrivateIpAddress(), "create", null); - return answer; - } else { - return new Answer(cmd, false, result); - } - } - - protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { - List vmNames = cmd.getVmNames(); - try { - HashMap vmStatsNameMap = new HashMap(); - Connect conn = LibvirtConnection.getConnection(); - for (String vmName : vmNames) { - VmStatsEntry statEntry = getVmStat(conn, vmName); - if (statEntry == null) { - continue; - } - - vmStatsNameMap.put(vmName, statEntry); - } - return new GetVmStatsAnswer(cmd, vmStatsNameMap); - } catch (LibvirtException e) { - s_logger.debug("Can't get vm stats: " + e.toString()); - return new GetVmStatsAnswer(cmd, null); - } - } - - protected Answer execute(StopCommand cmd) { - final String vmName = cmd.getVmName(); - - Long bytesReceived = new Long(0); - Long bytesSent = new Long(0); - - State state = null; - synchronized (_vms) { - state = _vms.get(vmName); - _vms.put(vmName, State.Stopping); - } - try { - Connect conn = LibvirtConnection.getConnection(); - - List disks = getDisks(conn, vmName); - destroy_network_rules_for_vm(conn, vmName); - String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM); - if (result == null) { - for (DiskDef disk : disks) { - if (disk.getDeviceType() == DiskDef.deviceType.CDROM - && disk.getDiskPath() != null) - cleanupDisk(conn, disk); - } - } - - final String result2 = cleanupVnet(conn, cmd.getVnet()); - - if (result != null && result2 != null) { - result = result2 + result; - } - state = State.Stopped; - return new StopAnswer(cmd, result, 0, bytesSent, bytesReceived); - } catch (LibvirtException e) { - return new StopAnswer(cmd, e.getMessage()); - } finally { - synchronized (_vms) { - if (state != null) { - _vms.put(vmName, state); - } else { - _vms.remove(vmName); - } - } - } - } - - protected Answer execute(ModifySshKeysCommand cmd) { - File sshKeysDir = new File(_SSHKEYSPATH); - String result = null; - if (!sshKeysDir.exists()) { - sshKeysDir.mkdir(); - // Change permissions for the 600 - Script script = new Script("chmod", _timeout, s_logger); - script.add("600", _SSHKEYSPATH); - script.execute(); - } - - File pubKeyFile = new File(_SSHPUBKEYPATH); - if (!pubKeyFile.exists()) { - try { - pubKeyFile.createNewFile(); - } catch (IOException e) { - result = "Failed to create file: " + e.toString(); - s_logger.debug(result); - } - } - - if (pubKeyFile.exists()) { - String pubKey = cmd.getPubKey(); - try { - FileOutputStream pubkStream = new FileOutputStream(pubKeyFile); - pubkStream.write(pubKey.getBytes()); - pubkStream.close(); - } catch (FileNotFoundException e) { - result = "File" + _SSHPUBKEYPATH + "is not found:" - + e.toString(); - s_logger.debug(result); - } catch (IOException e) { - result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString(); - s_logger.debug(result); - } - } - - File prvKeyFile = new File(_SSHPRVKEYPATH); - if (!prvKeyFile.exists()) { - try { - prvKeyFile.createNewFile(); - } catch (IOException e) { - result = "Failed to create file: " + e.toString(); - s_logger.debug(result); - } - } - - if (prvKeyFile.exists()) { - String prvKey = cmd.getPrvKey(); - try { - FileOutputStream prvKStream = new FileOutputStream(prvKeyFile); - prvKStream.write(prvKey.getBytes()); - prvKStream.close(); - } catch (FileNotFoundException e) { - result = "File" + _SSHPRVKEYPATH + "is not found:" - + e.toString(); - s_logger.debug(result); - } catch (IOException e) { - result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString(); - s_logger.debug(result); - } - - Script script = new Script("chmod", _timeout, s_logger); - script.add("600", _SSHPRVKEYPATH); - script.execute(); - } - - if (result != null) { - return new Answer(cmd, false, result); - } else { - return new Answer(cmd, true, null); - } - } - - protected void handleVmStartFailure(Connect conn, String vmName, - LibvirtVMDef vm) { - if (vm != null && vm.getDevices() != null) { - cleanupVMNetworks(conn, vm.getDevices().getInterfaces()); - } - } - - protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) { - LibvirtVMDef vm = new LibvirtVMDef(); - vm.setHvsType(_hypervisorType); - vm.setDomainName(vmTO.getName()); - vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes()) - .toString()); - vm.setDomDescription(vmTO.getOs()); - - GuestDef guest = new GuestDef(); - guest.setGuestType(GuestDef.guestType.KVM); - guest.setGuestArch(vmTO.getArch()); - guest.setMachineType("pc"); - guest.setBootOrder(GuestDef.bootOrder.CDROM); - guest.setBootOrder(GuestDef.bootOrder.HARDISK); - - vm.addComp(guest); - - GuestResourceDef grd = new GuestResourceDef(); - grd.setMemorySize(vmTO.getMinRam() / 1024); - grd.setVcpuNum(vmTO.getCpus()); - vm.addComp(grd); - - FeaturesDef features = new FeaturesDef(); - features.addFeatures("pae"); - features.addFeatures("apic"); - features.addFeatures("acpi"); - vm.addComp(features); - - TermPolicy term = new TermPolicy(); - term.setCrashPolicy("destroy"); - term.setPowerOffPolicy("destroy"); - term.setRebootPolicy("restart"); - vm.addComp(term); - - ClockDef clock = new ClockDef(); - if (vmTO.getOs().startsWith("Windows")) { - clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME); - clock.setTimer("rtc", "catchup", null); - } - - vm.addComp(clock); - - DevicesDef devices = new DevicesDef(); - devices.setEmulatorPath(_hypervisorPath); - - SerialDef serial = new SerialDef("pty", null, (short) 0); - devices.addDevice(serial); - - ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0); - devices.addDevice(console); - - GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null, - null); - devices.addDevice(grap); - - InputDef input = new InputDef("tablet", "usb"); - devices.addDevice(input); - - vm.addComp(devices); - - return vm; - } - - protected void createVifs(Connect conn, VirtualMachineTO vmSpec, - LibvirtVMDef vm) throws InternalErrorException, LibvirtException { - NicTO[] nics = vmSpec.getNics(); - for (int i = 0; i < nics.length; i++) { - for (NicTO nic : vmSpec.getNics()) { - if (nic.getDeviceId() == i) { - createVif(conn, vm, nic); - } - } - } - } - - protected synchronized StartAnswer execute(StartCommand cmd) { - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + ServerResource { + private static final Logger s_logger = Logger + .getLogger(LibvirtComputingResource.class); + + private String _modifyVlanPath; + private String _versionstringpath; + private String _patchdomrPath; + private String _createvmPath; + private String _manageSnapshotPath; + private String _createTmplPath; + private String _heartBeatPath; + private String _securityGroupPath; + private String _networkUsagePath; + private String _host; + private String _dcId; + private String _pod; + private String _clusterId; + private int _migrateSpeed; + + private long _hvVersion; + private KVMHAMonitor _monitor; + private final String _SSHKEYSPATH = "/root/.ssh"; + private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator + + "id_rsa.cloud"; + private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator + + "id_rsa.pub.cloud"; + private String _mountPoint = "/mnt"; + StorageLayer _storage; + private KVMStoragePoolManager _storagePoolMgr; + + private static final class KeyValueInterpreter extends OutputInterpreter { + private final Map map = new HashMap(); + + @Override + public String interpret(BufferedReader reader) throws IOException { + String line = null; + int numLines = 0; + while ((line = reader.readLine()) != null) { + String[] toks = line.trim().split("="); + if (toks.length < 2) { + s_logger.warn("Failed to parse Script output: " + line); + } else { + map.put(toks[0].trim(), toks[1].trim()); + } + numLines++; + } + if (numLines == 0) { + s_logger.warn("KeyValueInterpreter: no output lines?"); + } + return null; + } + + public Map getKeyValues() { + return map; + } + } + + @Override + protected String getDefaultScriptsDir() { + return null; + } + + protected static MessageFormat SnapshotXML = new MessageFormat( + " " + " {0}" + " " + + " {1}" + " " + + " "); + + protected String _hypervisorType; + protected String _hypervisorURI; + protected String _hypervisorPath; + protected String _sysvmISOPath; + protected String _privNwName; + protected String _privBridgeName; + protected String _linkLocalBridgeName; + protected String _publicBridgeName; + protected String _guestBridgeName; + protected String _privateIp; + protected String _pool; + protected String _localGateway; + private boolean _can_bridge_firewall; + protected String _localStoragePath; + protected String _localStorageUUID; + private Pair _pifs; + private final Map _vmStats = new ConcurrentHashMap(); + + protected boolean _disconnected = true; + protected int _timeout; + protected int _cmdsTimeout; + protected int _stopTimeout; + protected static HashMap s_statesTable; + static { + s_statesTable = new HashMap(); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF, + State.Stopped); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED, + State.Running); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING, + State.Running); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED, + State.Running); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE, + State.Unknown); + s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN, + State.Stopping); + } + + protected HashMap _vms = new HashMap(20); + protected List _vmsKilled = new ArrayList(); + + private VirtualRoutingResource _virtRouterResource; + + private String _pingTestPath; + + private int _dom0MinMem; + + protected enum defineOps { + UNDEFINE_VM, DEFINE_VM + } + + private String getEndIpFromStartIp(String startIp, int numIps) { + String[] tokens = startIp.split("[.]"); + assert (tokens.length == 4); + int lastbyte = Integer.parseInt(tokens[3]); + lastbyte = lastbyte + numIps; + tokens[3] = Integer.toString(lastbyte); + StringBuilder end = new StringBuilder(15); + end.append(tokens[0]).append(".").append(tokens[1]).append(".") + .append(tokens[2]).append(".").append(tokens[3]); + return end.toString(); + } + + private Map getDeveloperProperties() + throws ConfigurationException { + final File file = PropertiesUtil.findConfigFile("developer.properties"); + if (file == null) { + throw new ConfigurationException( + "Unable to find developer.properties."); + } + + s_logger.info("developer.properties found at " + file.getAbsolutePath()); + Properties properties = new Properties(); + try { + properties.load(new FileInputStream(file)); + + String startMac = (String) properties.get("private.macaddr.start"); + if (startMac == null) { + throw new ConfigurationException( + "Developers must specify start mac for private ip range"); + } + + String startIp = (String) properties.get("private.ipaddr.start"); + if (startIp == null) { + throw new ConfigurationException( + "Developers must specify start ip for private ip range"); + } + final Map params = PropertiesUtil.toMap(properties); + + String endIp = (String) properties.get("private.ipaddr.end"); + if (endIp == null) { + endIp = getEndIpFromStartIp(startIp, 16); + params.put("private.ipaddr.end", endIp); + } + return params; + } 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 String getDefaultNetworkScriptsDir() { + return "scripts/vm/network/vnet"; + } + + protected String getDefaultStorageScriptsDir() { + return "scripts/storage/qcow2"; + } + + private void saveProperties(Map params) + 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 _properties = new Properties(); + _properties.load(new FileInputStream(file)); + Set names = _properties.stringPropertyNames(); + for (String key : params.keySet()) { + if (!names.contains(key)) { + _properties.setProperty(key, (String) params.get(key)); + } + } + _properties.store(new FileOutputStream(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); + } + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + boolean success = super.configure(name, params); + if (!success) { + return false; + } + + try { + Class clazz = Class + .forName("com.cloud.storage.JavaStorageLayer"); + _storage = (StorageLayer) ComponentLocator.inject(clazz); + _storage.configure("StorageLayer", params); + } catch (ClassNotFoundException e) { + throw new ConfigurationException("Unable to find class " + + "com.cloud.storage.JavaStorageLayer"); + } + + _virtRouterResource = new VirtualRoutingResource(); + + // Set the domr scripts directory + params.put("domr.scripts.dir", "scripts/network/domr/kvm"); + + success = _virtRouterResource.configure(name, params); + + String kvmScriptsDir = (String) params.get("kvm.scripts.dir"); + if (kvmScriptsDir == null) { + kvmScriptsDir = "scripts/vm/hypervisor/kvm"; + } + + String networkScriptsDir = (String) params.get("network.scripts.dir"); + if (networkScriptsDir == null) { + networkScriptsDir = getDefaultNetworkScriptsDir(); + } + + String storageScriptsDir = (String) params.get("storage.scripts.dir"); + if (storageScriptsDir == null) { + storageScriptsDir = getDefaultStorageScriptsDir(); + } + + if (!success) { + return false; + } + + _host = (String) params.get("host"); + if (_host == null) { + _host = "localhost"; + } + + _dcId = (String) params.get("zone"); + if (_dcId == null) { + _dcId = "default"; + } + + _pod = (String) params.get("pod"); + if (_pod == null) { + _pod = "default"; + } + + _clusterId = (String) params.get("cluster"); + + _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); + if (_modifyVlanPath == null) { + throw new ConfigurationException("Unable to find modifyvlan.sh"); + } + + _versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh"); + if (_versionstringpath == null) { + throw new ConfigurationException("Unable to find versions.sh"); + } + + _patchdomrPath = Script.findScript(kvmScriptsDir + "/patch/", + "rundomrpre.sh"); + if (_patchdomrPath == null) { + throw new ConfigurationException("Unable to find rundomrpre.sh"); + } + + _heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh"); + if (_heartBeatPath == null) { + throw new ConfigurationException("Unable to find kvmheartbeat.sh"); + } + + _createvmPath = Script.findScript(storageScriptsDir, "createvm.sh"); + if (_createvmPath == null) { + throw new ConfigurationException("Unable to find the createvm.sh"); + } + + _manageSnapshotPath = Script.findScript(storageScriptsDir, + "managesnapshot.sh"); + if (_manageSnapshotPath == null) { + throw new ConfigurationException( + "Unable to find the managesnapshot.sh"); + } + + _createTmplPath = Script + .findScript(storageScriptsDir, "createtmplt.sh"); + if (_createTmplPath == null) { + throw new ConfigurationException( + "Unable to find the createtmplt.sh"); + } + + _securityGroupPath = Script.findScript(networkScriptsDir, + "security_group.py"); + if (_securityGroupPath == null) { + throw new ConfigurationException( + "Unable to find the security_group.py"); + } + + _networkUsagePath = Script.findScript("scripts/network/domr/", + "networkUsage.sh"); + if (_networkUsagePath == null) { + throw new ConfigurationException( + "Unable to find the networkUsage.sh"); + } + + String value = (String) params.get("developer"); + boolean isDeveloper = Boolean.parseBoolean(value); + + if (isDeveloper) { + params.putAll(getDeveloperProperties()); + } + + _pool = (String) params.get("pool"); + if (_pool == null) { + _pool = "/root"; + } + + String instance = (String) params.get("instance"); + + _hypervisorType = (String) params.get("hypervisor.type"); + if (_hypervisorType == null) { + _hypervisorType = "kvm"; + } + + _hypervisorURI = (String) params.get("hypervisor.uri"); + if (_hypervisorURI == null) { + _hypervisorURI = "qemu:///system"; + } + String startMac = (String) params.get("private.macaddr.start"); + if (startMac == null) { + startMac = "00:16:3e:77:e2:a0"; + } + + String startIp = (String) params.get("private.ipaddr.start"); + if (startIp == null) { + startIp = "192.168.166.128"; + } + + _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); + if (_pingTestPath == null) { + throw new ConfigurationException("Unable to find the pingtest.sh"); + } + + _linkLocalBridgeName = (String) params.get("private.bridge.name"); + if (_linkLocalBridgeName == null) { + if (isDeveloper) { + _linkLocalBridgeName = "cloud-" + instance + "-0"; + } else { + _linkLocalBridgeName = "cloud0"; + } + } + + _publicBridgeName = (String) params.get("public.network.device"); + if (_publicBridgeName == null) { + _publicBridgeName = "cloudbr0"; + } + + _privBridgeName = (String) params.get("private.network.device"); + if (_privBridgeName == null) { + _privBridgeName = "cloudbr1"; + } + + _guestBridgeName = (String) params.get("guest.network.device"); + if (_guestBridgeName == null) { + _guestBridgeName = _privBridgeName; + } + + _privNwName = (String) params.get("private.network.name"); + if (_privNwName == null) { + if (isDeveloper) { + _privNwName = "cloud-" + instance + "-private"; + } else { + _privNwName = "cloud-private"; + } + } + + _localStoragePath = (String) params.get("local.storage.path"); + if (_localStoragePath == null) { + _localStoragePath = "/var/lib/libvirt/images/"; + } + + _localStorageUUID = (String) params.get("local.storage.uuid"); + if (_localStorageUUID == null) { + _localStorageUUID = UUID.randomUUID().toString(); + params.put("local.storage.uuid", _localStorageUUID); + } + + value = (String) params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; + + value = (String) params.get("stop.script.timeout"); + _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000; + + value = (String) params.get("cmds.timeout"); + _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; + + value = (String) params.get("host.reserved.mem.mb"); + _dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024; + + value = (String) params.get("debug.mode"); + + LibvirtConnection.initialize(_hypervisorURI); + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.getMessage()); + } + + /* Does node support HVM guest? If not, exit */ + if (!IsHVMEnabled(conn)) { + throw new ConfigurationException( + "NO HVM support on this machine, pls make sure: " + + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. " + + "2. kvm modules is installed"); + } + + _hypervisorPath = getHypervisorPath(conn); + try { + _hvVersion = conn.getVersion(); + _hvVersion = (_hvVersion % 1000000) / 1000; + } catch (LibvirtException e) { + + } + + String[] info = NetUtils.getNetworkParams(_privateNic); + + _monitor = new KVMHAMonitor(null, info[0], _heartBeatPath); + Thread ha = new Thread(_monitor); + ha.start(); + + _storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor); + + _sysvmISOPath = (String) params.get("systemvm.iso.path"); + if (_sysvmISOPath == null) { + String[] isoPaths = { "/usr/lib64/cloud/agent/vms/systemvm.iso", + "/usr/lib/cloud/agent/vms/systemvm.iso" }; + for (String isoPath : isoPaths) { + if (_storage.exists(isoPath)) { + _sysvmISOPath = isoPath; + break; + } + } + if (_sysvmISOPath == null) { + s_logger.debug("Can't find system vm ISO"); + } + } + + try { + createControlNetwork(conn); + } catch (LibvirtException e) { + throw new ConfigurationException(e.getMessage()); + } + + _pifs = getPifs(); + if (_pifs.first() == null) { + s_logger.debug("Failed to get private nic name"); + throw new ConfigurationException("Failed to get private nic name"); + } + + if (_pifs.second() == null) { + s_logger.debug("Failed to get public nic name"); + throw new ConfigurationException("Failed to get public nic name"); + } + s_logger.debug("Found pif: " + _pifs.first() + " on " + _privBridgeName + + ", pif: " + _pifs.second() + " on " + _publicBridgeName); + + _can_bridge_firewall = can_bridge_firewall(_pifs.second()); + + _localGateway = Script + .runSimpleBashScript("ip route |grep default|awk '{print $3}'"); + if (_localGateway == null) { + s_logger.debug("Failed to found the local gateway"); + } + + _mountPoint = (String) params.get("mount.path"); + if (_mountPoint == null) { + _mountPoint = "/mnt"; + } + + value = (String) params.get("vm.migrate.speed"); + _migrateSpeed = NumbersUtil.parseInt(value, -1); + if (_migrateSpeed == -1) { + //get guest network device speed + _migrateSpeed = 0; + String speed = Script.runSimpleBashScript("ethtool " + _pifs.second() + " |grep Speed | cut -d \\ -f 2"); + if (speed != null) { + String[] tokens = speed.split("M"); + if (tokens.length == 2) { + try { + _migrateSpeed = Integer.parseInt(tokens[0]); + } catch (Exception e) { + + } + s_logger.debug("device " + _pifs.second() + " has speed: " + String.valueOf(_migrateSpeed)); + } + } + params.put("vm.migrate.speed", String.valueOf(_migrateSpeed)); + } + saveProperties(params); + + return true; + } + + private Pair getPifs() { + /* get pifs from bridge */ + String pubPif = null; + String privPif = null; + String vlan = null; + if (_publicBridgeName != null) { + pubPif = Script.runSimpleBashScript("brctl show | grep " + + _publicBridgeName + " | awk '{print $4}'"); + vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pubPif); + if (vlan != null && !vlan.isEmpty()) { + pubPif = Script + .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + + pubPif + " | awk {'print $2'}"); + } + } + if (_guestBridgeName != null) { + privPif = Script.runSimpleBashScript("brctl show | grep " + + _guestBridgeName + " | awk '{print $4}'"); + vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + privPif); + if (vlan != null && !vlan.isEmpty()) { + privPif = Script + .runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + + privPif + " | awk {'print $2'}"); + } + } + return new Pair(privPif, pubPif); + } + + private boolean checkNetwork(String networkName) { + if (networkName == null) { + return true; + } + + String name = Script.runSimpleBashScript("brctl show | grep " + + networkName + " | awk '{print $4}'"); + if (name == null) { + return false; + } else { + return true; + } + } + + private String getVnetId(String vnetId) { + return vnetId; + } + + private void patchSystemVm(String cmdLine, String dataDiskPath, + String vmName) throws InternalErrorException { + String result; + final Script command = new Script(_patchdomrPath, _timeout, s_logger); + command.add("-l", vmName); + command.add("-t", "all"); + command.add("-d", dataDiskPath); + command.add("-p", cmdLine.replaceAll(" ", "%")); + result = command.execute(); + if (result != null) { + throw new InternalErrorException(result); + } + } + + boolean isDirectAttachedNetwork(String type) { + if ("untagged".equalsIgnoreCase(type)) { + return true; + } else { + try { + Long.valueOf(type); + } catch (NumberFormatException e) { + return true; + } + return false; + } + } + + protected String startDomain(Connect conn, String vmName, String domainXML) + throws LibvirtException, InternalErrorException { + /* No duplicated vm, we will success, or failed */ + boolean failed = false; + Domain dm = null; + try { + dm = conn.domainDefineXML(domainXML); + } catch (final LibvirtException e) { + /* Duplicated defined vm */ + s_logger.warn("Failed to define domain " + vmName + ": " + + e.getMessage()); + failed = true; + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (final LibvirtException e) { + + } + } + + /* If failed, undefine the vm */ + Domain dmOld = null; + Domain dmNew = null; + try { + if (failed) { + dmOld = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + dmOld.undefine(); + dmNew = conn.domainDefineXML(domainXML); + } + } catch (final LibvirtException e) { + s_logger.warn("Failed to define domain (second time) " + vmName + + ": " + e.getMessage()); + throw e; + } catch (Exception e) { + s_logger.warn("Failed to define domain (second time) " + vmName + + ": " + e.getMessage()); + throw new InternalErrorException(e.toString()); + } finally { + try { + if (dmOld != null) { + dmOld.free(); + } + if (dmNew != null) { + dmNew.free(); + } + } catch (final LibvirtException e) { + + } + } + + /* Start the VM */ + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + dm.create(); + } catch (LibvirtException e) { + s_logger.warn("Failed to start domain: " + vmName + ": " + + e.getMessage()); + throw e; + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (final LibvirtException e) { + + } + } + return null; + } + + @Override + public boolean stop() { + try { + Connect conn = LibvirtConnection.getConnection(); + conn.close(); + } catch (LibvirtException e) { + } + + return true; + } + + public static void main(String[] args) { + s_logger.addAppender(new org.apache.log4j.ConsoleAppender( + new org.apache.log4j.PatternLayout(), "System.out")); + LibvirtComputingResource test = new LibvirtComputingResource(); + Map params = new HashMap(); + try { + test.configure("test", params); + } catch (ConfigurationException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + String result = null; + // String result = test.startDomainRouter("domr1", + // "/var/lib/images/centos.5-4.x86-64/centos-small.img", 128, "0064", + // "02:00:30:00:01:01", "00:16:3e:77:e2:a1", "02:00:30:00:64:01"); + boolean created = (result == null); + s_logger.info("Domain " + (created ? " " : " not ") + " created"); + + s_logger.info("Rule " + (created ? " " : " not ") + " created"); + test.stop(); + } + + @Override + public Answer executeRequest(Command cmd) { + + try { + if (cmd instanceof StopCommand) { + return execute((StopCommand) cmd); + } else if (cmd instanceof GetVmStatsCommand) { + return execute((GetVmStatsCommand) cmd); + } else if (cmd instanceof RebootRouterCommand) { + return execute((RebootRouterCommand) cmd); + } else if (cmd instanceof RebootCommand) { + return execute((RebootCommand) cmd); + } else if (cmd instanceof GetHostStatsCommand) { + return execute((GetHostStatsCommand) cmd); + } else if (cmd instanceof CheckStateCommand) { + return executeRequest(cmd); + } else if (cmd instanceof CheckHealthCommand) { + return execute((CheckHealthCommand) cmd); + } else if (cmd instanceof PrepareForMigrationCommand) { + return execute((PrepareForMigrationCommand) cmd); + } else if (cmd instanceof MigrateCommand) { + return execute((MigrateCommand) cmd); + } else if (cmd instanceof PingTestCommand) { + return execute((PingTestCommand) cmd); + } else if (cmd instanceof CheckVirtualMachineCommand) { + return execute((CheckVirtualMachineCommand) cmd); + } else if (cmd instanceof ReadyCommand) { + return execute((ReadyCommand) cmd); + } else if (cmd instanceof AttachIsoCommand) { + return execute((AttachIsoCommand) cmd); + } else if (cmd instanceof AttachVolumeCommand) { + return execute((AttachVolumeCommand) cmd); + } else if (cmd instanceof StopCommand) { + return execute((StopCommand) cmd); + } else if (cmd instanceof CheckConsoleProxyLoadCommand) { + return execute((CheckConsoleProxyLoadCommand) cmd); + } else if (cmd instanceof WatchConsoleProxyLoadCommand) { + return execute((WatchConsoleProxyLoadCommand) cmd); + } else if (cmd instanceof GetVncPortCommand) { + return execute((GetVncPortCommand) cmd); + } else if (cmd instanceof ModifySshKeysCommand) { + return execute((ModifySshKeysCommand) cmd); + } else if (cmd instanceof MaintainCommand) { + return execute((MaintainCommand) cmd); + } else if (cmd instanceof CreateCommand) { + return execute((CreateCommand) cmd); + } else if (cmd instanceof DestroyCommand) { + return execute((DestroyCommand) cmd); + } else if (cmd instanceof PrimaryStorageDownloadCommand) { + return execute((PrimaryStorageDownloadCommand) cmd); + } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) { + return execute((CreatePrivateTemplateFromVolumeCommand) cmd); + } else if (cmd instanceof GetStorageStatsCommand) { + return execute((GetStorageStatsCommand) cmd); + } else if (cmd instanceof ManageSnapshotCommand) { + return execute((ManageSnapshotCommand) cmd); + } else if (cmd instanceof BackupSnapshotCommand) { + return execute((BackupSnapshotCommand) cmd); + } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { + return execute((CreateVolumeFromSnapshotCommand) cmd); + } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { + return execute((CreatePrivateTemplateFromSnapshotCommand) cmd); + } else if (cmd instanceof UpgradeSnapshotCommand) { + return execute((UpgradeSnapshotCommand) cmd); + } else if (cmd instanceof CreateStoragePoolCommand) { + return execute((CreateStoragePoolCommand) cmd); + } else if (cmd instanceof ModifyStoragePoolCommand) { + return execute((ModifyStoragePoolCommand) cmd); + } else if (cmd instanceof SecurityGroupRulesCmd) { + return execute((SecurityGroupRulesCmd) cmd); + } else if (cmd instanceof DeleteStoragePoolCommand) { + return execute((DeleteStoragePoolCommand) cmd); + } else if (cmd instanceof FenceCommand) { + return execute((FenceCommand) cmd); + } else if (cmd instanceof StartCommand) { + return execute((StartCommand) cmd); + } else if (cmd instanceof IpAssocCommand) { + return execute((IpAssocCommand) cmd); + } else if (cmd instanceof NetworkElementCommand) { + return _virtRouterResource.executeRequest(cmd); + } else if (cmd instanceof CheckSshCommand) { + return execute((CheckSshCommand) cmd); + } else if (cmd instanceof NetworkUsageCommand) { + return execute((NetworkUsageCommand) cmd); + } else if (cmd instanceof NetworkRulesSystemVmCommand) { + return execute((NetworkRulesSystemVmCommand) cmd); + } else if (cmd instanceof CleanupNetworkRulesCmd) { + return execute((CleanupNetworkRulesCmd) cmd); + } else if (cmd instanceof CopyVolumeCommand) { + return execute((CopyVolumeCommand) cmd); + } else if (cmd instanceof CheckNetworkCommand) { + return execute((CheckNetworkCommand) cmd); + } else { + s_logger.warn("Unsupported command "); + return Answer.createUnsupportedCommandAnswer(cmd); + } + } catch (final IllegalArgumentException e) { + return new Answer(cmd, false, e.getMessage()); + } + } + + private CheckNetworkAnswer execute(CheckNetworkCommand cmd) { + List phyNics = cmd + .getPhysicalNetworkInfoList(); + String errMsg = null; + for (PhysicalNetworkSetupInfo nic : phyNics) { + if (!checkNetwork(nic.getGuestNetworkName())) { + errMsg = "Can not find network: " + nic.getGuestNetworkName(); + break; + } else if (!checkNetwork(nic.getPrivateNetworkName())) { + errMsg = "Can not find network: " + nic.getPrivateNetworkName(); + break; + } else if (!checkNetwork(nic.getPublicNetworkName())) { + errMsg = "Can not find network: " + nic.getPublicNetworkName(); + break; + } + } + + if (errMsg != null) { + return new CheckNetworkAnswer(cmd, false, errMsg); + } else { + return new CheckNetworkAnswer(cmd, true, null); + } + } + + private CopyVolumeAnswer execute(CopyVolumeCommand cmd) { + boolean copyToSecondary = cmd.toSecondaryStorage(); + String volumePath = cmd.getVolumePath(); + StorageFilerTO pool = cmd.getPool(); + String secondaryStorageUrl = cmd.getSecondaryStorageURL(); + KVMStoragePool secondaryStoragePool = null; + try { + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool + .getUuid()); + String volumeName = UUID.randomUUID().toString(); + + if (copyToSecondary) { + String destVolumeName = volumeName + ".qcow2"; + KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd + .getVolumePath()); + String volumeDestPath = "/volumes/" + cmd.getVolumeId() + + File.separator; + secondaryStoragePool = _storagePoolMgr + .getStoragePoolByURI(secondaryStorageUrl); + secondaryStoragePool.createFolder(volumeDestPath); + secondaryStoragePool.delete(); + secondaryStoragePool = _storagePoolMgr + .getStoragePoolByURI(secondaryStorageUrl + + volumeDestPath); + _storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, + secondaryStoragePool); + return new CopyVolumeAnswer(cmd, true, null, null, volumeName); + } else { + volumePath = "/volumes/" + cmd.getVolumeId() + File.separator; + secondaryStoragePool = _storagePoolMgr + .getStoragePoolByURI(secondaryStorageUrl + volumePath); + KVMPhysicalDisk volume = secondaryStoragePool + .getPhysicalDisk(cmd.getVolumePath() + ".qcow2"); + _storagePoolMgr.copyPhysicalDisk(volume, volumeName, + primaryPool); + return new CopyVolumeAnswer(cmd, true, null, null, volumeName); + } + } catch (CloudRuntimeException e) { + return new CopyVolumeAnswer(cmd, false, e.toString(), null, null); + } finally { + if (secondaryStoragePool != null) { + secondaryStoragePool.delete(); + } + } + } + + protected Answer execute(DeleteStoragePoolCommand cmd) { + try { + _storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid()); + return new Answer(cmd); + } catch (CloudRuntimeException e) { + return new Answer(cmd, false, e.toString()); + } + } + + protected FenceAnswer execute(FenceCommand cmd) { + ExecutorService executors = Executors.newSingleThreadExecutor(); + List pools = _monitor.getStoragePools(); + KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp()); + Future future = executors.submit(ha); + try { + Boolean result = future.get(); + if (result) { + return new FenceAnswer(cmd, false, "Heart is still beating..."); + } else { + return new FenceAnswer(cmd); + } + } catch (InterruptedException e) { + s_logger.warn("Unable to fence", e); + return new FenceAnswer(cmd, false, e.getMessage()); + } catch (ExecutionException e) { + s_logger.warn("Unable to fence", e); + return new FenceAnswer(cmd, false, e.getMessage()); + } + + } + + protected Storage.StorageResourceType getStorageResourceType() { + return Storage.StorageResourceType.STORAGE_POOL; + } + + protected Answer execute(CreateCommand cmd) { + StorageFilerTO pool = cmd.getPool(); + DiskProfile dskch = cmd.getDiskCharacteristics(); + KVMPhysicalDisk BaseVol = null; + KVMStoragePool primaryPool = null; + KVMPhysicalDisk vol = null; + long disksize; + try { + primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid()); + + if (cmd.getTemplateUrl() != null) { + + BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl()); + vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID + .randomUUID().toString(), primaryPool); + + if (vol == null) { + return new Answer(cmd, false, + " Can't create storage volume on storage pool"); + } + disksize = vol.getSize(); + } else { + disksize = dskch.getSize(); + vol = primaryPool.createPhysicalDisk(UUID.randomUUID() + .toString(), dskch.getSize()); + } + VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(), + pool.getType(), pool.getUuid(), pool.getPath(), + vol.getName(), vol.getName(), disksize, null); + return new CreateAnswer(cmd, volume); + } catch (CloudRuntimeException e) { + s_logger.debug("Failed to create volume: " + e.toString()); + return new CreateAnswer(cmd, e); + } + } + + public Answer execute(DestroyCommand cmd) { + VolumeTO vol = cmd.getVolume(); + + try { + KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol + .getPoolUuid()); + pool.deletePhysicalDisk(vol.getPath()); + + return new Answer(cmd, true, "Success"); + } catch (CloudRuntimeException e) { + s_logger.debug("Failed to delete volume: " + e.toString()); + return new Answer(cmd, false, e.toString()); + } + } + + private String getVlanIdFromBridge(String brName) { + OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser(); + final Script cmd = new Script("/bin/bash", s_logger); + cmd.add("-c"); + cmd.add("vlanid=$(brctl show |grep " + brName + + " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid"); + String result = cmd.execute(vlanIdParser); + if (result != null) { + return null; + } + String vlanId = vlanIdParser.getLine(); + if (vlanId.equalsIgnoreCase("")) { + return null; + } else { + return vlanId; + } + } + + private void VifHotPlug(Connect conn, String vmName, String vlanId, + String macAddr) throws InternalErrorException, LibvirtException { + NicTO nicTO = new NicTO(); + nicTO.setMac(macAddr); + nicTO.setType(TrafficType.Public); + if (vlanId == null) { + nicTO.setBroadcastType(BroadcastDomainType.Native); + } else { + nicTO.setBroadcastType(BroadcastDomainType.Vlan); + nicTO.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanId)); + } + + InterfaceDef nic = createVif(conn, nicTO, InterfaceDef.nicModel.VIRTIO); + Domain vm = getDomain(conn, vmName); + vm.attachDevice(nic.toString()); + } + + public Answer execute(IpAssocCommand cmd) { + String routerName = cmd + .getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String[] results = new String[cmd.getIpAddresses().length]; + Connect conn; + try { + conn = LibvirtConnection.getConnection(); + List nics = getInterfaces(conn, routerName); + Map vlanAllocatedToVM = new HashMap(); + Integer nicPos = 0; + for (InterfaceDef nic : nics) { + if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) { + vlanAllocatedToVM.put("LinkLocal", nicPos); + } else { + String vlanId = getVlanIdFromBridge(nic.getBrName()); + if (vlanId != null) { + vlanAllocatedToVM.put(vlanId, nicPos); + } else { + vlanAllocatedToVM.put(Vlan.UNTAGGED, nicPos); + } + } + nicPos++; + } + IpAddressTO[] ips = cmd.getIpAddresses(); + int i = 0; + String result = null; + int nicNum = 0; + for (IpAddressTO ip : ips) { + if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) { + /* plug a vif into router */ + VifHotPlug(conn, routerName, ip.getVlanId(), + ip.getVifMacAddress()); + vlanAllocatedToVM.put(ip.getVlanId(), nicPos++); + } + nicNum = vlanAllocatedToVM.get(ip.getVlanId()); + networkUsage(routerIp, "addVif", "eth" + nicNum); + result = _virtRouterResource.assignPublicIpAddress(routerName, + routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), + ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), + ip.getVlanNetmask(), ip.getVifMacAddress(), + ip.getGuestIp(), nicNum); + + if (result != null) { + results[i++] = IpAssocAnswer.errorResult; + } else { + results[i++] = ip.getPublicIp() + " - success"; + ; + } + } + return new IpAssocAnswer(cmd, results); + } catch (LibvirtException e) { + return new IpAssocAnswer(cmd, results); + } catch (InternalErrorException e) { + return new IpAssocAnswer(cmd, results); + } + } + + protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { + String snapshotName = cmd.getSnapshotName(); + String snapshotPath = cmd.getSnapshotPath(); + String vmName = cmd.getVmName(); + try { + Connect conn = LibvirtConnection.getConnection(); + DomainInfo.DomainState state = null; + Domain vm = null; + if (vmName != null) { + try { + vm = getDomain(conn, cmd.getVmName()); + state = vm.getInfo().state; + } catch (LibvirtException e) { + + } + } + + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd + .getPool().getUuid()); + KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd + .getVolumePath()); + if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING + && !primaryPool.isExternalSnapshot()) { + String vmUuid = vm.getUUIDString(); + Object[] args = new Object[] { snapshotName, vmUuid }; + String snapshot = SnapshotXML.format(args); + s_logger.debug(snapshot); + if (cmd.getCommandSwitch().equalsIgnoreCase( + ManageSnapshotCommand.CREATE_SNAPSHOT)) { + vm.snapshotCreateXML(snapshot); + } else { + DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); + snap.delete(0); + } + + /* + * libvirt on RHEL6 doesn't handle resume event emitted from + * qemu + */ + vm = getDomain(conn, cmd.getVmName()); + state = vm.getInfo().state; + if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { + vm.resume(); + } + } else { + + /* VM is not running, create a snapshot by ourself */ + final Script command = new Script(_manageSnapshotPath, + _cmdsTimeout, s_logger); + if (cmd.getCommandSwitch().equalsIgnoreCase( + ManageSnapshotCommand.CREATE_SNAPSHOT)) { + command.add("-c", disk.getPath()); + } else { + command.add("-d", snapshotPath); + } + + command.add("-n", snapshotName); + String result = command.execute(); + if (result != null) { + s_logger.debug("Failed to manage snapshot: " + result); + return new ManageSnapshotAnswer(cmd, false, + "Failed to manage snapshot: " + result); + } + } + return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(), + disk.getPath() + File.separator + snapshotName, true, null); + } catch (LibvirtException e) { + s_logger.debug("Failed to manage snapshot: " + e.toString()); + return new ManageSnapshotAnswer(cmd, false, + "Failed to manage snapshot: " + e.toString()); + } + + } + + protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) { + Long dcId = cmd.getDataCenterId(); + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); + String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl(); + String snapshotName = cmd.getSnapshotName(); + String snapshotPath = cmd.getVolumePath(); + String snapshotDestPath = null; + String snapshotRelPath = null; + String vmName = cmd.getVmName(); + KVMStoragePool secondaryStoragePool = null; + try { + Connect conn = LibvirtConnection.getConnection(); + + secondaryStoragePool = _storagePoolMgr + .getStoragePoolByURI(secondaryStoragePoolUrl); + + String ssPmountPath = secondaryStoragePool.getLocalPath(); + snapshotRelPath = File.separator + "snapshots" + File.separator + + dcId + File.separator + accountId + File.separator + + volumeId; + + snapshotDestPath = ssPmountPath + File.separator + "snapshots" + + File.separator + dcId + File.separator + accountId + + File.separator + volumeId; + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd + .getPrimaryStoragePoolNameLabel()); + KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd + .getVolumePath()); + Script command = new Script(_manageSnapshotPath, _cmdsTimeout, + s_logger); + command.add("-b", snapshotDisk.getPath()); + command.add("-n", snapshotName); + command.add("-p", snapshotDestPath); + command.add("-t", snapshotName); + String result = command.execute(); + if (result != null) { + s_logger.debug("Failed to backup snaptshot: " + result); + return new BackupSnapshotAnswer(cmd, false, result, null, true); + } + /* Delete the snapshot on primary */ + + DomainInfo.DomainState state = null; + Domain vm = null; + if (vmName != null) { + try { + vm = getDomain(conn, cmd.getVmName()); + state = vm.getInfo().state; + } catch (LibvirtException e) { + + } + } + + KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd + .getPool().getUuid()); + if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING + && !primaryStorage.isExternalSnapshot()) { + String vmUuid = vm.getUUIDString(); + Object[] args = new Object[] { snapshotName, vmUuid }; + String snapshot = SnapshotXML.format(args); + s_logger.debug(snapshot); + DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); + snap.delete(0); + + /* + * libvirt on RHEL6 doesn't handle resume event emitted from + * qemu + */ + vm = getDomain(conn, cmd.getVmName()); + state = vm.getInfo().state; + if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { + vm.resume(); + } + } else { + command = new Script(_manageSnapshotPath, _cmdsTimeout, + s_logger); + command.add("-d", snapshotDisk.getPath()); + command.add("-n", snapshotName); + result = command.execute(); + if (result != null) { + s_logger.debug("Failed to backup snapshot: " + result); + return new BackupSnapshotAnswer(cmd, false, + "Failed to backup snapshot: " + result, null, true); + } + } + } catch (LibvirtException e) { + return new BackupSnapshotAnswer(cmd, false, e.toString(), null, + true); + } catch (CloudRuntimeException e) { + return new BackupSnapshotAnswer(cmd, false, e.toString(), null, + true); + } finally { + if (secondaryStoragePool != null) { + secondaryStoragePool.delete(); + } + } + return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath + + File.separator + snapshotName, true); + } + + protected DeleteSnapshotBackupAnswer execute( + final DeleteSnapshotBackupCommand cmd) { + Long dcId = cmd.getDataCenterId(); + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); + KVMStoragePool secondaryStoragePool = null; + try { + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd + .getSecondaryStorageUrl()); + + String ssPmountPath = secondaryStoragePool.getLocalPath(); + String snapshotDestPath = ssPmountPath + File.separator + + "snapshots" + File.separator + dcId + File.separator + + accountId + File.separator + volumeId; + + final Script command = new Script(_manageSnapshotPath, + _cmdsTimeout, s_logger); + command.add("-d", snapshotDestPath); + command.add("-n", cmd.getSnapshotName()); + + command.execute(); + } catch (CloudRuntimeException e) { + return new DeleteSnapshotBackupAnswer(cmd, false, e.toString()); + } finally { + if (secondaryStoragePool != null) { + secondaryStoragePool.delete(); + } + } + return new DeleteSnapshotBackupAnswer(cmd, true, null); + } + + protected Answer execute(DeleteSnapshotsDirCommand cmd) { + Long dcId = cmd.getDcId(); + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); + KVMStoragePool secondaryStoragePool = null; + try { + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd + .getSecondaryStorageUrl()); + + String ssPmountPath = secondaryStoragePool.getLocalPath(); + String snapshotDestPath = ssPmountPath + File.separator + + "snapshots" + File.separator + dcId + File.separator + + accountId + File.separator + volumeId; + + final Script command = new Script(_manageSnapshotPath, + _cmdsTimeout, s_logger); + command.add("-d", snapshotDestPath); + command.add("-f"); + command.execute(); + } catch (CloudRuntimeException e) { + return new Answer(cmd, false, e.toString()); + } finally { + if (secondaryStoragePool != null) { + secondaryStoragePool.delete(); + } + + } + return new Answer(cmd, true, null); + } + + protected CreateVolumeFromSnapshotAnswer execute( + final CreateVolumeFromSnapshotCommand cmd) { + try { + + String snapshotPath = cmd.getSnapshotUuid(); + int index = snapshotPath.lastIndexOf("/"); + snapshotPath = snapshotPath.substring(0, index); + KVMStoragePool secondaryPool = _storagePoolMgr + .getStoragePoolByURI(cmd.getSecondaryStorageUrl() + + snapshotPath); + KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd + .getSnapshotName()); + + String primaryUuid = cmd.getPrimaryStoragePoolNameLabel(); + KVMStoragePool primaryPool = _storagePoolMgr + .getStoragePool(primaryUuid); + String volUuid = UUID.randomUUID().toString(); + KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot, + volUuid, primaryPool); + return new CreateVolumeFromSnapshotAnswer(cmd, true, "", + disk.getName()); + } catch (CloudRuntimeException e) { + return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(), + null); + } + } + + protected Answer execute(final UpgradeSnapshotCommand cmd) { + + return new Answer(cmd, true, "success"); + } + + protected CreatePrivateTemplateAnswer execute( + final CreatePrivateTemplateFromSnapshotCommand cmd) { + String templateFolder = cmd.getAccountId() + File.separator + + cmd.getNewTemplateId(); + String templateInstallFolder = "template/tmpl/" + templateFolder; + String tmplName = UUID.randomUUID().toString(); + String tmplFileName = tmplName + ".qcow2"; + KVMStoragePool secondaryPool = null; + KVMStoragePool snapshotPool = null; + try { + String snapshotPath = cmd.getSnapshotUuid(); + int index = snapshotPath.lastIndexOf("/"); + snapshotPath = snapshotPath.substring(0, index); + snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd + .getSecondaryStorageUrl() + snapshotPath); + KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd + .getSnapshotName()); + + secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd + .getSecondaryStorageUrl()); + + String templatePath = secondaryPool.getLocalPath() + File.separator + + templateInstallFolder; + + _storage.mkdirs(templatePath); + + String tmplPath = templateInstallFolder + File.separator + + tmplFileName; + Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger); + command.add("-t", templatePath); + command.add("-n", tmplFileName); + command.add("-f", snapshot.getPath()); + command.execute(); + + Map params = new HashMap(); + params.put(StorageLayer.InstanceConfigKey, _storage); + Processor qcow2Processor = new QCOW2Processor(); + qcow2Processor.configure("QCOW2 Processor", params); + FormatInfo info = qcow2Processor.process(templatePath, null, + tmplName); + + TemplateLocation loc = new TemplateLocation(_storage, templatePath); + loc.create(1, true, tmplName); + loc.addFormat(info); + loc.save(); + + return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath, + info.virtualSize, info.size, tmplName, info.format); + } catch (ConfigurationException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); + } catch (InternalErrorException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); + } catch (IOException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); + } catch (CloudRuntimeException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); + } finally { + if (secondaryPool != null) { + secondaryPool.delete(); + } + if (snapshotPool != null) { + snapshotPool.delete(); + } + } + } + + protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { + try { + KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd + .getStorageId()); + return new GetStorageStatsAnswer(cmd, sp.getCapacity(), + sp.getUsed()); + } catch (CloudRuntimeException e) { + return new GetStorageStatsAnswer(cmd, e.toString()); + } + } + + protected CreatePrivateTemplateAnswer execute( + CreatePrivateTemplateFromVolumeCommand cmd) { + String secondaryStorageURL = cmd.getSecondaryStorageUrl(); + + KVMStoragePool secondaryStorage = null; + try { + Connect conn = LibvirtConnection.getConnection(); + String templateFolder = cmd.getAccountId() + File.separator + + cmd.getTemplateId() + File.separator; + String templateInstallFolder = "/template/tmpl/" + templateFolder; + + secondaryStorage = _storagePoolMgr + .getStoragePoolByURI(secondaryStorageURL); + + KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd + .getPrimaryStoragePoolNameLabel()); + KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); + String tmpltPath = secondaryStorage.getLocalPath() + File.separator + + templateInstallFolder; + _storage.mkdirs(tmpltPath); + + Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger); + command.add("-f", disk.getPath()); + command.add("-t", tmpltPath); + command.add("-n", cmd.getUniqueName() + ".qcow2"); + + String result = command.execute(); + + if (result != null) { + s_logger.debug("failed to create template: " + result); + return new CreatePrivateTemplateAnswer(cmd, false, result); + } + + Map params = new HashMap(); + params.put(StorageLayer.InstanceConfigKey, _storage); + Processor qcow2Processor = new QCOW2Processor(); + + qcow2Processor.configure("QCOW2 Processor", params); + + FormatInfo info = qcow2Processor.process(tmpltPath, null, + cmd.getUniqueName()); + + TemplateLocation loc = new TemplateLocation(_storage, tmpltPath); + loc.create(1, true, cmd.getUniqueName()); + loc.addFormat(info); + loc.save(); + + return new CreatePrivateTemplateAnswer(cmd, true, null, + templateInstallFolder + cmd.getUniqueName() + ".qcow2", + info.virtualSize, info.size, cmd.getUniqueName(), + ImageFormat.QCOW2); + } catch (LibvirtException e) { + s_logger.debug("Failed to get secondary storage pool: " + + e.toString()); + return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); + } catch (InternalErrorException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); + } catch (IOException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); + } catch (ConfigurationException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); + } catch (CloudRuntimeException e) { + return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); + } finally { + if (secondaryStorage != null) { + secondaryStorage.delete(); + } + } + } + + protected PrimaryStorageDownloadAnswer execute( + final PrimaryStorageDownloadCommand cmd) { + String tmplturl = cmd.getUrl(); + int index = tmplturl.lastIndexOf("/"); + String mountpoint = tmplturl.substring(0, index); + String tmpltname = null; + if (index < tmplturl.length() - 1) { + tmpltname = tmplturl.substring(index + 1); + } + + KVMPhysicalDisk tmplVol = null; + KVMStoragePool secondaryPool = null; + try { + secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint); + + /* Get template vol */ + if (tmpltname == null) { + secondaryPool.refresh(); + List disks = secondaryPool.listPhysicalDisks(); + if (disks == null || disks.isEmpty()) { + return new PrimaryStorageDownloadAnswer( + "Failed to get volumes from pool: " + + secondaryPool.getUuid()); + } + for (KVMPhysicalDisk disk : disks) { + if (disk.getName().endsWith("qcow2")) { + tmplVol = disk; + break; + } + } + if (tmplVol == null) { + return new PrimaryStorageDownloadAnswer( + "Failed to get template from pool: " + + secondaryPool.getUuid()); + } + } else { + tmplVol = secondaryPool.getPhysicalDisk(tmpltname); + } + + /* Copy volume to primary storage */ + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd + .getPoolUuid()); + + KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk( + tmplVol, UUID.randomUUID().toString(), primaryPool); + + return new PrimaryStorageDownloadAnswer(primaryVol.getName(), + primaryVol.getSize()); + } catch (CloudRuntimeException e) { + return new PrimaryStorageDownloadAnswer(e.toString()); + } finally { + if (secondaryPool != null) { + secondaryPool.delete(); + } + } + } + + protected Answer execute(CreateStoragePoolCommand cmd) { + return new Answer(cmd, true, "success"); + } + + protected Answer execute(ModifyStoragePoolCommand cmd) { + KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd + .getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool() + .getPath(), cmd.getPool().getType()); + if (storagepool == null) { + return new Answer(cmd, false, " Failed to create storage pool"); + } + + Map tInfo = new HashMap(); + ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, + storagepool.getCapacity(), storagepool.getUsed(), tInfo); + + return answer; + } + + private Answer execute(SecurityGroupRulesCmd cmd) { + String vif = null; + String brname = null; + try { + Connect conn = LibvirtConnection.getConnection(); + List nics = getInterfaces(conn, cmd.getVmName()); + vif = nics.get(0).getDevName(); + brname = nics.get(0).getBrName(); + } catch (LibvirtException e) { + return new SecurityGroupRuleAnswer(cmd, false, e.toString()); + } + + boolean result = add_network_rules(cmd.getVmName(), + Long.toString(cmd.getVmId()), cmd.getGuestIp(), + cmd.getSignature(), Long.toString(cmd.getSeqNum()), + cmd.getGuestMac(), cmd.stringifyRules(), vif, brname); + + if (!result) { + s_logger.warn("Failed to program network rules for vm " + + cmd.getVmName()); + return new SecurityGroupRuleAnswer(cmd, false, + "programming network rules failed"); + } else { + s_logger.debug("Programmed network rules for vm " + cmd.getVmName() + + " guestIp=" + cmd.getGuestIp() + ",ingress numrules=" + + cmd.getIngressRuleSet().length + ",egress numrules=" + + cmd.getEgressRuleSet().length); + return new SecurityGroupRuleAnswer(cmd); + } + } + + private Answer execute(CleanupNetworkRulesCmd cmd) { + boolean result = cleanup_rules(); + return new Answer(cmd, result, ""); + } + + protected GetVncPortAnswer execute(GetVncPortCommand cmd) { + try { + Connect conn = LibvirtConnection.getConnection(); + Integer vncPort = getVncPort(conn, cmd.getName()); + return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort); + } catch (Exception e) { + return new GetVncPortAnswer(cmd, e.toString()); + } + } + + protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { + return executeProxyLoadScan(cmd, cmd.getProxyVmId(), + cmd.getProxyVmName(), cmd.getProxyManagementIp(), + cmd.getProxyCmdPort()); + } + + protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { + return executeProxyLoadScan(cmd, cmd.getProxyVmId(), + cmd.getProxyVmName(), cmd.getProxyManagementIp(), + cmd.getProxyCmdPort()); + } + + protected MaintainAnswer execute(MaintainCommand cmd) { + return new MaintainAnswer(cmd); + } + + private Answer executeProxyLoadScan(final Command cmd, + final long proxyVmId, final String proxyVmName, + final String proxyManagementIp, final int cmdPort) { + String result = null; + + final StringBuffer sb = new StringBuffer(); + sb.append("http://").append(proxyManagementIp).append(":" + cmdPort) + .append("/cmd/getstatus"); + + boolean success = true; + try { + final URL url = new URL(sb.toString()); + final URLConnection conn = url.openConnection(); + + final InputStream is = conn.getInputStream(); + final BufferedReader reader = new BufferedReader( + new InputStreamReader(is)); + final StringBuilder sb2 = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb2.append(line + "\n"); + } + result = sb2.toString(); + } catch (final IOException e) { + success = false; + } finally { + try { + is.close(); + } catch (final IOException e) { + s_logger.warn("Exception when closing , console proxy address : " + + proxyManagementIp); + success = false; + } + } + } catch (final IOException e) { + s_logger.warn("Unable to open console proxy command port url, console proxy address : " + + proxyManagementIp); + success = false; + } + + return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, + result); + } + + private Answer execute(AttachIsoCommand cmd) { + try { + Connect conn = LibvirtConnection.getConnection(); + attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(), + cmd.isAttach()); + } catch (LibvirtException e) { + return new Answer(cmd, false, e.toString()); + } catch (URISyntaxException e) { + return new Answer(cmd, false, e.toString()); + } catch (InternalErrorException e) { + return new Answer(cmd, false, e.toString()); + } + + return new Answer(cmd); + } + + private AttachVolumeAnswer execute(AttachVolumeCommand cmd) { + try { + Connect conn = LibvirtConnection.getConnection(); + KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd + .getPoolUuid()); + KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); + attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk, + cmd.getDeviceId().intValue()); + } catch (LibvirtException e) { + return new AttachVolumeAnswer(cmd, e.toString()); + } catch (InternalErrorException e) { + return new AttachVolumeAnswer(cmd, e.toString()); + } + + return new AttachVolumeAnswer(cmd, cmd.getDeviceId()); + } + + private Answer execute(ReadyCommand cmd) { + return new ReadyAnswer(cmd); + } + + protected State convertToState(DomainInfo.DomainState ps) { + final State state = s_statesTable.get(ps); + return state == null ? State.Unknown : state; + } + + protected State getVmState(Connect conn, final String vmName) { + int retry = 3; + Domain vms = null; + while (retry-- > 0) { + try { + vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + State s = convertToState(vms.getInfo().state); + return s; + } catch (final LibvirtException e) { + s_logger.warn("Can't get vm state " + vmName + e.getMessage() + + "retry:" + retry); + } catch (Exception e) { + s_logger.warn("Can't get vm state " + vmName + e.getMessage() + + "retry:" + retry); + } finally { + try { + if (vms != null) { + vms.free(); + } + } catch (final LibvirtException e) { + + } + } + } + return State.Stopped; + } + + private Answer execute(CheckVirtualMachineCommand cmd) { + try { + Connect conn = LibvirtConnection.getConnection(); + final State state = getVmState(conn, cmd.getVmName()); + Integer vncPort = null; + if (state == State.Running) { + vncPort = getVncPort(conn, cmd.getVmName()); + + synchronized (_vms) { + _vms.put(cmd.getVmName(), State.Running); + } + } + + return new CheckVirtualMachineAnswer(cmd, state, vncPort); + } catch (LibvirtException e) { + return new CheckVirtualMachineAnswer(cmd, e.getMessage()); + } + } + + private Answer execute(PingTestCommand cmd) { + String result = null; + final String computingHostIp = cmd.getComputingHostIp(); // TODO, split + // the + // command + // into 2 + // types + + if (computingHostIp != null) { + result = doPingTest(computingHostIp); + } else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) { + result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp()); + } else { + return new Answer(cmd, false, "routerip and private ip is null"); + } + + if (result != null) { + return new Answer(cmd, false, result); + } + return new Answer(cmd); + } + + private String doPingTest(final String computingHostIp) { + final Script command = new Script(_pingTestPath, 10000, s_logger); + command.add("-h", computingHostIp); + return command.execute(); + } + + private String doPingTest(final String domRIp, final String vmIp) { + final Script command = new Script(_pingTestPath, 10000, s_logger); + command.add("-i", domRIp); + command.add("-p", vmIp); + return command.execute(); + } + + private synchronized Answer execute(MigrateCommand cmd) { + String vmName = cmd.getVmName(); + + State state = null; + String result = null; + synchronized (_vms) { + state = _vms.get(vmName); + _vms.put(vmName, State.Stopping); + } + + Domain dm = null; + Connect dconn = null; + Domain destDomain = null; + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp() + + "/system"); + /* + * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and + * VIR_MIGRATE_PERSIST_DEST(1<<3) + */ + destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:" + + cmd.getDestinationIp(), _migrateSpeed); + } catch (LibvirtException e) { + s_logger.debug("Can't migrate domain: " + e.getMessage()); + result = e.getMessage(); + } catch (Exception e) { + s_logger.debug("Can't migrate domain: " + e.getMessage()); + result = e.getMessage(); + } finally { + try { + if (dm != null) { + dm.free(); + } + if (dconn != null) { + dconn.close(); + } + if (destDomain != null) { + destDomain.free(); + } + } catch (final LibvirtException e) { + + } + } + + if (result != null) { + synchronized (_vms) { + _vms.put(vmName, state); + } + } else { + destroy_network_rules_for_vm(conn, vmName); + cleanupVM(conn, vmName, + getVnetId(VirtualMachineName.getVnet(vmName))); + } + + return new MigrateAnswer(cmd, result == null, result, null); + } + + private synchronized Answer execute(PrepareForMigrationCommand cmd) { + + VirtualMachineTO vm = cmd.getVirtualMachine(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Preparing host for migrating " + vm); + } + + NicTO[] nics = vm.getNics(); + try { + Connect conn = LibvirtConnection.getConnection(); + for (NicTO nic : nics) { + String vlanId = null; + if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { + URI broadcastUri = nic.getBroadcastUri(); + vlanId = broadcastUri.getHost(); + } + if (nic.getType() == TrafficType.Guest) { + if (nic.getBroadcastType() == BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + createVlanBr(vlanId, _pifs.first()); + } + } else if (nic.getType() == TrafficType.Control) { + /* Make sure the network is still there */ + createControlNetwork(conn); + } else if (nic.getType() == TrafficType.Public) { + if (nic.getBroadcastType() == BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + createVlanBr(vlanId, _pifs.second()); + } + } + } + + /* setup disks, e.g for iso */ + VolumeTO[] volumes = vm.getDisks(); + for (VolumeTO volume : volumes) { + if (volume.getType() == Volume.Type.ISO) { + getVolumePath(conn, volume); + } + } + + synchronized (_vms) { + _vms.put(vm.getName(), State.Migrating); + } + + return new PrepareForMigrationAnswer(cmd); + } catch (LibvirtException e) { + return new PrepareForMigrationAnswer(cmd, e.toString()); + } catch (InternalErrorException e) { + return new PrepareForMigrationAnswer(cmd, e.toString()); + } catch (URISyntaxException e) { + return new PrepareForMigrationAnswer(cmd, e.toString()); + } + } + + public void createVnet(String vnetId, String pif) + throws InternalErrorException { + final Script command = new Script(_modifyVlanPath, _timeout, s_logger); + command.add("-v", vnetId); + command.add("-p", pif); + command.add("-o", "add"); + + final String result = command.execute(); + if (result != null) { + throw new InternalErrorException("Failed to create vnet " + vnetId + + ": " + result); + } + } + + private Answer execute(CheckHealthCommand cmd) { + return new CheckHealthAnswer(cmd, true); + } + + private Answer execute(GetHostStatsCommand cmd) { + final Script cpuScript = new Script("/bin/bash", s_logger); + cpuScript.add("-c"); + cpuScript + .add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle"); + + final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); + String result = cpuScript.execute(parser); + if (result != null) { + s_logger.debug("Unable to get the host CPU state: " + result); + return new Answer(cmd, false, result); + } + double cpuUtil = (100.0D - Double.parseDouble(parser.getLine())); + + long freeMem = 0; + final Script memScript = new Script("/bin/bash", s_logger); + memScript.add("-c"); + memScript + .add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem"); + final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser(); + result = memScript.execute(Memparser); + if (result != null) { + s_logger.debug("Unable to get the host Mem state: " + result); + return new Answer(cmd, false, result); + } + freeMem = Long.parseLong(Memparser.getLine()); + + Script totalMem = new Script("/bin/bash", s_logger); + totalMem.add("-c"); + totalMem.add("free|grep Mem:|awk '{print $2}'"); + final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser(); + result = totalMem.execute(totMemparser); + if (result != null) { + s_logger.debug("Unable to get the host Mem state: " + result); + return new Answer(cmd, false, result); + } + long totMem = Long.parseLong(totMemparser.getLine()); + + Pair nicStats = getNicStats(_publicBridgeName); + + HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil, + nicStats.first() / 1000, nicStats.second() / 1000, "host", + totMem, freeMem, 0, 0); + return new GetHostStatsAnswer(cmd, hostStats); + } + + protected String networkUsage(final String privateIpAddress, + final String option, final String vif) { + Script getUsage = new Script(_networkUsagePath, s_logger); + if (option.equals("get")) { + getUsage.add("-g"); + } else if (option.equals("create")) { + getUsage.add("-c"); + } else if (option.equals("reset")) { + getUsage.add("-r"); + } else if (option.equals("addVif")) { + getUsage.add("-a", vif); + } else if (option.equals("deleteVif")) { + getUsage.add("-d", vif); + } + + getUsage.add("-i", privateIpAddress); + final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); + String result = getUsage.execute(usageParser); + if (result != null) { + s_logger.debug("Failed to execute networkUsage:" + result); + return null; + } + return usageParser.getLine(); + } + + protected long[] getNetworkStats(String privateIP) { + String result = networkUsage(privateIP, "get", null); + long[] stats = new long[2]; + if (result != null) { + String[] splitResult = result.split(":"); + int i = 0; + while (i < splitResult.length - 1) { + stats[0] += (new Long(splitResult[i++])).longValue(); + stats[1] += (new Long(splitResult[i++])).longValue(); + } + } + return stats; + } + + private Answer execute(NetworkUsageCommand cmd) { + if (cmd.getOption() != null && cmd.getOption().equals("create")) { + String result = networkUsage(cmd.getPrivateIP(), "create", null); + NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, + 0L); + return answer; + } + long[] stats = getNetworkStats(cmd.getPrivateIP()); + NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], + stats[1]); + return answer; + } + + private Answer execute(RebootCommand cmd) { + Long bytesReceived = null; + Long bytesSent = null; + + synchronized (_vms) { + _vms.put(cmd.getVmName(), State.Starting); + } + + try { + Connect conn = LibvirtConnection.getConnection(); + final String result = rebootVM(conn, cmd.getVmName()); + if (result == null) { + Integer vncPort = null; + try { + vncPort = getVncPort(conn, cmd.getVmName()); + } catch (Exception e) { + + } + get_rule_logs_for_vms(); + return new RebootAnswer(cmd, null, bytesSent, bytesReceived, + vncPort); + } else { + return new RebootAnswer(cmd, result); + } + } catch (LibvirtException e) { + return new RebootAnswer(cmd, e.getMessage()); + } finally { + synchronized (_vms) { + _vms.put(cmd.getVmName(), State.Running); + } + } + } + + protected Answer execute(RebootRouterCommand cmd) { + Long bytesSent = 0L; + Long bytesRcvd = 0L; + if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { + long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); + bytesSent = stats[0]; + bytesRcvd = stats[1]; + } + RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); + answer.setBytesSent(bytesSent); + answer.setBytesReceived(bytesRcvd); + String result = _virtRouterResource.connect(cmd.getPrivateIpAddress()); + if (result == null) { + networkUsage(cmd.getPrivateIpAddress(), "create", null); + return answer; + } else { + return new Answer(cmd, false, result); + } + } + + protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { + List vmNames = cmd.getVmNames(); + try { + HashMap vmStatsNameMap = new HashMap(); + Connect conn = LibvirtConnection.getConnection(); + for (String vmName : vmNames) { + VmStatsEntry statEntry = getVmStat(conn, vmName); + if (statEntry == null) { + continue; + } + + vmStatsNameMap.put(vmName, statEntry); + } + return new GetVmStatsAnswer(cmd, vmStatsNameMap); + } catch (LibvirtException e) { + s_logger.debug("Can't get vm stats: " + e.toString()); + return new GetVmStatsAnswer(cmd, null); + } + } + + protected Answer execute(StopCommand cmd) { + final String vmName = cmd.getVmName(); + + Long bytesReceived = new Long(0); + Long bytesSent = new Long(0); + + State state = null; + synchronized (_vms) { + state = _vms.get(vmName); + _vms.put(vmName, State.Stopping); + } + try { + Connect conn = LibvirtConnection.getConnection(); + + List disks = getDisks(conn, vmName); + destroy_network_rules_for_vm(conn, vmName); + String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM); + if (result == null) { + for (DiskDef disk : disks) { + if (disk.getDeviceType() == DiskDef.deviceType.CDROM + && disk.getDiskPath() != null) + cleanupDisk(conn, disk); + } + } + + final String result2 = cleanupVnet(conn, cmd.getVnet()); + + if (result != null && result2 != null) { + result = result2 + result; + } + state = State.Stopped; + return new StopAnswer(cmd, result, 0, bytesSent, bytesReceived); + } catch (LibvirtException e) { + return new StopAnswer(cmd, e.getMessage()); + } finally { + synchronized (_vms) { + if (state != null) { + _vms.put(vmName, state); + } else { + _vms.remove(vmName); + } + } + } + } + + protected Answer execute(ModifySshKeysCommand cmd) { + File sshKeysDir = new File(_SSHKEYSPATH); + String result = null; + if (!sshKeysDir.exists()) { + sshKeysDir.mkdir(); + // Change permissions for the 600 + Script script = new Script("chmod", _timeout, s_logger); + script.add("600", _SSHKEYSPATH); + script.execute(); + } + + File pubKeyFile = new File(_SSHPUBKEYPATH); + if (!pubKeyFile.exists()) { + try { + pubKeyFile.createNewFile(); + } catch (IOException e) { + result = "Failed to create file: " + e.toString(); + s_logger.debug(result); + } + } + + if (pubKeyFile.exists()) { + String pubKey = cmd.getPubKey(); + try { + FileOutputStream pubkStream = new FileOutputStream(pubKeyFile); + pubkStream.write(pubKey.getBytes()); + pubkStream.close(); + } catch (FileNotFoundException e) { + result = "File" + _SSHPUBKEYPATH + "is not found:" + + e.toString(); + s_logger.debug(result); + } catch (IOException e) { + result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString(); + s_logger.debug(result); + } + } + + File prvKeyFile = new File(_SSHPRVKEYPATH); + if (!prvKeyFile.exists()) { + try { + prvKeyFile.createNewFile(); + } catch (IOException e) { + result = "Failed to create file: " + e.toString(); + s_logger.debug(result); + } + } + + if (prvKeyFile.exists()) { + String prvKey = cmd.getPrvKey(); + try { + FileOutputStream prvKStream = new FileOutputStream(prvKeyFile); + prvKStream.write(prvKey.getBytes()); + prvKStream.close(); + } catch (FileNotFoundException e) { + result = "File" + _SSHPRVKEYPATH + "is not found:" + + e.toString(); + s_logger.debug(result); + } catch (IOException e) { + result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString(); + s_logger.debug(result); + } + + Script script = new Script("chmod", _timeout, s_logger); + script.add("600", _SSHPRVKEYPATH); + script.execute(); + } + + if (result != null) { + return new Answer(cmd, false, result); + } else { + return new Answer(cmd, true, null); + } + } + + protected void handleVmStartFailure(Connect conn, String vmName, + LibvirtVMDef vm) { + if (vm != null && vm.getDevices() != null) { + cleanupVMNetworks(conn, vm.getDevices().getInterfaces()); + } + } + + protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) { + LibvirtVMDef vm = new LibvirtVMDef(); + vm.setHvsType(_hypervisorType); + vm.setDomainName(vmTO.getName()); + vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes()) + .toString()); + vm.setDomDescription(vmTO.getOs()); + + GuestDef guest = new GuestDef(); + guest.setGuestType(GuestDef.guestType.KVM); + guest.setGuestArch(vmTO.getArch()); + guest.setMachineType("pc"); + guest.setBootOrder(GuestDef.bootOrder.CDROM); + guest.setBootOrder(GuestDef.bootOrder.HARDISK); + + vm.addComp(guest); + + GuestResourceDef grd = new GuestResourceDef(); + grd.setMemorySize(vmTO.getMinRam() / 1024); + grd.setVcpuNum(vmTO.getCpus()); + vm.addComp(grd); + + FeaturesDef features = new FeaturesDef(); + features.addFeatures("pae"); + features.addFeatures("apic"); + features.addFeatures("acpi"); + vm.addComp(features); + + TermPolicy term = new TermPolicy(); + term.setCrashPolicy("destroy"); + term.setPowerOffPolicy("destroy"); + term.setRebootPolicy("restart"); + vm.addComp(term); + + ClockDef clock = new ClockDef(); + if (vmTO.getOs().startsWith("Windows")) { + clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME); + clock.setTimer("rtc", "catchup", null); + } + + vm.addComp(clock); + + DevicesDef devices = new DevicesDef(); + devices.setEmulatorPath(_hypervisorPath); + + SerialDef serial = new SerialDef("pty", null, (short) 0); + devices.addDevice(serial); + + ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0); + devices.addDevice(console); + + GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null, + null); + devices.addDevice(grap); + + InputDef input = new InputDef("tablet", "usb"); + devices.addDevice(input); + + vm.addComp(devices); + + return vm; + } + + protected void createVifs(Connect conn, VirtualMachineTO vmSpec, + LibvirtVMDef vm) throws InternalErrorException, LibvirtException { + NicTO[] nics = vmSpec.getNics(); + for (int i = 0; i < nics.length; i++) { + for (NicTO nic : vmSpec.getNics()) { + if (nic.getDeviceId() == i) { + createVif(conn, vm, nic); + } + } + } + } + + protected synchronized StartAnswer execute(StartCommand cmd) { + VirtualMachineTO vmSpec = cmd.getVirtualMachine(); vmSpec.setVncAddr(cmd.getHostIp()); - String vmName = vmSpec.getName(); - LibvirtVMDef vm = null; - - State state = State.Stopped; - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - synchronized (_vms) { - _vms.put(vmName, State.Starting); - } - - vm = createVMFromSpec(vmSpec); - - createVbd(conn, vmSpec, vmName, vm); - - createVifs(conn, vmSpec, vm); - - s_logger.debug("starting " + vmName + ": " + vm.toString()); - startDomain(conn, vmName, vm.toString()); - Script.runSimpleBashScript("virsh schedinfo " + vmName - + " --set cpu_shares=" + vmSpec.getCpus() - * vmSpec.getSpeed()); - - NicTO[] nics = vmSpec.getNics(); - for (NicTO nic : nics) { - if (nic.getIsolationUri() != null - && nic.getIsolationUri().getScheme() - .equalsIgnoreCase(IsolationType.Ec2.toString())) { - if (vmSpec.getType() != VirtualMachine.Type.User) { - default_network_rules_for_systemvm(conn, vmName); - break; - } else { - default_network_rules(conn, vmName, nic, vmSpec.getId()); - } - } - } - - state = State.Running; - return new StartAnswer(cmd); - } catch (Exception e) { - s_logger.warn("Exception ", e); - if (conn != null) { - handleVmStartFailure(conn, vmName, vm); - } - return new StartAnswer(cmd, e.getMessage()); - } finally { - synchronized (_vms) { - if (state != State.Stopped) { - _vms.put(vmName, state); - } else { - _vms.remove(vmName); - } - } - } - } - - private String getVolumePath(Connect conn, VolumeTO volume) - throws LibvirtException, URISyntaxException { - if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) { - String isoPath = volume.getPath(); - int index = isoPath.lastIndexOf("/"); - String path = isoPath.substring(0, index); - String name = isoPath.substring(index + 1); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(path); - KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); - return isoVol.getPath(); - } else { - return volume.getPath(); - } - } - - protected void createVbd(Connect conn, VirtualMachineTO vmSpec, - String vmName, LibvirtVMDef vm) throws InternalErrorException, - LibvirtException, URISyntaxException { - List disks = Arrays.asList(vmSpec.getDisks()); - Collections.sort(disks, new Comparator() { - @Override - public int compare(VolumeTO arg0, VolumeTO arg1) { - return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1; - } - }); - - for (VolumeTO volume : disks) { - KVMPhysicalDisk physicalDisk = null; - KVMStoragePool pool = null; - if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) { - String volPath = volume.getPath(); - int index = volPath.lastIndexOf("/"); - String volDir = volPath.substring(0, index); - String volName = volPath.substring(index + 1); - KVMStoragePool secondaryStorage = _storagePoolMgr - .getStoragePoolByURI(volDir); - physicalDisk = secondaryStorage.getPhysicalDisk(volName); - } else if (volume.getType() != Volume.Type.ISO) { - pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid()); - physicalDisk = pool.getPhysicalDisk(volume.getPath()); - } - - String volPath = null; - if (physicalDisk != null) { - volPath = physicalDisk.getPath(); - } - - DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs()); - DiskDef disk = new DiskDef(); - if (volume.getType() == Volume.Type.ISO) { - if (volPath == null) { - /* Add iso as placeholder */ - disk.defISODisk(null); - } else { - disk.defISODisk(volPath); - } - } else { - int devId = (int) volume.getDeviceId(); - - if (volume.getType() == Volume.Type.DATADISK) { - disk.defFileBasedDisk(physicalDisk.getPath(), devId, - DiskDef.diskBus.VIRTIO, - DiskDef.diskFmtType.QCOW2); - } else { - disk.defFileBasedDisk(physicalDisk.getPath(), devId, - diskBusType, DiskDef.diskFmtType.QCOW2); - } - - } - - vm.getDevices().addDevice(disk); - } - - if (vmSpec.getType() != VirtualMachine.Type.User) { - if (_sysvmISOPath != null) { - DiskDef iso = new DiskDef(); - iso.defISODisk(_sysvmISOPath); - vm.getDevices().addDevice(iso); - } - - createPatchVbd(conn, vmName, vm, vmSpec); - } - } - - private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) { - VolumeTO volumes[] = vmSpec.getDisks(); - for (VolumeTO volume : volumes) { - if (volume.getType() == type) { - return volume; - } - } - return null; - } - - private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm, - VirtualMachineTO vmSpec) throws LibvirtException, - InternalErrorException { - - List disks = vm.getDevices().getDisks(); - DiskDef rootDisk = disks.get(0); - VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT); - KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol - .getPoolUuid()); - KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID() - .toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW, - 10L * 1024 * 1024); - /* Format/create fs on this disk */ - final Script command = new Script(_createvmPath, _timeout, s_logger); - command.add("-f", disk.getPath()); - String result = command.execute(); - if (result != null) { - s_logger.debug("Failed to create data disk: " + result); - throw new InternalErrorException("Failed to create data disk: " - + result); - } - String datadiskPath = disk.getPath(); - - /* add patch disk */ - DiskDef patchDisk = new DiskDef(); - - patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(), - DiskDef.diskFmtType.RAW); - - disks.add(patchDisk); - - String bootArgs = vmSpec.getBootArgs(); - - patchSystemVm(bootArgs, datadiskPath, vmName); - } - - private String createVlanBr(String vlanId, String nic) - throws InternalErrorException { - String brName = setVnetBrName(vlanId); - createVnet(vlanId, nic); - return brName; - } - - private InterfaceDef createVif(Connect conn, NicTO nic, - InterfaceDef.nicModel model) throws InternalErrorException, - LibvirtException { - InterfaceDef intf = new InterfaceDef(); - - String vlanId = null; - if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { - URI broadcastUri = nic.getBroadcastUri(); - vlanId = broadcastUri.getHost(); - } - - if (nic.getType() == TrafficType.Guest) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan - && !vlanId.equalsIgnoreCase("untagged")) { - String brName = createVlanBr(vlanId, _pifs.first()); - intf.defBridgeNet(brName, null, nic.getMac(), model); - } else { - intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model); - } - } else if (nic.getType() == TrafficType.Control) { - /* Make sure the network is still there */ - createControlNetwork(conn); - intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model); - } else if (nic.getType() == TrafficType.Public) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan - && !vlanId.equalsIgnoreCase("untagged")) { - String brName = createVlanBr(vlanId, _pifs.second()); - intf.defBridgeNet(brName, null, nic.getMac(), model); - } else { - intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model); - } - } else if (nic.getType() == TrafficType.Management) { - intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model); - } else if (nic.getType() == TrafficType.Storage) { - String storageBrName = nic.getName() == null ? _privBridgeName - : nic.getName(); - intf.defBridgeNet(storageBrName, null, nic.getMac(), model); - } - - return intf; - } - - private void createVif(Connect conn, LibvirtVMDef vm, NicTO nic) - throws InternalErrorException, LibvirtException { - vm.getDevices().addDevice( - createVif(conn, nic, getGuestNicModel(vm.getGuestOSType()))); - } - - protected CheckSshAnswer execute(CheckSshCommand cmd) { - String vmName = cmd.getName(); - String privateIp = cmd.getIp(); - int cmdPort = cmd.getPort(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); - } - - try { - String result = _virtRouterResource.connect(privateIp, cmdPort); - if (result != null) { - return new CheckSshAnswer(cmd, "Can not ping System vm " - + vmName + "due to:" + result); - } - } catch (Exception e) { - return new CheckSshAnswer(cmd, e); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Ping command port succeeded for vm " + vmName); - } - - return new CheckSshAnswer(cmd); - } - - private boolean cleanupDisk(Connect conn, DiskDef disk) { - // need to umount secondary storage - String path = disk.getDiskPath(); - String poolUuid = null; - if (path != null) { - String[] token = path.split("/"); - if (token.length > 3) { - poolUuid = token[2]; - } - } - - if (poolUuid == null) { - return true; - } - - try { - KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid); - if (pool != null) { - pool.delete(); - } - return true; - } catch (CloudRuntimeException e) { - return false; - } - } - - protected synchronized String attachOrDetachISO(Connect conn, - String vmName, String isoPath, boolean isAttach) - throws LibvirtException, URISyntaxException, InternalErrorException { - String isoXml = null; - if (isoPath != null && isAttach) { - int index = isoPath.lastIndexOf("/"); - String path = isoPath.substring(0, index); - String name = isoPath.substring(index + 1); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(path); - KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); - isoPath = isoVol.getPath(); - - DiskDef iso = new DiskDef(); - iso.defISODisk(isoPath); - isoXml = iso.toString(); - } else { - DiskDef iso = new DiskDef(); - iso.defISODisk(null); - isoXml = iso.toString(); - } - - List disks = getDisks(conn, vmName); - String result = attachOrDetachDevice(conn, true, vmName, isoXml); - if (result == null && !isAttach) { - for (DiskDef disk : disks) { - if (disk.getDeviceType() == DiskDef.deviceType.CDROM) { - cleanupDisk(conn, disk); - } - } - - } - return result; - } - - protected synchronized String attachOrDetachDisk(Connect conn, - boolean attach, String vmName, KVMPhysicalDisk attachingDisk, - int devId) throws LibvirtException, InternalErrorException { - List disks = null; - Domain dm = null; - DiskDef diskdef = null; - try { - if (!attach) { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - String xml = dm.getXMLDesc(0); - parser.parseDomainXML(xml); - disks = parser.getDisks(); - - for (DiskDef disk : disks) { - String file = disk.getDiskPath(); - if (file != null - && file.equalsIgnoreCase(attachingDisk.getPath())) { - diskdef = disk; - break; - } - } - if (diskdef == null) { - throw new InternalErrorException("disk: " - + attachingDisk.getPath() - + " is not attached before"); - } - } else { - diskdef = new DiskDef(); - if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) { - diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, - DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2); - } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) { - diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, - DiskDef.diskBus.VIRTIO); - } - } - - String xml = diskdef.toString(); - return attachOrDetachDevice(conn, attach, vmName, xml); - } finally { - if (dm != null) { - dm.free(); - } - } - } - - protected synchronized String attachOrDetachDevice(Connect conn, - boolean attach, String vmName, String xml) throws LibvirtException, - InternalErrorException { - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName - .getBytes()))); - - if (attach) { - s_logger.debug("Attaching device: " + xml); - dm.attachDevice(xml); - } else { - s_logger.debug("Detaching device: " + xml); - dm.detachDevice(xml); - } - } catch (LibvirtException e) { - if (attach) { - s_logger.warn("Failed to attach device to " + vmName + ": " - + e.getMessage()); - } else { - s_logger.warn("Failed to detach device from " + vmName + ": " - + e.getMessage()); - } - throw e; - } catch (Exception e) { - throw new InternalErrorException(e.toString()); - } finally { - if (dm != null) { - try { - dm.free(); - } catch (LibvirtException l) { - - } - } - } - - return null; - } - - @Override - public PingCommand getCurrentStatus(long id) { - final HashMap newStates = sync(); - - if (!_can_bridge_firewall) { - return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, - newStates); - } else { - HashMap> nwGrpStates = syncNetworkGroups(id); - return new PingRoutingWithNwGroupsCommand(getType(), id, newStates, - nwGrpStates); - } - } - - @Override - public Type getType() { - return Type.Routing; - } - - private Map getVersionStrings() { - final Script command = new Script(_versionstringpath, _timeout, - s_logger); - KeyValueInterpreter kvi = new KeyValueInterpreter(); - String result = command.execute(kvi); - if (result == null) { - return kvi.getKeyValues(); - } else { - return new HashMap(1); - } - } - - @Override - public StartupCommand[] initialize() { - Map changes = null; - - synchronized (_vms) { - _vms.clear(); - changes = sync(); - } - - final List info = getHostInfo(); - - final StartupRoutingCommand cmd = new StartupRoutingCommand( - (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), - (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, - RouterPrivateIpStrategy.HostLocal); - cmd.setStateChanges(changes); - fillNetworkInformation(cmd); - _privateIp = cmd.getPrivateIpAddress(); - cmd.getHostDetails().putAll(getVersionStrings()); - cmd.setPool(_pool); - cmd.setCluster(_clusterId); - cmd.setGatewayIpAddress(_localGateway); - - StartupStorageCommand sscmd = null; - try { - - KVMStoragePool localStoragePool = _storagePoolMgr - .createStoragePool(_localStorageUUID, "localhost", - _localStoragePath, StoragePoolType.Filesystem); - com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo( - localStoragePool.getUuid(), cmd.getPrivateIpAddress(), - _localStoragePath, _localStoragePath, - StoragePoolType.Filesystem, localStoragePool.getCapacity(), - localStoragePool.getUsed()); - - sscmd = new StartupStorageCommand(); - sscmd.setPoolInfo(pi); - sscmd.setGuid(pi.getUuid()); - sscmd.setDataCenter(_dcId); - sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); - } catch (CloudRuntimeException e) { - - } - - if (sscmd != null) { - return new StartupCommand[] { cmd, sscmd }; - } else { - return new StartupCommand[] { cmd }; - } - } - - protected HashMap sync() { - HashMap newStates; - HashMap oldStates = null; - - final HashMap changes = new HashMap(); - - synchronized (_vms) { - newStates = getAllVms(); - if (newStates == null) { - s_logger.debug("Unable to get the vm states so no state sync at this point."); - return changes; - } - - oldStates = new HashMap(_vms.size()); - oldStates.putAll(_vms); - - for (final Map.Entry entry : newStates.entrySet()) { - final String vm = entry.getKey(); - - State newState = entry.getValue(); - final State oldState = oldStates.remove(vm); - - if (newState == State.Stopped && oldState != State.Stopping - && oldState != null && oldState != State.Stopped) { - newState = getRealPowerState(vm); - } - - if (s_logger.isTraceEnabled()) { - s_logger.trace("VM " + vm + ": libvirt has state " - + newState + " and we have state " - + (oldState != null ? oldState.toString() : "null")); - } - - if (vm.startsWith("migrating")) { - s_logger.debug("Migration detected. Skipping"); - continue; - } - if (oldState == null) { - _vms.put(vm, newState); - s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " - + vm); - changes.put(vm, newState); - } else if (oldState == State.Starting) { - if (newState == State.Running) { - _vms.put(vm, newState); - } else if (newState == State.Stopped) { - s_logger.debug("Ignoring vm " + vm - + " because of a lag in starting the vm."); - } - } else if (oldState == State.Migrating) { - if (newState == State.Running) { - s_logger.debug("Detected that an migrating VM is now running: " - + vm); - _vms.put(vm, newState); - } - } else if (oldState == State.Stopping) { - if (newState == State.Stopped) { - _vms.put(vm, newState); - } else if (newState == State.Running) { - s_logger.debug("Ignoring vm " + vm - + " because of a lag in stopping the vm. "); - } - } else if (oldState != newState) { - _vms.put(vm, newState); - if (newState == State.Stopped) { - if (_vmsKilled.remove(vm)) { - s_logger.debug("VM " + vm - + " has been killed for storage. "); - newState = State.Error; - } - } - changes.put(vm, newState); - } - } - - for (final Map.Entry entry : oldStates.entrySet()) { - final String vm = entry.getKey(); - final State oldState = entry.getValue(); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("VM " - + vm - + " is now missing from libvirt so reporting stopped"); - } - - if (oldState == State.Stopping) { - s_logger.debug("Ignoring VM " + vm - + " in transition state stopping."); - _vms.remove(vm); - } else if (oldState == State.Starting) { - s_logger.debug("Ignoring VM " + vm - + " in transition state starting."); - } else if (oldState == State.Stopped) { - _vms.remove(vm); - } else if (oldState == State.Migrating) { - s_logger.debug("Ignoring VM " + vm + " in migrating state."); - } else { - _vms.remove(vm); - State state = State.Stopped; - if (_vmsKilled.remove(entry.getKey())) { - s_logger.debug("VM " + vm - + " has been killed by storage monitor"); - state = State.Error; - } - changes.put(entry.getKey(), state); - } - } - } - - return changes; - } - - protected State getRealPowerState(String vm) { - int i = 0; - s_logger.trace("Checking on the HALTED State"); - Domain dm = null; - for (; i < 5; i++) { - try { - Connect conn = LibvirtConnection.getConnection(); - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm - .getBytes())); - DomainInfo.DomainState vps = dm.getInfo().state; - if (vps != null - && vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF - && vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) { - return convertToState(vps); - } - } catch (final LibvirtException e) { - s_logger.trace(e.getMessage()); - } catch (Exception e) { - s_logger.trace(e.getMessage()); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (final LibvirtException e) { - - } - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - return State.Stopped; - } - - protected List getAllVmNames(Connect conn) { - ArrayList la = new ArrayList(); - try { - final String names[] = conn.listDefinedDomains(); - for (int i = 0; i < names.length; i++) { - la.add(names[i]); - } - } catch (final LibvirtException e) { - s_logger.warn("Failed to list Defined domains", e); - } - - int[] ids = null; - try { - ids = conn.listDomains(); - } catch (final LibvirtException e) { - s_logger.warn("Failed to list domains", e); - return la; - } - - Domain dm = null; - for (int i = 0; i < ids.length; i++) { - try { - dm = conn.domainLookupByID(ids[i]); - la.add(dm.getName()); - } catch (final LibvirtException e) { - s_logger.warn("Unable to get vms", e); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (final LibvirtException e) { - - } - } - } - - return la; - } - - private HashMap getAllVms() { - final HashMap vmStates = new HashMap(); - - String[] vms = null; - int[] ids = null; - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - s_logger.debug("Failed to get connection: " + e.getMessage()); - return vmStates; - } - - try { - ids = conn.listDomains(); - } catch (final LibvirtException e) { - s_logger.warn("Unable to listDomains", e); - return null; - } - try { - vms = conn.listDefinedDomains(); - } catch (final LibvirtException e) { - s_logger.warn("Unable to listDomains", e); - return null; - } - - Domain dm = null; - for (int i = 0; i < ids.length; i++) { - try { - dm = conn.domainLookupByID(ids[i]); - - DomainInfo.DomainState ps = dm.getInfo().state; - - final State state = convertToState(ps); - - s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps - + "; vm state=" + state.toString()); - String vmName = dm.getName(); - vmStates.put(vmName, state); - } catch (final LibvirtException e) { - s_logger.warn("Unable to get vms", e); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - - } - } - } - - for (int i = 0; i < vms.length; i++) { - try { - - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i] - .getBytes())); - - DomainInfo.DomainState ps = dm.getInfo().state; - final State state = convertToState(ps); - String vmName = dm.getName(); - s_logger.trace("VM " + vmName + ": powerstate = " + ps - + "; vm state=" + state.toString()); - - vmStates.put(vmName, state); - } catch (final LibvirtException e) { - s_logger.warn("Unable to get vms", e); - } catch (Exception e) { - s_logger.warn("Unable to get vms", e); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - - } - } - } - - return vmStates; - } - - protected List getHostInfo() { - final ArrayList info = new ArrayList(); - long speed = 0; - long cpus = 0; - long ram = 0; - String cap = null; - try { - Connect conn = LibvirtConnection.getConnection(); - final NodeInfo hosts = conn.nodeInfo(); - boolean result = false; - try { - BufferedReader in = new BufferedReader( - new FileReader( - "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")); - speed = Long.parseLong(in.readLine()) / 1000; - result = true; - } catch (FileNotFoundException e) { - - } catch (IOException e) { - - } catch (NumberFormatException e) { - - } - - if (!result) { - speed = hosts.mhz; - } - - cpus = hosts.cpus; - ram = hosts.memory * 1024L; - LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); - parser.parseCapabilitiesXML(conn.getCapabilities()); - ArrayList oss = parser.getGuestOsType(); - for (String s : oss) { - /* - * Even host supports guest os type more than hvm, we only - * report hvm to management server - */ - if (s.equalsIgnoreCase("hvm")) { - cap = "hvm"; - } - } - } catch (LibvirtException e) { - - } - - if (isSnapshotSupported()) { - cap = cap + ",snapshot"; - } - - info.add((int) cpus); - info.add(speed); - info.add(ram); - info.add(cap); - long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum - // of 10% of - // system ram or - // 768M - dom0ram = Math.max(dom0ram, _dom0MinMem); - info.add(dom0ram); - s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram - + ", dom0ram=" + dom0ram); - - return info; - } - - protected void cleanupVM(Connect conn, final String vmName, - final String vnet) { - s_logger.debug("Trying to cleanup the vnet: " + vnet); - if (vnet != null) { - cleanupVnet(conn, vnet); - } - - _vmStats.remove(vmName); - } - - protected String rebootVM(Connect conn, String vmName) { - Domain dm = null; - String msg = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - String vmDef = dm.getXMLDesc(0); - s_logger.debug(vmDef); - msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM); - msg = startDomain(conn, vmName, vmDef); - return null; - } catch (LibvirtException e) { - s_logger.warn("Failed to create vm", e); - msg = e.getMessage(); - } catch (Exception e) { - s_logger.warn("Failed to create vm", e); - msg = e.getMessage(); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - - } - } - - return msg; - } - - protected String stopVM(Connect conn, String vmName, defineOps df) { - DomainInfo.DomainState state = null; - Domain dm = null; - - s_logger.debug("Try to stop the vm at first"); - String ret = stopVM(conn, vmName, false); - if (ret == Script.ERR_TIMEOUT) { - ret = stopVM(conn, vmName, true); - } else if (ret != null) { - /* - * There is a race condition between libvirt and qemu: libvirt - * listens on qemu's monitor fd. If qemu is shutdown, while libvirt - * is reading on the fd, then libvirt will report an error. - */ - /* Retry 3 times, to make sure we can get the vm's status */ - for (int i = 0; i < 3; i++) { - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - state = dm.getInfo().state; - break; - } catch (LibvirtException e) { - s_logger.debug("Failed to get vm status:" + e.getMessage()); - } catch (Exception e) { - s_logger.debug("Failed to get vm status:" + e.getMessage()); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException l) { - - } - } - } - - if (state == null) { - s_logger.debug("Can't get vm's status, assume it's dead already"); - return null; - } - - if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { - s_logger.debug("Try to destroy the vm"); - ret = stopVM(conn, vmName, true); - if (ret != null) { - return ret; - } - } - } - - if (df == defineOps.UNDEFINE_VM) { - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - dm.undefine(); - } catch (LibvirtException e) { - - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException l) { - - } - } - } - return null; - } - - protected String stopVM(Connect conn, String vmName, boolean force) { - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - if (force) { - if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { - dm.destroy(); - } - } else { - if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { - return null; - } - dm.shutdown(); - int retry = _stopTimeout / 2000; - /* Wait for the domain gets into shutoff state */ - while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) - && (retry >= 0)) { - Thread.sleep(2000); - retry--; - } - if (retry < 0) { - s_logger.warn("Timed out waiting for domain " + vmName - + " to shutdown gracefully"); - return Script.ERR_TIMEOUT; - } - } - } catch (LibvirtException e) { - s_logger.debug("Failed to stop VM :" + vmName + " :", e); - return e.getMessage(); - } catch (InterruptedException ie) { - s_logger.debug("Interrupted sleep"); - return ie.getMessage(); - } catch (Exception e) { - s_logger.debug("Failed to stop VM :" + vmName + " :", e); - return e.getMessage(); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - } - } - - return null; - } - - public synchronized String cleanupVnet(Connect conn, final String vnetId) { - // VNC proxy VMs do not have vnet - if (vnetId == null || vnetId.isEmpty() - || isDirectAttachedNetwork(vnetId)) { - return null; - } - - final List names = getAllVmNames(conn); - - if (!names.isEmpty()) { - for (final String name : names) { - if (VirtualMachineName.getVnet(name).equals(vnetId)) { - return null; // Can't remove the vnet yet. - } - } - } - - final Script command = new Script(_modifyVlanPath, _timeout, s_logger); - command.add("-o", "delete"); - command.add("-v", vnetId); - return command.execute(); - } - - protected Integer getVncPort(Connect conn, String vmName) - throws LibvirtException { - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - String xmlDesc = dm.getXMLDesc(0); - parser.parseDomainXML(xmlDesc); - return parser.getVncPort(); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException l) { - - } - } - } - - private boolean IsHVMEnabled(Connect conn) { - LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); - try { - parser.parseCapabilitiesXML(conn.getCapabilities()); - ArrayList osTypes = parser.getGuestOsType(); - for (String o : osTypes) { - if (o.equalsIgnoreCase("hvm")) { - return true; - } - } - } catch (LibvirtException e) { - - } - return false; - } - - private String getHypervisorPath(Connect conn) { - File f = new File("/usr/bin/cloud-qemu-kvm"); - if (f.exists()) { - return "/usr/bin/cloud-qemu-kvm"; - } else { - f = new File("/usr/libexec/cloud-qemu-kvm"); - if (f.exists()) { - return "/usr/libexec/cloud-qemu-kvm"; - } - - LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); - try { - parser.parseCapabilitiesXML(conn.getCapabilities()); - } catch (LibvirtException e) { - - } - return parser.getEmulator(); - } - } - - private String getGuestType(Connect conn, String vmName) { - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - String xmlDesc = dm.getXMLDesc(0); - parser.parseDomainXML(xmlDesc); - return parser.getDescription(); - } catch (LibvirtException e) { - return null; - } catch (Exception e) { - return null; - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException l) { - - } - } - } - - private boolean isGuestPVEnabled(String guestOS) { - if (guestOS == null) { - return false; - } - String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS); - if (guestOS.startsWith("Ubuntu") - || guestOSName.startsWith("Fedora 13") - || guestOSName.startsWith("Fedora 12") - || guestOSName.startsWith("Fedora 11") - || guestOSName.startsWith("Fedora 10") - || guestOSName.startsWith("Fedora 9") - || guestOSName.startsWith("CentOS 5.3") - || guestOSName.startsWith("CentOS 5.4") - || guestOSName.startsWith("CentOS 5.5") - || guestOS.startsWith("CentOS") - || guestOS.startsWith("Fedora") - || guestOSName.startsWith("Red Hat Enterprise Linux 5.3") - || guestOSName.startsWith("Red Hat Enterprise Linux 5.4") - || guestOSName.startsWith("Red Hat Enterprise Linux 5.5") - || guestOSName.startsWith("Red Hat Enterprise Linux 6") - || guestOS.startsWith("Debian GNU/Linux") - || guestOSName.startsWith("Other PV")) { - return true; - } else { - return false; - } - } - - public boolean isCentosHost() { - if (_hvVersion <= 9) { - return true; - } else { - return false; - } - } - - private InterfaceDef.nicModel getGuestNicModel(String guestOSType) { - if (isGuestPVEnabled(guestOSType)) { - return InterfaceDef.nicModel.VIRTIO; - } else { - return InterfaceDef.nicModel.E1000; - } - } - - private DiskDef.diskBus getGuestDiskModel(String guestOSType) { - if (isGuestPVEnabled(guestOSType)) { - return DiskDef.diskBus.VIRTIO; - } else { - return DiskDef.diskBus.IDE; - } - } - - private String setVnetBrName(String vnetId) { - return "cloudVirBr" + vnetId; - } - - private String getVnetIdFromBrName(String vnetBrName) { - return vnetBrName.replaceAll("cloudVirBr", ""); - } - - private void cleanupVMNetworks(Connect conn, List nics) { - for (InterfaceDef nic : nics) { - if (nic.getHostNetType() == hostNicType.VNET) { - cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName())); - } - } - } - - private Domain getDomain(Connect conn, String vmName) - throws LibvirtException { - return conn - .domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes())); - } - - protected List getInterfaces(Connect conn, String vmName) { - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - parser.parseDomainXML(dm.getXMLDesc(0)); - return parser.getInterfaces(); - - } catch (LibvirtException e) { - s_logger.debug("Failed to get dom xml: " + e.toString()); - return new ArrayList(); - } catch (Exception e) { - s_logger.debug("Failed to get dom xml: " + e.toString()); - return new ArrayList(); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - - } - } - } - - protected List getDisks(Connect conn, String vmName) { - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - Domain dm = null; - try { - dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName - .getBytes())); - parser.parseDomainXML(dm.getXMLDesc(0)); - return parser.getDisks(); - - } catch (LibvirtException e) { - s_logger.debug("Failed to get dom xml: " + e.toString()); - return new ArrayList(); - } catch (Exception e) { - s_logger.debug("Failed to get dom xml: " + e.toString()); - return new ArrayList(); - } finally { - try { - if (dm != null) { - dm.free(); - } - } catch (LibvirtException e) { - - } - } - } - - private String executeBashScript(String script) { - Script command = new Script("/bin/bash", _timeout, s_logger); - command.add("-c"); - command.add(script); - return command.execute(); - } - - private String executeBashScript(String script, OutputInterpreter parser) { - Script command = new Script("/bin/bash", _timeout, s_logger); - command.add("-c"); - command.add(script); - return command.execute(parser); - } - - private void deletExitingLinkLocalRoutTable(String linkLocalBr) { - Script command = new Script("/bin/bash", _timeout); - command.add("-c"); - command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); - OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); - String result = command.execute(parser); - boolean foundLinkLocalBr = false; - if (result == null && parser.getLines() != null) { - String[] lines = parser.getLines().split("\\n"); - for (String line : lines) { - String[] tokens = line.split(" "); - if (!tokens[2].equalsIgnoreCase(linkLocalBr)) { - Script.runSimpleBashScript("ip route del " - + NetUtils.getLinkLocalCIDR()); - } else { - foundLinkLocalBr = true; - } - } - } - if (!foundLinkLocalBr) { - Script.runSimpleBashScript("ip route add " - + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr - + " src " + NetUtils.getLinkLocalGateway()); - } - } - - private class vmStats { - long _usedTime; - long _tx; - long _rx; - Calendar _timestamp; - } - - private VmStatsEntry getVmStat(Connect conn, String vmName) - throws LibvirtException { - Domain dm = null; - try { - dm = getDomain(conn, vmName); - DomainInfo info = dm.getInfo(); - - VmStatsEntry stats = new VmStatsEntry(); - stats.setNumCPUs(info.nrVirtCpu); - stats.setEntityType("vm"); - - /* get cpu utilization */ - vmStats oldStats = null; - - Calendar now = Calendar.getInstance(); - - oldStats = _vmStats.get(vmName); - - long elapsedTime = 0; - if (oldStats != null) { - elapsedTime = now.getTimeInMillis() - - oldStats._timestamp.getTimeInMillis(); - double utilization = (info.cpuTime - oldStats._usedTime) - / ((double) elapsedTime * 1000000); - - NodeInfo node = conn.nodeInfo(); - utilization = utilization / node.cpus; - stats.setCPUUtilization(utilization * 100); - } - - /* get network stats */ - - List vifs = getInterfaces(conn, vmName); - long rx = 0; - long tx = 0; - for (InterfaceDef vif : vifs) { - DomainInterfaceStats ifStats = dm.interfaceStats(vif - .getDevName()); - rx += ifStats.rx_bytes; - tx += ifStats.tx_bytes; - } - - if (oldStats != null) { - long deltarx = rx - oldStats._rx; - if (deltarx > 0) - stats.setNetworkReadKBs(deltarx / 1000); - long deltatx = tx - oldStats._tx; - if (deltatx > 0) - stats.setNetworkWriteKBs(deltatx / 1000); - } - - vmStats newStat = new vmStats(); - newStat._usedTime = info.cpuTime; - newStat._rx = rx; - newStat._tx = tx; - newStat._timestamp = now; - _vmStats.put(vmName, newStat); - return stats; - } finally { - if (dm != null) { - dm.free(); - } - } - } - - private boolean can_bridge_firewall(String prvNic) { - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("can_bridge_firewall"); - cmd.add(prvNic); - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) { - if (!_can_bridge_firewall) { - return false; - } - String vif = null; - List intfs = getInterfaces(conn, vmName); - if (intfs.size() > 0) { - InterfaceDef intf = intfs.get(0); - vif = intf.getDevName(); - } - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("destroy_network_rules_for_vm"); - cmd.add("--vmname", vmName); - if (vif != null) { - cmd.add("--vif", vif); - } - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - protected boolean default_network_rules(Connect conn, String vmName, - NicTO nic, Long vmId) { - if (!_can_bridge_firewall) { - return false; - } - - List intfs = getInterfaces(conn, vmName); - if (intfs.size() < nic.getDeviceId()) { - return false; - } - - InterfaceDef intf = intfs.get(nic.getDeviceId()); - String brname = intf.getBrName(); - String vif = intf.getDevName(); - - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("default_network_rules"); - cmd.add("--vmname", vmName); - cmd.add("--vmid", vmId.toString()); - if (nic.getIp() != null) { - cmd.add("--vmip", nic.getIp()); - } - cmd.add("--vmmac", nic.getMac()); - cmd.add("--vif", vif); - cmd.add("--brname", brname); - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - protected boolean post_default_network_rules(Connect conn, String vmName, - NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp, - String hostMacAddr) { - if (!_can_bridge_firewall) { - return false; - } - - List intfs = getInterfaces(conn, vmName); - if (intfs.size() < nic.getDeviceId()) { - return false; - } - - InterfaceDef intf = intfs.get(nic.getDeviceId()); - String brname = intf.getBrName(); - String vif = intf.getDevName(); - - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("post_default_network_rules"); - cmd.add("--vmname", vmName); - cmd.add("--vmid", vmId.toString()); - cmd.add("--vmip", nic.getIp()); - cmd.add("--vmmac", nic.getMac()); - cmd.add("--vif", vif); - cmd.add("--brname", brname); - if (dhcpServerIp != null) - cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress()); - - cmd.add("--hostIp", hostIp); - cmd.add("--hostMacAddr", hostMacAddr); - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - protected boolean default_network_rules_for_systemvm(Connect conn, - String vmName) { - if (!_can_bridge_firewall) { - return false; - } - - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("default_network_rules_systemvm"); - cmd.add("--vmname", vmName); - cmd.add("--localbrname", _linkLocalBridgeName); - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - private boolean add_network_rules(String vmName, String vmId, - String guestIP, String sig, String seq, String mac, String rules, - String vif, String brname) { - if (!_can_bridge_firewall) { - return false; - } - - String newRules = rules.replace(" ", ";"); - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("add_network_rules"); - cmd.add("--vmname", vmName); - cmd.add("--vmid", vmId); - cmd.add("--vmip", guestIP); - cmd.add("--sig", sig); - cmd.add("--seq", seq); - cmd.add("--vmmac", mac); - cmd.add("--vif", vif); - cmd.add("--brname", brname); - if (rules != null) { - cmd.add("--rules", newRules); - } - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - private boolean cleanup_rules() { - if (!_can_bridge_firewall) { - return false; - } - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("cleanup_rules"); - String result = cmd.execute(); - if (result != null) { - return false; - } - return true; - } - - private String get_rule_logs_for_vms() { - Script cmd = new Script(_securityGroupPath, _timeout, s_logger); - cmd.add("get_rule_logs_for_vms"); - OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - String result = cmd.execute(parser); - if (result == null) { - return parser.getLine(); - } - return null; - } - - private HashMap> syncNetworkGroups(long id) { - HashMap> states = new HashMap>(); - - String result = get_rule_logs_for_vms(); - s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); - String[] rulelogs = result != null ? result.split(";") : new String[0]; - for (String rulesforvm : rulelogs) { - String[] log = rulesforvm.split(","); - if (log.length != 6) { - continue; - } - try { - states.put(log[0], new Pair(Long.parseLong(log[1]), - Long.parseLong(log[5]))); - } catch (NumberFormatException nfe) { - states.put(log[0], new Pair(-1L, -1L)); - } - } - return states; - } - - /* online snapshot supported by enhanced qemu-kvm */ - private boolean isSnapshotSupported() { - String result = executeBashScript("qemu-img --help|grep convert |grep snapshot"); - if (result != null) { - return false; - } else { - return true; - } - } - - private Pair getNicStats(String nicName) { - double rx = 0.0; - OutputInterpreter.OneLineParser rxParser = new OutputInterpreter.OneLineParser(); - String result = executeBashScript("cat /sys/class/net/" + nicName - + "/statistics/rx_bytes", rxParser); - if (result == null && rxParser.getLine() != null) { - rx = Double.parseDouble(rxParser.getLine()); - } - - double tx = 0.0; - OutputInterpreter.OneLineParser txParser = new OutputInterpreter.OneLineParser(); - result = executeBashScript("cat /sys/class/net/" + nicName - + "/statistics/tx_bytes", txParser); - if (result == null && txParser.getLine() != null) { - tx = Double.parseDouble(txParser.getLine()); - } - - return new Pair(rx, tx); - } - - private void createControlNetwork(Connect conn) throws LibvirtException { - _virtRouterResource.createControlNetwork(_linkLocalBridgeName); - } - - private Answer execute(NetworkRulesSystemVmCommand cmd) { - boolean success = false; - Connect conn; - try { - conn = LibvirtConnection.getConnection(); - success = default_network_rules_for_systemvm(conn, cmd.getVmName()); - } catch (LibvirtException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return new Answer(cmd, success, ""); - } + String vmName = vmSpec.getName(); + LibvirtVMDef vm = null; + + State state = State.Stopped; + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + synchronized (_vms) { + _vms.put(vmName, State.Starting); + } + + vm = createVMFromSpec(vmSpec); + + createVbd(conn, vmSpec, vmName, vm); + + createVifs(conn, vmSpec, vm); + + s_logger.debug("starting " + vmName + ": " + vm.toString()); + startDomain(conn, vmName, vm.toString()); + Script.runSimpleBashScript("virsh schedinfo " + vmName + + " --set cpu_shares=" + vmSpec.getCpus() + * vmSpec.getSpeed()); + + NicTO[] nics = vmSpec.getNics(); + for (NicTO nic : nics) { + if (nic.getIsolationUri() != null + && nic.getIsolationUri().getScheme() + .equalsIgnoreCase(IsolationType.Ec2.toString())) { + if (vmSpec.getType() != VirtualMachine.Type.User) { + default_network_rules_for_systemvm(conn, vmName); + break; + } else { + default_network_rules(conn, vmName, nic, vmSpec.getId()); + } + } + } + + state = State.Running; + return new StartAnswer(cmd); + } catch (Exception e) { + s_logger.warn("Exception ", e); + if (conn != null) { + handleVmStartFailure(conn, vmName, vm); + } + return new StartAnswer(cmd, e.getMessage()); + } finally { + synchronized (_vms) { + if (state != State.Stopped) { + _vms.put(vmName, state); + } else { + _vms.remove(vmName); + } + } + } + } + + private String getVolumePath(Connect conn, VolumeTO volume) + throws LibvirtException, URISyntaxException { + if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) { + String isoPath = volume.getPath(); + int index = isoPath.lastIndexOf("/"); + String path = isoPath.substring(0, index); + String name = isoPath.substring(index + 1); + KVMStoragePool secondaryPool = _storagePoolMgr + .getStoragePoolByURI(path); + KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); + return isoVol.getPath(); + } else { + return volume.getPath(); + } + } + + protected void createVbd(Connect conn, VirtualMachineTO vmSpec, + String vmName, LibvirtVMDef vm) throws InternalErrorException, + LibvirtException, URISyntaxException { + List disks = Arrays.asList(vmSpec.getDisks()); + Collections.sort(disks, new Comparator() { + @Override + public int compare(VolumeTO arg0, VolumeTO arg1) { + return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1; + } + }); + + for (VolumeTO volume : disks) { + KVMPhysicalDisk physicalDisk = null; + KVMStoragePool pool = null; + if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) { + String volPath = volume.getPath(); + int index = volPath.lastIndexOf("/"); + String volDir = volPath.substring(0, index); + String volName = volPath.substring(index + 1); + KVMStoragePool secondaryStorage = _storagePoolMgr + .getStoragePoolByURI(volDir); + physicalDisk = secondaryStorage.getPhysicalDisk(volName); + } else if (volume.getType() != Volume.Type.ISO) { + pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid()); + physicalDisk = pool.getPhysicalDisk(volume.getPath()); + } + + String volPath = null; + if (physicalDisk != null) { + volPath = physicalDisk.getPath(); + } + + DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs()); + DiskDef disk = new DiskDef(); + if (volume.getType() == Volume.Type.ISO) { + if (volPath == null) { + /* Add iso as placeholder */ + disk.defISODisk(null); + } else { + disk.defISODisk(volPath); + } + } else { + int devId = (int) volume.getDeviceId(); + + if (volume.getType() == Volume.Type.DATADISK) { + disk.defFileBasedDisk(physicalDisk.getPath(), devId, + DiskDef.diskBus.VIRTIO, + DiskDef.diskFmtType.QCOW2); + } else { + disk.defFileBasedDisk(physicalDisk.getPath(), devId, + diskBusType, DiskDef.diskFmtType.QCOW2); + } + + } + + vm.getDevices().addDevice(disk); + } + + if (vmSpec.getType() != VirtualMachine.Type.User) { + if (_sysvmISOPath != null) { + DiskDef iso = new DiskDef(); + iso.defISODisk(_sysvmISOPath); + vm.getDevices().addDevice(iso); + } + + createPatchVbd(conn, vmName, vm, vmSpec); + } + } + + private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) { + VolumeTO volumes[] = vmSpec.getDisks(); + for (VolumeTO volume : volumes) { + if (volume.getType() == type) { + return volume; + } + } + return null; + } + + private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm, + VirtualMachineTO vmSpec) throws LibvirtException, + InternalErrorException { + + List disks = vm.getDevices().getDisks(); + DiskDef rootDisk = disks.get(0); + VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT); + KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol + .getPoolUuid()); + KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID() + .toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW, + 10L * 1024 * 1024); + /* Format/create fs on this disk */ + final Script command = new Script(_createvmPath, _timeout, s_logger); + command.add("-f", disk.getPath()); + String result = command.execute(); + if (result != null) { + s_logger.debug("Failed to create data disk: " + result); + throw new InternalErrorException("Failed to create data disk: " + + result); + } + String datadiskPath = disk.getPath(); + + /* add patch disk */ + DiskDef patchDisk = new DiskDef(); + + patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(), + DiskDef.diskFmtType.RAW); + + disks.add(patchDisk); + + String bootArgs = vmSpec.getBootArgs(); + + patchSystemVm(bootArgs, datadiskPath, vmName); + } + + private String createVlanBr(String vlanId, String nic) + throws InternalErrorException { + String brName = setVnetBrName(vlanId); + createVnet(vlanId, nic); + return brName; + } + + private InterfaceDef createVif(Connect conn, NicTO nic, + InterfaceDef.nicModel model) throws InternalErrorException, + LibvirtException { + InterfaceDef intf = new InterfaceDef(); + + String vlanId = null; + if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { + URI broadcastUri = nic.getBroadcastUri(); + vlanId = broadcastUri.getHost(); + } + + if (nic.getType() == TrafficType.Guest) { + if (nic.getBroadcastType() == BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + String brName = createVlanBr(vlanId, _pifs.first()); + intf.defBridgeNet(brName, null, nic.getMac(), model); + } else { + intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model); + } + } else if (nic.getType() == TrafficType.Control) { + /* Make sure the network is still there */ + createControlNetwork(conn); + intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model); + } else if (nic.getType() == TrafficType.Public) { + if (nic.getBroadcastType() == BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + String brName = createVlanBr(vlanId, _pifs.second()); + intf.defBridgeNet(brName, null, nic.getMac(), model); + } else { + intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model); + } + } else if (nic.getType() == TrafficType.Management) { + intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model); + } else if (nic.getType() == TrafficType.Storage) { + String storageBrName = nic.getName() == null ? _privBridgeName + : nic.getName(); + intf.defBridgeNet(storageBrName, null, nic.getMac(), model); + } + + return intf; + } + + private void createVif(Connect conn, LibvirtVMDef vm, NicTO nic) + throws InternalErrorException, LibvirtException { + vm.getDevices().addDevice( + createVif(conn, nic, getGuestNicModel(vm.getGuestOSType()))); + } + + protected CheckSshAnswer execute(CheckSshCommand cmd) { + String vmName = cmd.getName(); + String privateIp = cmd.getIp(); + int cmdPort = cmd.getPort(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); + } + + try { + String result = _virtRouterResource.connect(privateIp, cmdPort); + if (result != null) { + return new CheckSshAnswer(cmd, "Can not ping System vm " + + vmName + "due to:" + result); + } + } catch (Exception e) { + return new CheckSshAnswer(cmd, e); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port succeeded for vm " + vmName); + } + + return new CheckSshAnswer(cmd); + } + + private boolean cleanupDisk(Connect conn, DiskDef disk) { + // need to umount secondary storage + String path = disk.getDiskPath(); + String poolUuid = null; + if (path != null) { + String[] token = path.split("/"); + if (token.length > 3) { + poolUuid = token[2]; + } + } + + if (poolUuid == null) { + return true; + } + + try { + KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid); + if (pool != null) { + pool.delete(); + } + return true; + } catch (CloudRuntimeException e) { + return false; + } + } + + protected synchronized String attachOrDetachISO(Connect conn, + String vmName, String isoPath, boolean isAttach) + throws LibvirtException, URISyntaxException, InternalErrorException { + String isoXml = null; + if (isoPath != null && isAttach) { + int index = isoPath.lastIndexOf("/"); + String path = isoPath.substring(0, index); + String name = isoPath.substring(index + 1); + KVMStoragePool secondaryPool = _storagePoolMgr + .getStoragePoolByURI(path); + KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); + isoPath = isoVol.getPath(); + + DiskDef iso = new DiskDef(); + iso.defISODisk(isoPath); + isoXml = iso.toString(); + } else { + DiskDef iso = new DiskDef(); + iso.defISODisk(null); + isoXml = iso.toString(); + } + + List disks = getDisks(conn, vmName); + String result = attachOrDetachDevice(conn, true, vmName, isoXml); + if (result == null && !isAttach) { + for (DiskDef disk : disks) { + if (disk.getDeviceType() == DiskDef.deviceType.CDROM) { + cleanupDisk(conn, disk); + } + } + + } + return result; + } + + protected synchronized String attachOrDetachDisk(Connect conn, + boolean attach, String vmName, KVMPhysicalDisk attachingDisk, + int devId) throws LibvirtException, InternalErrorException { + List disks = null; + Domain dm = null; + DiskDef diskdef = null; + try { + if (!attach) { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + String xml = dm.getXMLDesc(0); + parser.parseDomainXML(xml); + disks = parser.getDisks(); + + for (DiskDef disk : disks) { + String file = disk.getDiskPath(); + if (file != null + && file.equalsIgnoreCase(attachingDisk.getPath())) { + diskdef = disk; + break; + } + } + if (diskdef == null) { + throw new InternalErrorException("disk: " + + attachingDisk.getPath() + + " is not attached before"); + } + } else { + diskdef = new DiskDef(); + if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) { + diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, + DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2); + } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) { + diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, + DiskDef.diskBus.VIRTIO); + } + } + + String xml = diskdef.toString(); + return attachOrDetachDevice(conn, attach, vmName, xml); + } finally { + if (dm != null) { + dm.free(); + } + } + } + + protected synchronized String attachOrDetachDevice(Connect conn, + boolean attach, String vmName, String xml) throws LibvirtException, + InternalErrorException { + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName + .getBytes()))); + + if (attach) { + s_logger.debug("Attaching device: " + xml); + dm.attachDevice(xml); + } else { + s_logger.debug("Detaching device: " + xml); + dm.detachDevice(xml); + } + } catch (LibvirtException e) { + if (attach) { + s_logger.warn("Failed to attach device to " + vmName + ": " + + e.getMessage()); + } else { + s_logger.warn("Failed to detach device from " + vmName + ": " + + e.getMessage()); + } + throw e; + } catch (Exception e) { + throw new InternalErrorException(e.toString()); + } finally { + if (dm != null) { + try { + dm.free(); + } catch (LibvirtException l) { + + } + } + } + + return null; + } + + @Override + public PingCommand getCurrentStatus(long id) { + final HashMap newStates = sync(); + + if (!_can_bridge_firewall) { + return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, + newStates); + } else { + HashMap> nwGrpStates = syncNetworkGroups(id); + return new PingRoutingWithNwGroupsCommand(getType(), id, newStates, + nwGrpStates); + } + } + + @Override + public Type getType() { + return Type.Routing; + } + + private Map getVersionStrings() { + final Script command = new Script(_versionstringpath, _timeout, + s_logger); + KeyValueInterpreter kvi = new KeyValueInterpreter(); + String result = command.execute(kvi); + if (result == null) { + return kvi.getKeyValues(); + } else { + return new HashMap(1); + } + } + + @Override + public StartupCommand[] initialize() { + Map changes = null; + + synchronized (_vms) { + _vms.clear(); + changes = sync(); + } + + final List info = getHostInfo(); + + final StartupRoutingCommand cmd = new StartupRoutingCommand( + (Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), + (Long) info.get(4), (String) info.get(3), HypervisorType.KVM, + RouterPrivateIpStrategy.HostLocal); + cmd.setStateChanges(changes); + fillNetworkInformation(cmd); + _privateIp = cmd.getPrivateIpAddress(); + cmd.getHostDetails().putAll(getVersionStrings()); + cmd.setPool(_pool); + cmd.setCluster(_clusterId); + cmd.setGatewayIpAddress(_localGateway); + + StartupStorageCommand sscmd = null; + try { + + KVMStoragePool localStoragePool = _storagePoolMgr + .createStoragePool(_localStorageUUID, "localhost", + _localStoragePath, StoragePoolType.Filesystem); + com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo( + localStoragePool.getUuid(), cmd.getPrivateIpAddress(), + _localStoragePath, _localStoragePath, + StoragePoolType.Filesystem, localStoragePool.getCapacity(), + localStoragePool.getUsed()); + + sscmd = new StartupStorageCommand(); + sscmd.setPoolInfo(pi); + sscmd.setGuid(pi.getUuid()); + sscmd.setDataCenter(_dcId); + sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); + } catch (CloudRuntimeException e) { + + } + + if (sscmd != null) { + return new StartupCommand[] { cmd, sscmd }; + } else { + return new StartupCommand[] { cmd }; + } + } + + protected HashMap sync() { + HashMap newStates; + HashMap oldStates = null; + + final HashMap changes = new HashMap(); + + synchronized (_vms) { + newStates = getAllVms(); + if (newStates == null) { + s_logger.debug("Unable to get the vm states so no state sync at this point."); + return changes; + } + + oldStates = new HashMap(_vms.size()); + oldStates.putAll(_vms); + + for (final Map.Entry entry : newStates.entrySet()) { + final String vm = entry.getKey(); + + State newState = entry.getValue(); + final State oldState = oldStates.remove(vm); + + if (newState == State.Stopped && oldState != State.Stopping + && oldState != null && oldState != State.Stopped) { + newState = getRealPowerState(vm); + } + + if (s_logger.isTraceEnabled()) { + s_logger.trace("VM " + vm + ": libvirt has state " + + newState + " and we have state " + + (oldState != null ? oldState.toString() : "null")); + } + + if (vm.startsWith("migrating")) { + s_logger.debug("Migration detected. Skipping"); + continue; + } + if (oldState == null) { + _vms.put(vm, newState); + s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + + vm); + changes.put(vm, newState); + } else if (oldState == State.Starting) { + if (newState == State.Running) { + _vms.put(vm, newState); + } else if (newState == State.Stopped) { + s_logger.debug("Ignoring vm " + vm + + " because of a lag in starting the vm."); + } + } else if (oldState == State.Migrating) { + if (newState == State.Running) { + s_logger.debug("Detected that an migrating VM is now running: " + + vm); + _vms.put(vm, newState); + } + } else if (oldState == State.Stopping) { + if (newState == State.Stopped) { + _vms.put(vm, newState); + } else if (newState == State.Running) { + s_logger.debug("Ignoring vm " + vm + + " because of a lag in stopping the vm. "); + } + } else if (oldState != newState) { + _vms.put(vm, newState); + if (newState == State.Stopped) { + if (_vmsKilled.remove(vm)) { + s_logger.debug("VM " + vm + + " has been killed for storage. "); + newState = State.Error; + } + } + changes.put(vm, newState); + } + } + + for (final Map.Entry entry : oldStates.entrySet()) { + final String vm = entry.getKey(); + final State oldState = entry.getValue(); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("VM " + + vm + + " is now missing from libvirt so reporting stopped"); + } + + if (oldState == State.Stopping) { + s_logger.debug("Ignoring VM " + vm + + " in transition state stopping."); + _vms.remove(vm); + } else if (oldState == State.Starting) { + s_logger.debug("Ignoring VM " + vm + + " in transition state starting."); + } else if (oldState == State.Stopped) { + _vms.remove(vm); + } else if (oldState == State.Migrating) { + s_logger.debug("Ignoring VM " + vm + " in migrating state."); + } else { + _vms.remove(vm); + State state = State.Stopped; + if (_vmsKilled.remove(entry.getKey())) { + s_logger.debug("VM " + vm + + " has been killed by storage monitor"); + state = State.Error; + } + changes.put(entry.getKey(), state); + } + } + } + + return changes; + } + + protected State getRealPowerState(String vm) { + int i = 0; + s_logger.trace("Checking on the HALTED State"); + Domain dm = null; + for (; i < 5; i++) { + try { + Connect conn = LibvirtConnection.getConnection(); + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm + .getBytes())); + DomainInfo.DomainState vps = dm.getInfo().state; + if (vps != null + && vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF + && vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) { + return convertToState(vps); + } + } catch (final LibvirtException e) { + s_logger.trace(e.getMessage()); + } catch (Exception e) { + s_logger.trace(e.getMessage()); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (final LibvirtException e) { + + } + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + return State.Stopped; + } + + protected List getAllVmNames(Connect conn) { + ArrayList la = new ArrayList(); + try { + final String names[] = conn.listDefinedDomains(); + for (int i = 0; i < names.length; i++) { + la.add(names[i]); + } + } catch (final LibvirtException e) { + s_logger.warn("Failed to list Defined domains", e); + } + + int[] ids = null; + try { + ids = conn.listDomains(); + } catch (final LibvirtException e) { + s_logger.warn("Failed to list domains", e); + return la; + } + + Domain dm = null; + for (int i = 0; i < ids.length; i++) { + try { + dm = conn.domainLookupByID(ids[i]); + la.add(dm.getName()); + } catch (final LibvirtException e) { + s_logger.warn("Unable to get vms", e); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (final LibvirtException e) { + + } + } + } + + return la; + } + + private HashMap getAllVms() { + final HashMap vmStates = new HashMap(); + + String[] vms = null; + int[] ids = null; + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + } catch (LibvirtException e) { + s_logger.debug("Failed to get connection: " + e.getMessage()); + return vmStates; + } + + try { + ids = conn.listDomains(); + } catch (final LibvirtException e) { + s_logger.warn("Unable to listDomains", e); + return null; + } + try { + vms = conn.listDefinedDomains(); + } catch (final LibvirtException e) { + s_logger.warn("Unable to listDomains", e); + return null; + } + + Domain dm = null; + for (int i = 0; i < ids.length; i++) { + try { + dm = conn.domainLookupByID(ids[i]); + + DomainInfo.DomainState ps = dm.getInfo().state; + + final State state = convertToState(ps); + + s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps + + "; vm state=" + state.toString()); + String vmName = dm.getName(); + vmStates.put(vmName, state); + } catch (final LibvirtException e) { + s_logger.warn("Unable to get vms", e); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + + } + } + } + + for (int i = 0; i < vms.length; i++) { + try { + + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i] + .getBytes())); + + DomainInfo.DomainState ps = dm.getInfo().state; + final State state = convertToState(ps); + String vmName = dm.getName(); + s_logger.trace("VM " + vmName + ": powerstate = " + ps + + "; vm state=" + state.toString()); + + vmStates.put(vmName, state); + } catch (final LibvirtException e) { + s_logger.warn("Unable to get vms", e); + } catch (Exception e) { + s_logger.warn("Unable to get vms", e); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + + } + } + } + + return vmStates; + } + + protected List getHostInfo() { + final ArrayList info = new ArrayList(); + long speed = 0; + long cpus = 0; + long ram = 0; + String cap = null; + try { + Connect conn = LibvirtConnection.getConnection(); + final NodeInfo hosts = conn.nodeInfo(); + boolean result = false; + try { + BufferedReader in = new BufferedReader( + new FileReader( + "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")); + speed = Long.parseLong(in.readLine()) / 1000; + result = true; + } catch (FileNotFoundException e) { + + } catch (IOException e) { + + } catch (NumberFormatException e) { + + } + + if (!result) { + speed = hosts.mhz; + } + + cpus = hosts.cpus; + ram = hosts.memory * 1024L; + LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); + parser.parseCapabilitiesXML(conn.getCapabilities()); + ArrayList oss = parser.getGuestOsType(); + for (String s : oss) { + /* + * Even host supports guest os type more than hvm, we only + * report hvm to management server + */ + if (s.equalsIgnoreCase("hvm")) { + cap = "hvm"; + } + } + } catch (LibvirtException e) { + + } + + if (isSnapshotSupported()) { + cap = cap + ",snapshot"; + } + + info.add((int) cpus); + info.add(speed); + info.add(ram); + info.add(cap); + long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum + // of 10% of + // system ram or + // 768M + dom0ram = Math.max(dom0ram, _dom0MinMem); + info.add(dom0ram); + s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram + + ", dom0ram=" + dom0ram); + + return info; + } + + protected void cleanupVM(Connect conn, final String vmName, + final String vnet) { + s_logger.debug("Trying to cleanup the vnet: " + vnet); + if (vnet != null) { + cleanupVnet(conn, vnet); + } + + _vmStats.remove(vmName); + } + + protected String rebootVM(Connect conn, String vmName) { + Domain dm = null; + String msg = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + String vmDef = dm.getXMLDesc(0); + s_logger.debug(vmDef); + msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM); + msg = startDomain(conn, vmName, vmDef); + return null; + } catch (LibvirtException e) { + s_logger.warn("Failed to create vm", e); + msg = e.getMessage(); + } catch (Exception e) { + s_logger.warn("Failed to create vm", e); + msg = e.getMessage(); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + + } + } + + return msg; + } + + protected String stopVM(Connect conn, String vmName, defineOps df) { + DomainInfo.DomainState state = null; + Domain dm = null; + + s_logger.debug("Try to stop the vm at first"); + String ret = stopVM(conn, vmName, false); + if (ret == Script.ERR_TIMEOUT) { + ret = stopVM(conn, vmName, true); + } else if (ret != null) { + /* + * There is a race condition between libvirt and qemu: libvirt + * listens on qemu's monitor fd. If qemu is shutdown, while libvirt + * is reading on the fd, then libvirt will report an error. + */ + /* Retry 3 times, to make sure we can get the vm's status */ + for (int i = 0; i < 3; i++) { + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + state = dm.getInfo().state; + break; + } catch (LibvirtException e) { + s_logger.debug("Failed to get vm status:" + e.getMessage()); + } catch (Exception e) { + s_logger.debug("Failed to get vm status:" + e.getMessage()); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException l) { + + } + } + } + + if (state == null) { + s_logger.debug("Can't get vm's status, assume it's dead already"); + return null; + } + + if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { + s_logger.debug("Try to destroy the vm"); + ret = stopVM(conn, vmName, true); + if (ret != null) { + return ret; + } + } + } + + if (df == defineOps.UNDEFINE_VM) { + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + dm.undefine(); + } catch (LibvirtException e) { + + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException l) { + + } + } + } + return null; + } + + protected String stopVM(Connect conn, String vmName, boolean force) { + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + if (force) { + if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { + dm.destroy(); + } + } else { + if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) { + return null; + } + dm.shutdown(); + int retry = _stopTimeout / 2000; + /* Wait for the domain gets into shutoff state */ + while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) + && (retry >= 0)) { + Thread.sleep(2000); + retry--; + } + if (retry < 0) { + s_logger.warn("Timed out waiting for domain " + vmName + + " to shutdown gracefully"); + return Script.ERR_TIMEOUT; + } + } + } catch (LibvirtException e) { + s_logger.debug("Failed to stop VM :" + vmName + " :", e); + return e.getMessage(); + } catch (InterruptedException ie) { + s_logger.debug("Interrupted sleep"); + return ie.getMessage(); + } catch (Exception e) { + s_logger.debug("Failed to stop VM :" + vmName + " :", e); + return e.getMessage(); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + } + } + + return null; + } + + public synchronized String cleanupVnet(Connect conn, final String vnetId) { + // VNC proxy VMs do not have vnet + if (vnetId == null || vnetId.isEmpty() + || isDirectAttachedNetwork(vnetId)) { + return null; + } + + final List names = getAllVmNames(conn); + + if (!names.isEmpty()) { + for (final String name : names) { + if (VirtualMachineName.getVnet(name).equals(vnetId)) { + return null; // Can't remove the vnet yet. + } + } + } + + final Script command = new Script(_modifyVlanPath, _timeout, s_logger); + command.add("-o", "delete"); + command.add("-v", vnetId); + return command.execute(); + } + + protected Integer getVncPort(Connect conn, String vmName) + throws LibvirtException { + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + String xmlDesc = dm.getXMLDesc(0); + parser.parseDomainXML(xmlDesc); + return parser.getVncPort(); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException l) { + + } + } + } + + private boolean IsHVMEnabled(Connect conn) { + LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); + try { + parser.parseCapabilitiesXML(conn.getCapabilities()); + ArrayList osTypes = parser.getGuestOsType(); + for (String o : osTypes) { + if (o.equalsIgnoreCase("hvm")) { + return true; + } + } + } catch (LibvirtException e) { + + } + return false; + } + + private String getHypervisorPath(Connect conn) { + File f = new File("/usr/bin/cloud-qemu-kvm"); + if (f.exists()) { + return "/usr/bin/cloud-qemu-kvm"; + } else { + f = new File("/usr/libexec/cloud-qemu-kvm"); + if (f.exists()) { + return "/usr/libexec/cloud-qemu-kvm"; + } + + LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); + try { + parser.parseCapabilitiesXML(conn.getCapabilities()); + } catch (LibvirtException e) { + + } + return parser.getEmulator(); + } + } + + private String getGuestType(Connect conn, String vmName) { + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + String xmlDesc = dm.getXMLDesc(0); + parser.parseDomainXML(xmlDesc); + return parser.getDescription(); + } catch (LibvirtException e) { + return null; + } catch (Exception e) { + return null; + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException l) { + + } + } + } + + private boolean isGuestPVEnabled(String guestOS) { + if (guestOS == null) { + return false; + } + String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS); + if (guestOS.startsWith("Ubuntu") + || guestOSName.startsWith("Fedora 13") + || guestOSName.startsWith("Fedora 12") + || guestOSName.startsWith("Fedora 11") + || guestOSName.startsWith("Fedora 10") + || guestOSName.startsWith("Fedora 9") + || guestOSName.startsWith("CentOS 5.3") + || guestOSName.startsWith("CentOS 5.4") + || guestOSName.startsWith("CentOS 5.5") + || guestOS.startsWith("CentOS") + || guestOS.startsWith("Fedora") + || guestOSName.startsWith("Red Hat Enterprise Linux 5.3") + || guestOSName.startsWith("Red Hat Enterprise Linux 5.4") + || guestOSName.startsWith("Red Hat Enterprise Linux 5.5") + || guestOSName.startsWith("Red Hat Enterprise Linux 6") + || guestOS.startsWith("Debian GNU/Linux") + || guestOSName.startsWith("Other PV")) { + return true; + } else { + return false; + } + } + + public boolean isCentosHost() { + if (_hvVersion <= 9) { + return true; + } else { + return false; + } + } + + private InterfaceDef.nicModel getGuestNicModel(String guestOSType) { + if (isGuestPVEnabled(guestOSType)) { + return InterfaceDef.nicModel.VIRTIO; + } else { + return InterfaceDef.nicModel.E1000; + } + } + + private DiskDef.diskBus getGuestDiskModel(String guestOSType) { + if (isGuestPVEnabled(guestOSType)) { + return DiskDef.diskBus.VIRTIO; + } else { + return DiskDef.diskBus.IDE; + } + } + + private String setVnetBrName(String vnetId) { + return "cloudVirBr" + vnetId; + } + + private String getVnetIdFromBrName(String vnetBrName) { + return vnetBrName.replaceAll("cloudVirBr", ""); + } + + private void cleanupVMNetworks(Connect conn, List nics) { + for (InterfaceDef nic : nics) { + if (nic.getHostNetType() == hostNicType.VNET) { + cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName())); + } + } + } + + private Domain getDomain(Connect conn, String vmName) + throws LibvirtException { + return conn + .domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes())); + } + + protected List getInterfaces(Connect conn, String vmName) { + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + parser.parseDomainXML(dm.getXMLDesc(0)); + return parser.getInterfaces(); + + } catch (LibvirtException e) { + s_logger.debug("Failed to get dom xml: " + e.toString()); + return new ArrayList(); + } catch (Exception e) { + s_logger.debug("Failed to get dom xml: " + e.toString()); + return new ArrayList(); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + + } + } + } + + protected List getDisks(Connect conn, String vmName) { + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + Domain dm = null; + try { + dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName + .getBytes())); + parser.parseDomainXML(dm.getXMLDesc(0)); + return parser.getDisks(); + + } catch (LibvirtException e) { + s_logger.debug("Failed to get dom xml: " + e.toString()); + return new ArrayList(); + } catch (Exception e) { + s_logger.debug("Failed to get dom xml: " + e.toString()); + return new ArrayList(); + } finally { + try { + if (dm != null) { + dm.free(); + } + } catch (LibvirtException e) { + + } + } + } + + private String executeBashScript(String script) { + Script command = new Script("/bin/bash", _timeout, s_logger); + command.add("-c"); + command.add(script); + return command.execute(); + } + + private String executeBashScript(String script, OutputInterpreter parser) { + Script command = new Script("/bin/bash", _timeout, s_logger); + command.add("-c"); + command.add(script); + return command.execute(parser); + } + + private void deletExitingLinkLocalRoutTable(String linkLocalBr) { + Script command = new Script("/bin/bash", _timeout); + command.add("-c"); + command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + boolean foundLinkLocalBr = false; + if (result == null && parser.getLines() != null) { + String[] lines = parser.getLines().split("\\n"); + for (String line : lines) { + String[] tokens = line.split(" "); + if (!tokens[2].equalsIgnoreCase(linkLocalBr)) { + Script.runSimpleBashScript("ip route del " + + NetUtils.getLinkLocalCIDR()); + } else { + foundLinkLocalBr = true; + } + } + } + if (!foundLinkLocalBr) { + Script.runSimpleBashScript("ip route add " + + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + + " src " + NetUtils.getLinkLocalGateway()); + } + } + + private class vmStats { + long _usedTime; + long _tx; + long _rx; + Calendar _timestamp; + } + + private VmStatsEntry getVmStat(Connect conn, String vmName) + throws LibvirtException { + Domain dm = null; + try { + dm = getDomain(conn, vmName); + DomainInfo info = dm.getInfo(); + + VmStatsEntry stats = new VmStatsEntry(); + stats.setNumCPUs(info.nrVirtCpu); + stats.setEntityType("vm"); + + /* get cpu utilization */ + vmStats oldStats = null; + + Calendar now = Calendar.getInstance(); + + oldStats = _vmStats.get(vmName); + + long elapsedTime = 0; + if (oldStats != null) { + elapsedTime = now.getTimeInMillis() + - oldStats._timestamp.getTimeInMillis(); + double utilization = (info.cpuTime - oldStats._usedTime) + / ((double) elapsedTime * 1000000); + + NodeInfo node = conn.nodeInfo(); + utilization = utilization / node.cpus; + stats.setCPUUtilization(utilization * 100); + } + + /* get network stats */ + + List vifs = getInterfaces(conn, vmName); + long rx = 0; + long tx = 0; + for (InterfaceDef vif : vifs) { + DomainInterfaceStats ifStats = dm.interfaceStats(vif + .getDevName()); + rx += ifStats.rx_bytes; + tx += ifStats.tx_bytes; + } + + if (oldStats != null) { + long deltarx = rx - oldStats._rx; + if (deltarx > 0) + stats.setNetworkReadKBs(deltarx / 1000); + long deltatx = tx - oldStats._tx; + if (deltatx > 0) + stats.setNetworkWriteKBs(deltatx / 1000); + } + + vmStats newStat = new vmStats(); + newStat._usedTime = info.cpuTime; + newStat._rx = rx; + newStat._tx = tx; + newStat._timestamp = now; + _vmStats.put(vmName, newStat); + return stats; + } finally { + if (dm != null) { + dm.free(); + } + } + } + + private boolean can_bridge_firewall(String prvNic) { + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("can_bridge_firewall"); + cmd.add(prvNic); + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) { + if (!_can_bridge_firewall) { + return false; + } + String vif = null; + List intfs = getInterfaces(conn, vmName); + if (intfs.size() > 0) { + InterfaceDef intf = intfs.get(0); + vif = intf.getDevName(); + } + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("destroy_network_rules_for_vm"); + cmd.add("--vmname", vmName); + if (vif != null) { + cmd.add("--vif", vif); + } + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + protected boolean default_network_rules(Connect conn, String vmName, + NicTO nic, Long vmId) { + if (!_can_bridge_firewall) { + return false; + } + + List intfs = getInterfaces(conn, vmName); + if (intfs.size() < nic.getDeviceId()) { + return false; + } + + InterfaceDef intf = intfs.get(nic.getDeviceId()); + String brname = intf.getBrName(); + String vif = intf.getDevName(); + + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("default_network_rules"); + cmd.add("--vmname", vmName); + cmd.add("--vmid", vmId.toString()); + if (nic.getIp() != null) { + cmd.add("--vmip", nic.getIp()); + } + cmd.add("--vmmac", nic.getMac()); + cmd.add("--vif", vif); + cmd.add("--brname", brname); + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + protected boolean post_default_network_rules(Connect conn, String vmName, + NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp, + String hostMacAddr) { + if (!_can_bridge_firewall) { + return false; + } + + List intfs = getInterfaces(conn, vmName); + if (intfs.size() < nic.getDeviceId()) { + return false; + } + + InterfaceDef intf = intfs.get(nic.getDeviceId()); + String brname = intf.getBrName(); + String vif = intf.getDevName(); + + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("post_default_network_rules"); + cmd.add("--vmname", vmName); + cmd.add("--vmid", vmId.toString()); + cmd.add("--vmip", nic.getIp()); + cmd.add("--vmmac", nic.getMac()); + cmd.add("--vif", vif); + cmd.add("--brname", brname); + if (dhcpServerIp != null) + cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress()); + + cmd.add("--hostIp", hostIp); + cmd.add("--hostMacAddr", hostMacAddr); + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + protected boolean default_network_rules_for_systemvm(Connect conn, + String vmName) { + if (!_can_bridge_firewall) { + return false; + } + + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("default_network_rules_systemvm"); + cmd.add("--vmname", vmName); + cmd.add("--localbrname", _linkLocalBridgeName); + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + private boolean add_network_rules(String vmName, String vmId, + String guestIP, String sig, String seq, String mac, String rules, + String vif, String brname) { + if (!_can_bridge_firewall) { + return false; + } + + String newRules = rules.replace(" ", ";"); + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("add_network_rules"); + cmd.add("--vmname", vmName); + cmd.add("--vmid", vmId); + cmd.add("--vmip", guestIP); + cmd.add("--sig", sig); + cmd.add("--seq", seq); + cmd.add("--vmmac", mac); + cmd.add("--vif", vif); + cmd.add("--brname", brname); + if (rules != null) { + cmd.add("--rules", newRules); + } + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + private boolean cleanup_rules() { + if (!_can_bridge_firewall) { + return false; + } + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("cleanup_rules"); + String result = cmd.execute(); + if (result != null) { + return false; + } + return true; + } + + private String get_rule_logs_for_vms() { + Script cmd = new Script(_securityGroupPath, _timeout, s_logger); + cmd.add("get_rule_logs_for_vms"); + OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); + String result = cmd.execute(parser); + if (result == null) { + return parser.getLine(); + } + return null; + } + + private HashMap> syncNetworkGroups(long id) { + HashMap> states = new HashMap>(); + + String result = get_rule_logs_for_vms(); + s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); + String[] rulelogs = result != null ? result.split(";") : new String[0]; + for (String rulesforvm : rulelogs) { + String[] log = rulesforvm.split(","); + if (log.length != 6) { + continue; + } + try { + states.put(log[0], new Pair(Long.parseLong(log[1]), + Long.parseLong(log[5]))); + } catch (NumberFormatException nfe) { + states.put(log[0], new Pair(-1L, -1L)); + } + } + return states; + } + + /* online snapshot supported by enhanced qemu-kvm */ + private boolean isSnapshotSupported() { + String result = executeBashScript("qemu-img --help|grep convert |grep snapshot"); + if (result != null) { + return false; + } else { + return true; + } + } + + private Pair getNicStats(String nicName) { + double rx = 0.0; + OutputInterpreter.OneLineParser rxParser = new OutputInterpreter.OneLineParser(); + String result = executeBashScript("cat /sys/class/net/" + nicName + + "/statistics/rx_bytes", rxParser); + if (result == null && rxParser.getLine() != null) { + rx = Double.parseDouble(rxParser.getLine()); + } + + double tx = 0.0; + OutputInterpreter.OneLineParser txParser = new OutputInterpreter.OneLineParser(); + result = executeBashScript("cat /sys/class/net/" + nicName + + "/statistics/tx_bytes", txParser); + if (result == null && txParser.getLine() != null) { + tx = Double.parseDouble(txParser.getLine()); + } + + return new Pair(rx, tx); + } + + private void createControlNetwork(Connect conn) throws LibvirtException { + _virtRouterResource.createControlNetwork(_linkLocalBridgeName); + } + + private Answer execute(NetworkRulesSystemVmCommand cmd) { + boolean success = false; + Connect conn; + try { + conn = LibvirtConnection.getConnection(); + success = default_network_rules_for_systemvm(conn, cmd.getVmName()); + } catch (LibvirtException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return new Answer(cmd, success, ""); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtConnection.java b/agent/src/com/cloud/agent/resource/computing/LibvirtConnection.java index 874ad983309..d3a231871bb 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtConnection.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtConnection.java @@ -21,28 +21,28 @@ import org.libvirt.Connect; import org.libvirt.LibvirtException; public class LibvirtConnection { - private static final Logger s_logger = Logger - .getLogger(LibvirtConnection.class); - static private Connect _connection; - static private String _hypervisorURI; + private static final Logger s_logger = Logger + .getLogger(LibvirtConnection.class); + static private Connect _connection; + static private String _hypervisorURI; - static public Connect getConnection() throws LibvirtException { - if (_connection == null) { - _connection = new Connect(_hypervisorURI, false); - } else { - try { - _connection.getVersion(); - } catch (LibvirtException e) { - s_logger.debug("Connection with libvirtd is broken, due to " - + e.getMessage()); - _connection = new Connect(_hypervisorURI, false); - } - } + static public Connect getConnection() throws LibvirtException { + if (_connection == null) { + _connection = new Connect(_hypervisorURI, false); + } else { + try { + _connection.getVersion(); + } catch (LibvirtException e) { + s_logger.debug("Connection with libvirtd is broken, due to " + + e.getMessage()); + _connection = new Connect(_hypervisorURI, false); + } + } - return _connection; - } + return _connection; + } - static void initialize(String hypervisorURI) { - _hypervisorURI = hypervisorURI; - } + static void initialize(String hypervisorURI) { + _hypervisorURI = hypervisorURI; + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java index f51d7ae8278..62155349b66 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java @@ -45,209 +45,209 @@ import com.cloud.agent.resource.computing.LibvirtVMDef.InterfaceDef.nicModel; * */ public class LibvirtDomainXMLParser { - private static final Logger s_logger = Logger - .getLogger(LibvirtDomainXMLParser.class); - private final List interfaces = new ArrayList(); - private final List diskDefs = new ArrayList(); - private Integer vncPort; - private String desc; + private static final Logger s_logger = Logger + .getLogger(LibvirtDomainXMLParser.class); + private final List interfaces = new ArrayList(); + private final List diskDefs = new ArrayList(); + private Integer vncPort; + private String desc; - public boolean parseDomainXML(String domXML) { - DocumentBuilder builder; - try { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + public boolean parseDomainXML(String domXML) { + DocumentBuilder builder; + try { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(domXML)); - Document doc = builder.parse(is); + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(domXML)); + Document doc = builder.parse(is); - Element rootElement = doc.getDocumentElement(); + Element rootElement = doc.getDocumentElement(); - desc = getTagValue("description", rootElement); + desc = getTagValue("description", rootElement); - Element devices = (Element) rootElement.getElementsByTagName( - "devices").item(0); - NodeList disks = devices.getElementsByTagName("disk"); - for (int i = 0; i < disks.getLength(); i++) { - Element disk = (Element) disks.item(i); - String diskFmtType = getAttrValue("driver", "type", disk); - String diskFile = getAttrValue("source", "file", disk); - String diskDev = getAttrValue("source", "dev", disk); + Element devices = (Element) rootElement.getElementsByTagName( + "devices").item(0); + NodeList disks = devices.getElementsByTagName("disk"); + for (int i = 0; i < disks.getLength(); i++) { + Element disk = (Element) disks.item(i); + String diskFmtType = getAttrValue("driver", "type", disk); + String diskFile = getAttrValue("source", "file", disk); + String diskDev = getAttrValue("source", "dev", disk); - String diskLabel = getAttrValue("target", "dev", disk); - String bus = getAttrValue("target", "bus", disk); - String type = disk.getAttribute("type"); - String device = disk.getAttribute("device"); + String diskLabel = getAttrValue("target", "dev", disk); + String bus = getAttrValue("target", "bus", disk); + String type = disk.getAttribute("type"); + String device = disk.getAttribute("device"); - DiskDef def = new DiskDef(); - if (type.equalsIgnoreCase("file")) { - if (device.equalsIgnoreCase("disk")) { - DiskDef.diskFmtType fmt = null; - if (diskFmtType != null) { - fmt = DiskDef.diskFmtType.valueOf(diskFmtType - .toUpperCase()); - } - def.defFileBasedDisk(diskFile, diskLabel, - DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt); - } else if (device.equalsIgnoreCase("cdrom")) { - def.defISODisk(diskFile); - } - } else if (type.equalsIgnoreCase("block")) { - def.defBlockBasedDisk(diskDev, diskLabel, - DiskDef.diskBus.valueOf(bus.toUpperCase())); - } - diskDefs.add(def); - } + DiskDef def = new DiskDef(); + if (type.equalsIgnoreCase("file")) { + if (device.equalsIgnoreCase("disk")) { + DiskDef.diskFmtType fmt = null; + if (diskFmtType != null) { + fmt = DiskDef.diskFmtType.valueOf(diskFmtType + .toUpperCase()); + } + def.defFileBasedDisk(diskFile, diskLabel, + DiskDef.diskBus.valueOf(bus.toUpperCase()), fmt); + } else if (device.equalsIgnoreCase("cdrom")) { + def.defISODisk(diskFile); + } + } else if (type.equalsIgnoreCase("block")) { + def.defBlockBasedDisk(diskDev, diskLabel, + DiskDef.diskBus.valueOf(bus.toUpperCase())); + } + diskDefs.add(def); + } - NodeList nics = devices.getElementsByTagName("interface"); - for (int i = 0; i < nics.getLength(); i++) { - Element nic = (Element) nics.item(i); + NodeList nics = devices.getElementsByTagName("interface"); + for (int i = 0; i < nics.getLength(); i++) { + Element nic = (Element) nics.item(i); - String type = nic.getAttribute("type"); - String mac = getAttrValue("mac", "address", nic); - String dev = getAttrValue("target", "dev", nic); - String model = getAttrValue("model", "type", nic); - InterfaceDef def = new InterfaceDef(); + String type = nic.getAttribute("type"); + String mac = getAttrValue("mac", "address", nic); + String dev = getAttrValue("target", "dev", nic); + String model = getAttrValue("model", "type", nic); + InterfaceDef def = new InterfaceDef(); - if (type.equalsIgnoreCase("network")) { - String network = getAttrValue("source", "network", nic); - def.defPrivateNet(network, dev, mac, - nicModel.valueOf(model.toUpperCase())); - } else if (type.equalsIgnoreCase("bridge")) { - String bridge = getAttrValue("source", "bridge", nic); - def.defBridgeNet(bridge, dev, mac, - nicModel.valueOf(model.toUpperCase())); - } - interfaces.add(def); - } + if (type.equalsIgnoreCase("network")) { + String network = getAttrValue("source", "network", nic); + def.defPrivateNet(network, dev, mac, + nicModel.valueOf(model.toUpperCase())); + } else if (type.equalsIgnoreCase("bridge")) { + String bridge = getAttrValue("source", "bridge", nic); + def.defBridgeNet(bridge, dev, mac, + nicModel.valueOf(model.toUpperCase())); + } + interfaces.add(def); + } - Element graphic = (Element) devices - .getElementsByTagName("graphics").item(0); - String port = graphic.getAttribute("port"); - if (port != null) { - try { - vncPort = Integer.parseInt(port); - if (vncPort != -1) { - vncPort = vncPort - 5900; - } else { - vncPort = null; - } - } catch (NumberFormatException nfe) { - vncPort = null; - } - } + Element graphic = (Element) devices + .getElementsByTagName("graphics").item(0); + String port = graphic.getAttribute("port"); + if (port != null) { + try { + vncPort = Integer.parseInt(port); + if (vncPort != -1) { + vncPort = vncPort - 5900; + } else { + vncPort = null; + } + } catch (NumberFormatException nfe) { + vncPort = null; + } + } - return true; - } catch (ParserConfigurationException e) { - s_logger.debug(e.toString()); - } catch (SAXException e) { - s_logger.debug(e.toString()); - } catch (IOException e) { - s_logger.debug(e.toString()); - } - return false; - } + return true; + } catch (ParserConfigurationException e) { + s_logger.debug(e.toString()); + } catch (SAXException e) { + s_logger.debug(e.toString()); + } catch (IOException e) { + s_logger.debug(e.toString()); + } + return false; + } - private static String getTagValue(String tag, Element eElement) { - NodeList tagNodeList = eElement.getElementsByTagName(tag); - if (tagNodeList == null || tagNodeList.getLength() == 0) { - return null; - } + private static String getTagValue(String tag, Element eElement) { + NodeList tagNodeList = eElement.getElementsByTagName(tag); + if (tagNodeList == null || tagNodeList.getLength() == 0) { + return null; + } - NodeList nlList = tagNodeList.item(0).getChildNodes(); + NodeList nlList = tagNodeList.item(0).getChildNodes(); - Node nValue = (Node) nlList.item(0); + Node nValue = (Node) nlList.item(0); - return nValue.getNodeValue(); - } + return nValue.getNodeValue(); + } - private static String getAttrValue(String tag, String attr, Element eElement) { - NodeList tagNode = eElement.getElementsByTagName(tag); - if (tagNode.getLength() == 0) { - return null; - } - Element node = (Element) tagNode.item(0); - return node.getAttribute(attr); - } + private static String getAttrValue(String tag, String attr, Element eElement) { + NodeList tagNode = eElement.getElementsByTagName(tag); + if (tagNode.getLength() == 0) { + return null; + } + Element node = (Element) tagNode.item(0); + return node.getAttribute(attr); + } - public Integer getVncPort() { - return vncPort; - } + public Integer getVncPort() { + return vncPort; + } - public List getInterfaces() { - return interfaces; - } + public List getInterfaces() { + return interfaces; + } - public List getDisks() { - return diskDefs; - } + public List getDisks() { + return diskDefs; + } - public String getDescription() { - return desc; - } + public String getDescription() { + return desc; + } - public static void main(String[] args) { - LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); - parser.parseDomainXML("" - + "r-6-CV-5002-1" - + "581b5a4b-b496-8d4d-e44e-a7dcbe9df0b5" - + "testVM" - + "131072" - + "131072" - + "1" - + "" - + "hvm" - + "/var/lib/libvirt/qemu/vmlinuz-2.6.31.6-166.fc12.i686" - + "ro root=/dev/sda1 acpi=force selinux=0 eth0ip=10.1.1.1 eth0mask=255.255.255.0 eth2ip=192.168.10.152 eth2mask=255.255.255.0 gateway=192.168.10.1 dns1=72.52.126.11 dns2=72.52.126.12 domain=v4.myvm.com" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "destroy" - + "restart" - + "destroy" - + "" - + "/usr/bin/qemu-kvm" - + "" - + "" - + "" - + "" + "" - + "" - + "" - + "" + "" - + "" + "" - + "" - + "" - + "" + "" - + "" + "" - + "" - + "" - + "" + "" - + "" + "" - + "" - + "" - + "" + "" + "" + public static void main(String[] args) { + LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); + parser.parseDomainXML("" + + "r-6-CV-5002-1" + + "581b5a4b-b496-8d4d-e44e-a7dcbe9df0b5" + + "testVM" + + "131072" + + "131072" + + "1" + + "" + + "hvm" + + "/var/lib/libvirt/qemu/vmlinuz-2.6.31.6-166.fc12.i686" + + "ro root=/dev/sda1 acpi=force selinux=0 eth0ip=10.1.1.1 eth0mask=255.255.255.0 eth2ip=192.168.10.152 eth2mask=255.255.255.0 gateway=192.168.10.1 dns1=72.52.126.11 dns2=72.52.126.12 domain=v4.myvm.com" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "destroy" + + "restart" + + "destroy" + + "" + + "/usr/bin/qemu-kvm" + + "" + + "" + + "" + + "" + "" + + "" + + "" + + "" + "" + + "" + "" + + "" + + "" + + "" + "" + + "" + "" + + "" + + "" + + "" + "" + + "" + "" + + "" + + "" + + "" + "" + "" - ); - for (InterfaceDef intf : parser.getInterfaces()) { - System.out.println(intf); - } - for (DiskDef disk : parser.getDisks()) { - System.out.println(disk); - } - System.out.println(parser.getVncPort()); - System.out.println(parser.getDescription()); + ); + for (InterfaceDef intf : parser.getInterfaces()) { + System.out.println(intf); + } + for (DiskDef disk : parser.getDisks()) { + System.out.println(disk); + } + System.out.println(parser.getVncPort()); + System.out.println(parser.getDescription()); - List test = new ArrayList(1); - test.add("1"); - test.add("2"); - if (test.contains("1")) { - System.out.print("fdf"); - } - } + List test = new ArrayList(1); + test.add("1"); + test.add("2"); + if (test.contains("1")) { + System.out.print("fdf"); + } + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtNetworkDef.java b/agent/src/com/cloud/agent/resource/computing/LibvirtNetworkDef.java index 4c3db464891..7f757dec967 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtNetworkDef.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtNetworkDef.java @@ -20,174 +20,174 @@ import java.util.ArrayList; import java.util.List; public class LibvirtNetworkDef { - enum netType { - BRIDGE, NAT, LOCAL - } + enum netType { + BRIDGE, NAT, LOCAL + } - private final String _networkName; - private final String _uuid; - private netType _networkType; - private String _brName; - private boolean _stp; - private int _delay; - private String _fwDev; - private final String _domainName; - private String _brIPAddr; - private String _brNetMask; - private final List ipranges = new ArrayList(); - private final List dhcpMaps = new ArrayList(); + private final String _networkName; + private final String _uuid; + private netType _networkType; + private String _brName; + private boolean _stp; + private int _delay; + private String _fwDev; + private final String _domainName; + private String _brIPAddr; + private String _brNetMask; + private final List ipranges = new ArrayList(); + private final List dhcpMaps = new ArrayList(); - public static class dhcpMapping { - String _mac; - String _name; - String _ip; + public static class dhcpMapping { + String _mac; + String _name; + String _ip; - public dhcpMapping(String mac, String name, String ip) { - _mac = mac; - _name = name; - _ip = ip; - } - } + public dhcpMapping(String mac, String name, String ip) { + _mac = mac; + _name = name; + _ip = ip; + } + } - public static class IPRange { - String _start; - String _end; + public static class IPRange { + String _start; + String _end; - public IPRange(String start, String end) { - _start = start; - _end = end; - } - } + public IPRange(String start, String end) { + _start = start; + _end = end; + } + } - public LibvirtNetworkDef(String netName, String uuid, String domName) { - _networkName = netName; - _uuid = uuid; - _domainName = domName; - } + public LibvirtNetworkDef(String netName, String uuid, String domName) { + _networkName = netName; + _uuid = uuid; + _domainName = domName; + } - public void defNATNetwork(String brName, boolean stp, int delay, - String fwNic, String ipAddr, String netMask) { - _networkType = netType.NAT; - _brName = brName; - _stp = stp; - _delay = delay; - _fwDev = fwNic; - _brIPAddr = ipAddr; - _brNetMask = netMask; - } + public void defNATNetwork(String brName, boolean stp, int delay, + String fwNic, String ipAddr, String netMask) { + _networkType = netType.NAT; + _brName = brName; + _stp = stp; + _delay = delay; + _fwDev = fwNic; + _brIPAddr = ipAddr; + _brNetMask = netMask; + } - public void defBrNetwork(String brName, boolean stp, int delay, - String fwNic, String ipAddr, String netMask) { - _networkType = netType.BRIDGE; - _brName = brName; - _stp = stp; - _delay = delay; - _fwDev = fwNic; - _brIPAddr = ipAddr; - _brNetMask = netMask; - } + public void defBrNetwork(String brName, boolean stp, int delay, + String fwNic, String ipAddr, String netMask) { + _networkType = netType.BRIDGE; + _brName = brName; + _stp = stp; + _delay = delay; + _fwDev = fwNic; + _brIPAddr = ipAddr; + _brNetMask = netMask; + } - public void defLocalNetwork(String brName, boolean stp, int delay, - String ipAddr, String netMask) { - _networkType = netType.LOCAL; - _brName = brName; - _stp = stp; - _delay = delay; - _brIPAddr = ipAddr; - _brNetMask = netMask; - } + public void defLocalNetwork(String brName, boolean stp, int delay, + String ipAddr, String netMask) { + _networkType = netType.LOCAL; + _brName = brName; + _stp = stp; + _delay = delay; + _brIPAddr = ipAddr; + _brNetMask = netMask; + } - public void adddhcpIPRange(String start, String end) { - IPRange ipr = new IPRange(start, end); - ipranges.add(ipr); - } + public void adddhcpIPRange(String start, String end) { + IPRange ipr = new IPRange(start, end); + ipranges.add(ipr); + } - public void adddhcpMapping(String mac, String host, String ip) { - dhcpMapping map = new dhcpMapping(mac, host, ip); - dhcpMaps.add(map); - } + public void adddhcpMapping(String mac, String host, String ip) { + dhcpMapping map = new dhcpMapping(mac, host, ip); + dhcpMaps.add(map); + } - @Override - public String toString() { - StringBuilder netBuilder = new StringBuilder(); - netBuilder.append("\n"); - netBuilder.append("" + _networkName + "\n"); - if (_uuid != null) - netBuilder.append("" + _uuid + "\n"); - if (_brName != null) { - netBuilder.append("\n"); - } - if (_domainName != null) { - netBuilder.append("\n"); - } - if (_networkType == netType.BRIDGE) { - netBuilder.append("\n"); - } else if (_networkType == netType.NAT) { - netBuilder.append("\n"); - } - if (_brIPAddr != null || _brNetMask != null || !ipranges.isEmpty() - || !dhcpMaps.isEmpty()) { - netBuilder.append("\n"); + @Override + public String toString() { + StringBuilder netBuilder = new StringBuilder(); + netBuilder.append("\n"); + netBuilder.append("" + _networkName + "\n"); + if (_uuid != null) + netBuilder.append("" + _uuid + "\n"); + if (_brName != null) { + netBuilder.append("\n"); + } + if (_domainName != null) { + netBuilder.append("\n"); + } + if (_networkType == netType.BRIDGE) { + netBuilder.append("\n"); + } else if (_networkType == netType.NAT) { + netBuilder.append("\n"); + } + if (_brIPAddr != null || _brNetMask != null || !ipranges.isEmpty() + || !dhcpMaps.isEmpty()) { + netBuilder.append("\n"); - if (!ipranges.isEmpty() || !dhcpMaps.isEmpty()) { - netBuilder.append("\n"); - for (IPRange ip : ipranges) { - netBuilder.append("\n"); - } - for (dhcpMapping map : dhcpMaps) { - netBuilder.append("\n"); - } - netBuilder.append("\n"); - } - netBuilder.append("\n"); - } - netBuilder.append("\n"); - return netBuilder.toString(); - } + if (!ipranges.isEmpty() || !dhcpMaps.isEmpty()) { + netBuilder.append("\n"); + for (IPRange ip : ipranges) { + netBuilder.append("\n"); + } + for (dhcpMapping map : dhcpMaps) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); + } + netBuilder.append("\n"); + } + netBuilder.append("\n"); + return netBuilder.toString(); + } - /** - * @param args - */ - public static void main(String[] args) { - LibvirtNetworkDef net = new LibvirtNetworkDef("cloudPrivate", null, - "cloud.com"); - net.defNATNetwork("cloudbr0", false, 0, null, "192.168.168.1", - "255.255.255.0"); - net.adddhcpIPRange("192.168.168.100", "192.168.168.220"); - net.adddhcpIPRange("192.168.168.10", "192.168.168.50"); - net.adddhcpMapping("branch0.cloud.com", "00:16:3e:77:e2:ed", - "192.168.168.100"); - net.adddhcpMapping("branch1.cloud.com", "00:16:3e:77:e2:ef", - "192.168.168.101"); - net.adddhcpMapping("branch2.cloud.com", "00:16:3e:77:e2:f0", - "192.168.168.102"); - System.out.println(net.toString()); + /** + * @param args + */ + public static void main(String[] args) { + LibvirtNetworkDef net = new LibvirtNetworkDef("cloudPrivate", null, + "cloud.com"); + net.defNATNetwork("cloudbr0", false, 0, null, "192.168.168.1", + "255.255.255.0"); + net.adddhcpIPRange("192.168.168.100", "192.168.168.220"); + net.adddhcpIPRange("192.168.168.10", "192.168.168.50"); + net.adddhcpMapping("branch0.cloud.com", "00:16:3e:77:e2:ed", + "192.168.168.100"); + net.adddhcpMapping("branch1.cloud.com", "00:16:3e:77:e2:ef", + "192.168.168.101"); + net.adddhcpMapping("branch2.cloud.com", "00:16:3e:77:e2:f0", + "192.168.168.102"); + System.out.println(net.toString()); - } + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolDef.java b/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolDef.java index 5e0a8416e25..582cd2e2e6d 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolDef.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolDef.java @@ -17,74 +17,74 @@ package com.cloud.agent.resource.computing; public class LibvirtStoragePoolDef { - public enum poolType { - ISCSI("iscsi"), NETFS("netfs"), LOGICAL("logical"), DIR("dir"); - String _poolType; + public enum poolType { + ISCSI("iscsi"), NETFS("netfs"), LOGICAL("logical"), DIR("dir"); + String _poolType; - poolType(String poolType) { - _poolType = poolType; - } + poolType(String poolType) { + _poolType = poolType; + } - @Override - public String toString() { - return _poolType; - } - } + @Override + public String toString() { + return _poolType; + } + } - private poolType _poolType; - private String _poolName; - private String _uuid; - private String _sourceHost; - private String _sourceDir; - private String _targetPath; + private poolType _poolType; + private String _poolName; + private String _uuid; + private String _sourceHost; + private String _sourceDir; + private String _targetPath; - public LibvirtStoragePoolDef(poolType type, String poolName, String uuid, - String host, String dir, String targetPath) { - _poolType = type; - _poolName = poolName; - _uuid = uuid; - _sourceHost = host; - _sourceDir = dir; - _targetPath = targetPath; - } + public LibvirtStoragePoolDef(poolType type, String poolName, String uuid, + String host, String dir, String targetPath) { + _poolType = type; + _poolName = poolName; + _uuid = uuid; + _sourceHost = host; + _sourceDir = dir; + _targetPath = targetPath; + } - public String getPoolName() { - return _poolName; - } + public String getPoolName() { + return _poolName; + } - public poolType getPoolType() { - return _poolType; - } + public poolType getPoolType() { + return _poolType; + } - public String getSourceHost() { - return _sourceHost; - } + public String getSourceHost() { + return _sourceHost; + } - public String getSourceDir() { - return _sourceDir; - } + public String getSourceDir() { + return _sourceDir; + } - public String getTargetPath() { - return _targetPath; - } + public String getTargetPath() { + return _targetPath; + } - @Override - public String toString() { - StringBuilder storagePoolBuilder = new StringBuilder(); - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("" + _poolName + "\n"); - if (_uuid != null) - storagePoolBuilder.append("" + _uuid + "\n"); - if (_poolType == poolType.NETFS) { - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("\n"); - } - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("" + _targetPath + "\n"); - storagePoolBuilder.append("\n"); - storagePoolBuilder.append("\n"); - return storagePoolBuilder.toString(); - } + @Override + public String toString() { + StringBuilder storagePoolBuilder = new StringBuilder(); + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("" + _poolName + "\n"); + if (_uuid != null) + storagePoolBuilder.append("" + _uuid + "\n"); + if (_poolType == poolType.NETFS) { + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("\n"); + } + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("" + _targetPath + "\n"); + storagePoolBuilder.append("\n"); + storagePoolBuilder.append("\n"); + return storagePoolBuilder.toString(); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolXMLParser.java index 2adcfed579d..5c45d76e82d 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtStoragePoolXMLParser.java @@ -29,81 +29,81 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class LibvirtStoragePoolXMLParser { - private static final Logger s_logger = Logger - .getLogger(LibvirtStoragePoolXMLParser.class); + private static final Logger s_logger = Logger + .getLogger(LibvirtStoragePoolXMLParser.class); - public LibvirtStoragePoolDef parseStoragePoolXML(String poolXML) { - DocumentBuilder builder; - try { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + public LibvirtStoragePoolDef parseStoragePoolXML(String poolXML) { + DocumentBuilder builder; + try { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(poolXML)); - Document doc = builder.parse(is); + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(poolXML)); + Document doc = builder.parse(is); - Element rootElement = doc.getDocumentElement(); - String type = rootElement.getAttribute("type"); + Element rootElement = doc.getDocumentElement(); + String type = rootElement.getAttribute("type"); - String uuid = getTagValue("uuid", rootElement); + String uuid = getTagValue("uuid", rootElement); - String poolName = getTagValue("name", rootElement); + String poolName = getTagValue("name", rootElement); - Element source = (Element) rootElement.getElementsByTagName( - "source").item(0); - String host = getAttrValue("host", "name", source); - String path = getAttrValue("dir", "path", source); + Element source = (Element) rootElement.getElementsByTagName( + "source").item(0); + String host = getAttrValue("host", "name", source); + String path = getAttrValue("dir", "path", source); - Element target = (Element) rootElement.getElementsByTagName( - "target").item(0); - String targetPath = getTagValue("path", target); + Element target = (Element) rootElement.getElementsByTagName( + "target").item(0); + String targetPath = getTagValue("path", target); - return new LibvirtStoragePoolDef( - LibvirtStoragePoolDef.poolType.valueOf(type.toUpperCase()), - poolName, uuid, host, path, targetPath); - } catch (ParserConfigurationException e) { - s_logger.debug(e.toString()); - } catch (SAXException e) { - s_logger.debug(e.toString()); - } catch (IOException e) { - s_logger.debug(e.toString()); - } - return null; - } + return new LibvirtStoragePoolDef( + LibvirtStoragePoolDef.poolType.valueOf(type.toUpperCase()), + poolName, uuid, host, path, targetPath); + } catch (ParserConfigurationException e) { + s_logger.debug(e.toString()); + } catch (SAXException e) { + s_logger.debug(e.toString()); + } catch (IOException e) { + s_logger.debug(e.toString()); + } + return null; + } - private static String getTagValue(String tag, Element eElement) { - NodeList nlList = eElement.getElementsByTagName(tag).item(0) - .getChildNodes(); - Node nValue = (Node) nlList.item(0); + private static String getTagValue(String tag, Element eElement) { + NodeList nlList = eElement.getElementsByTagName(tag).item(0) + .getChildNodes(); + Node nValue = (Node) nlList.item(0); - return nValue.getNodeValue(); - } + return nValue.getNodeValue(); + } - private static String getAttrValue(String tag, String attr, Element eElement) { - NodeList tagNode = eElement.getElementsByTagName(tag); - if (tagNode.getLength() == 0) { - return null; - } - Element node = (Element) tagNode.item(0); - return node.getAttribute(attr); - } + private static String getAttrValue(String tag, String attr, Element eElement) { + NodeList tagNode = eElement.getElementsByTagName(tag); + if (tagNode.getLength() == 0) { + return null; + } + Element node = (Element) tagNode.item(0); + return node.getAttribute(attr); + } - public static void main(String[] args) { - s_logger.addAppender(new org.apache.log4j.ConsoleAppender( - new org.apache.log4j.PatternLayout(), "System.out")); - String storagePool = "" + "test" - + "bf723c83-4b95-259c-7089-60776e61a11f" - + "20314165248" - + "1955450880" - + "18358714368" + "" - + "" - + "" - + "" + "" + "" - + "/media" + "" + "0700" - + "0" + "0" + "" - + "" + ""; + public static void main(String[] args) { + s_logger.addAppender(new org.apache.log4j.ConsoleAppender( + new org.apache.log4j.PatternLayout(), "System.out")); + String storagePool = "" + "test" + + "bf723c83-4b95-259c-7089-60776e61a11f" + + "20314165248" + + "1955450880" + + "18358714368" + "" + + "" + + "" + + "" + "" + "" + + "/media" + "" + "0700" + + "0" + "0" + "" + + "" + ""; - LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); - LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool); - s_logger.debug(pool.toString()); - } + LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); + LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool); + s_logger.debug(pool.toString()); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeDef.java b/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeDef.java index e00ecaa58a7..ef8e22e6008 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeDef.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeDef.java @@ -17,75 +17,75 @@ package com.cloud.agent.resource.computing; public class LibvirtStorageVolumeDef { - public enum volFormat { - RAW("raw"), QCOW2("qcow2"), DIR("dir"); - private String _format; + public enum volFormat { + RAW("raw"), QCOW2("qcow2"), DIR("dir"); + private String _format; - volFormat(String format) { - _format = format; - } + volFormat(String format) { + _format = format; + } - @Override - public String toString() { - return _format; - } + @Override + public String toString() { + return _format; + } - public static volFormat getFormat(String format) { - if (format == null) { - return null; - } - if (format.equalsIgnoreCase("raw")) { - return RAW; - } else if (format.equalsIgnoreCase("qcow2")) { - return QCOW2; - } - return null; - } - } + public static volFormat getFormat(String format) { + if (format == null) { + return null; + } + if (format.equalsIgnoreCase("raw")) { + return RAW; + } else if (format.equalsIgnoreCase("qcow2")) { + return QCOW2; + } + return null; + } + } - private String _volName; - private Long _volSize; - private volFormat _volFormat; - private String _backingPath; - private volFormat _backingFormat; + private String _volName; + private Long _volSize; + private volFormat _volFormat; + private String _backingPath; + private volFormat _backingFormat; - public LibvirtStorageVolumeDef(String volName, Long size, volFormat format, - String tmplPath, volFormat tmplFormat) { - _volName = volName; - _volSize = size; - _volFormat = format; - _backingPath = tmplPath; - _backingFormat = tmplFormat; - } + public LibvirtStorageVolumeDef(String volName, Long size, volFormat format, + String tmplPath, volFormat tmplFormat) { + _volName = volName; + _volSize = size; + _volFormat = format; + _backingPath = tmplPath; + _backingFormat = tmplFormat; + } - public volFormat getFormat() { - return this._volFormat; - } + public volFormat getFormat() { + return this._volFormat; + } - @Override - public String toString() { - StringBuilder storageVolBuilder = new StringBuilder(); - storageVolBuilder.append("\n"); - storageVolBuilder.append("" + _volName + "\n"); - if (_volSize != null) { - storageVolBuilder - .append("" + _volSize + "\n"); - } - storageVolBuilder.append("\n"); - storageVolBuilder.append("\n"); - storageVolBuilder.append(""); - storageVolBuilder.append("0744"); - storageVolBuilder.append(""); - storageVolBuilder.append("\n"); - if (_backingPath != null) { - storageVolBuilder.append("\n"); - storageVolBuilder.append("" + _backingPath + "\n"); - storageVolBuilder.append("\n"); - storageVolBuilder.append("\n"); - } - storageVolBuilder.append("\n"); - return storageVolBuilder.toString(); - } + @Override + public String toString() { + StringBuilder storageVolBuilder = new StringBuilder(); + storageVolBuilder.append("\n"); + storageVolBuilder.append("" + _volName + "\n"); + if (_volSize != null) { + storageVolBuilder + .append("" + _volSize + "\n"); + } + storageVolBuilder.append("\n"); + storageVolBuilder.append("\n"); + storageVolBuilder.append(""); + storageVolBuilder.append("0744"); + storageVolBuilder.append(""); + storageVolBuilder.append("\n"); + if (_backingPath != null) { + storageVolBuilder.append("\n"); + storageVolBuilder.append("" + _backingPath + "\n"); + storageVolBuilder.append("\n"); + storageVolBuilder.append("\n"); + } + storageVolBuilder.append("\n"); + return storageVolBuilder.toString(); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeXMLParser.java index c4fe6dffd2f..163ca2b19db 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtStorageVolumeXMLParser.java @@ -32,73 +32,73 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class LibvirtStorageVolumeXMLParser { - private static final Logger s_logger = Logger - .getLogger(LibvirtStorageVolumeXMLParser.class); + private static final Logger s_logger = Logger + .getLogger(LibvirtStorageVolumeXMLParser.class); - public LibvirtStorageVolumeDef parseStorageVolumeXML(String volXML) { - DocumentBuilder builder; - try { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + public LibvirtStorageVolumeDef parseStorageVolumeXML(String volXML) { + DocumentBuilder builder; + try { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(volXML)); - Document doc = builder.parse(is); + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(volXML)); + Document doc = builder.parse(is); - Element rootElement = doc.getDocumentElement(); + Element rootElement = doc.getDocumentElement(); - String VolName = getTagValue("name", rootElement); - Element target = (Element) rootElement.getElementsByTagName( - "target").item(0); - String format = getAttrValue("type", "format", target); - Long capacity = Long - .parseLong(getTagValue("capacity", rootElement)); - return new LibvirtStorageVolumeDef(VolName, capacity, - LibvirtStorageVolumeDef.volFormat.getFormat(format), null, - null); - } catch (ParserConfigurationException e) { - s_logger.debug(e.toString()); - } catch (SAXException e) { - s_logger.debug(e.toString()); - } catch (IOException e) { - s_logger.debug(e.toString()); - } - return null; - } + String VolName = getTagValue("name", rootElement); + Element target = (Element) rootElement.getElementsByTagName( + "target").item(0); + String format = getAttrValue("type", "format", target); + Long capacity = Long + .parseLong(getTagValue("capacity", rootElement)); + return new LibvirtStorageVolumeDef(VolName, capacity, + LibvirtStorageVolumeDef.volFormat.getFormat(format), null, + null); + } catch (ParserConfigurationException e) { + s_logger.debug(e.toString()); + } catch (SAXException e) { + s_logger.debug(e.toString()); + } catch (IOException e) { + s_logger.debug(e.toString()); + } + return null; + } - private static String getTagValue(String tag, Element eElement) { - NodeList nlList = eElement.getElementsByTagName(tag).item(0) - .getChildNodes(); - Node nValue = (Node) nlList.item(0); + private static String getTagValue(String tag, Element eElement) { + NodeList nlList = eElement.getElementsByTagName(tag).item(0) + .getChildNodes(); + Node nValue = (Node) nlList.item(0); - return nValue.getNodeValue(); - } + return nValue.getNodeValue(); + } - private static String getAttrValue(String tag, String attr, Element eElement) { - NodeList tagNode = eElement.getElementsByTagName(tag); - if (tagNode.getLength() == 0) { - return null; - } - Element node = (Element) tagNode.item(0); - return node.getAttribute(attr); - } + private static String getAttrValue(String tag, String attr, Element eElement) { + NodeList tagNode = eElement.getElementsByTagName(tag); + if (tagNode.getLength() == 0) { + return null; + } + Element node = (Element) tagNode.item(0); + return node.getAttribute(attr); + } - public static void main(String[] args) { - s_logger.addAppender(new org.apache.log4j.ConsoleAppender( - new org.apache.log4j.PatternLayout(), "System.out")); - String storagePool = "" + "test" - + "bf723c83-4b95-259c-7089-60776e61a11f" - + "20314165248" - + "1955450880" - + "18358714368" + "" - + "" - + "" - + "" + "" + "" - + "/media" + "" + "0700" - + "0" + "0" + "" - + "" + ""; + public static void main(String[] args) { + s_logger.addAppender(new org.apache.log4j.ConsoleAppender( + new org.apache.log4j.PatternLayout(), "System.out")); + String storagePool = "" + "test" + + "bf723c83-4b95-259c-7089-60776e61a11f" + + "20314165248" + + "1955450880" + + "18358714368" + "" + + "" + + "" + + "" + "" + "" + + "/media" + "" + "0700" + + "0" + "0" + "" + + "" + ""; - LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); - LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool); - s_logger.debug(pool.toString()); - } + LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); + LibvirtStoragePoolDef pool = parser.parseStoragePoolXML(storagePool); + s_logger.debug(pool.toString()); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtVMDef.java b/agent/src/com/cloud/agent/resource/computing/LibvirtVMDef.java index 1a0afd02e23..8fd7815bf69 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtVMDef.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtVMDef.java @@ -24,879 +24,879 @@ import java.util.Map; import java.util.UUID; public class LibvirtVMDef { - private String _hvsType; - private String _domName; - private String _domUUID; - private String _desc; - private final Map components = new HashMap(); - - public static class GuestDef { - enum guestType { - KVM, XEN, EXE - } - - enum bootOrder { - HARDISK("hd"), CDROM("cdrom"), FLOOPY("fd"), NETWORK("network"); - String _order; - - bootOrder(String order) { - _order = order; - } - - @Override - public String toString() { - return _order; - } - } - - private guestType _type; - private String _arch; - private String _loader; - private String _kernel; - private String _initrd; - private String _root; - private String _cmdline; - private List _bootdevs = new ArrayList(); - private String _machine; - - public void setGuestType(guestType type) { - _type = type; - } - - public void setGuestArch(String arch) { - _arch = arch; - } - - public void setMachineType(String machine) { - _machine = machine; - } - - public void setLoader(String loader) { - _loader = loader; - } - - public void setBootKernel(String kernel, String initrd, String rootdev, - String cmdline) { - _kernel = kernel; - _initrd = initrd; - _root = rootdev; - _cmdline = cmdline; - } - - public void setBootOrder(bootOrder order) { - _bootdevs.add(order); - } - - @Override - public String toString() { - if (_type == guestType.KVM) { - StringBuilder guestDef = new StringBuilder(); - guestDef.append("\n"); - guestDef.append("hvm\n"); - if (!_bootdevs.isEmpty()) { - for (bootOrder bo : _bootdevs) { - guestDef.append("\n"); - } - } - guestDef.append("\n"); - return guestDef.toString(); - } else - return null; - } - } - - public static class GuestResourceDef { - private long _mem; - private int _currentMem = -1; - private String _memBacking; - private int _vcpu = -1; - - public void setMemorySize(long mem) { - _mem = mem; - } - - public void setCurrentMem(int currMem) { - _currentMem = currMem; - } - - public void setMemBacking(String memBacking) { - _memBacking = memBacking; - } - - public void setVcpuNum(int vcpu) { - _vcpu = vcpu; - } - - @Override - public String toString() { - StringBuilder resBuidler = new StringBuilder(); - resBuidler.append("" + _mem + "\n"); - if (_currentMem != -1) { - resBuidler.append("" + _currentMem - + "\n"); - } - if (_memBacking != null) { - resBuidler.append("" + "<" + _memBacking + "/>" - + "\n"); - } - if (_vcpu != -1) { - resBuidler.append("" + _vcpu + "\n"); - } - return resBuidler.toString(); - } - } - - public static class FeaturesDef { - private final List _features = new ArrayList(); - - public void addFeatures(String feature) { - _features.add(feature); - } - - @Override - public String toString() { - StringBuilder feaBuilder = new StringBuilder(); - feaBuilder.append("\n"); - for (String feature : _features) { - feaBuilder.append("<" + feature + "/>\n"); - } - feaBuilder.append("\n"); - return feaBuilder.toString(); - } - } - - public static class TermPolicy { - private String _reboot; - private String _powerOff; - private String _crash; - - public TermPolicy() { - _reboot = _powerOff = _crash = "destroy"; - } - - public void setRebootPolicy(String rbPolicy) { - _reboot = rbPolicy; - } - - public void setPowerOffPolicy(String poPolicy) { - _powerOff = poPolicy; - } - - public void setCrashPolicy(String crashPolicy) { - _crash = crashPolicy; - } - - @Override - public String toString() { - StringBuilder term = new StringBuilder(); - term.append("" + _reboot + "\n"); - term.append("" + _powerOff + "\n"); - term.append("" + _powerOff + "\n"); - return term.toString(); - } - } - - public static class ClockDef { - public enum ClockOffset { - UTC("utc"), LOCALTIME("localtime"), TIMEZONE("timezone"), VARIABLE( - "variable"); - - private String _offset; - - private ClockOffset(String offset) { - _offset = offset; - } - - @Override - public String toString() { - return _offset; - } - } - - private ClockOffset _offset; - private String _timerName; - private String _tickPolicy; - private String _track; - - public ClockDef() { - _offset = ClockOffset.UTC; - } - - public void setClockOffset(ClockOffset offset) { - _offset = offset; - } - - public void setTimer(String timerName, String tickPolicy, String track) { - _timerName = timerName; - _tickPolicy = tickPolicy; - _track = track; - } - - @Override - public String toString() { - StringBuilder clockBuilder = new StringBuilder(); - clockBuilder.append("\n"); - if (_timerName != null) { - clockBuilder.append("\n"); - clockBuilder.append("\n"); - } - clockBuilder.append("\n"); - return clockBuilder.toString(); - } - } - - public static class DevicesDef { - private String _emulator; - private final Map> devices = new HashMap>(); - - public boolean addDevice(Object device) { - Object dev = devices.get(device.getClass().toString()); - if (dev == null) { - List devs = new ArrayList(); - devs.add(device); - devices.put(device.getClass().toString(), devs); - } else { - List devs = (List) dev; - devs.add(device); - } - return true; - } - - public void setEmulatorPath(String emulator) { - _emulator = emulator; - } - - @Override - public String toString() { - StringBuilder devicesBuilder = new StringBuilder(); - devicesBuilder.append("\n"); - if (_emulator != null) { - devicesBuilder.append("" + _emulator - + "\n"); - } - - for (List devs : devices.values()) { - for (Object dev : devs) { - devicesBuilder.append(dev.toString()); - } - } - devicesBuilder.append("\n"); - return devicesBuilder.toString(); - } - - @SuppressWarnings("unchecked") - public List getDisks() { - return (List) devices.get(DiskDef.class.toString()); - } - - @SuppressWarnings("unchecked") - public List getInterfaces() { - return (List) devices.get(InterfaceDef.class - .toString()); - } - - } - - public static class DiskDef { - enum deviceType { - FLOOPY("floopy"), DISK("disk"), CDROM("cdrom"); - String _type; - - deviceType(String type) { - _type = type; - } - - @Override - public String toString() { - return _type; - } - } - - enum diskType { - FILE("file"), BLOCK("block"), DIRECTROY("dir"); - String _diskType; - - diskType(String type) { - _diskType = type; - } - - @Override - public String toString() { - return _diskType; - } - } - - enum diskBus { - IDE("ide"), SCSI("scsi"), VIRTIO("virtio"), XEN("xen"), USB("usb"), UML( - "uml"), FDC("fdc"); - String _bus; - - diskBus(String bus) { - _bus = bus; - } - - @Override - public String toString() { - return _bus; - } - } - - enum diskFmtType { - RAW("raw"), QCOW2("qcow2"); - String _fmtType; - - diskFmtType(String fmt) { - _fmtType = fmt; - } - - @Override - public String toString() { - return _fmtType; - } - } - - private deviceType _deviceType; /* floppy, disk, cdrom */ - private diskType _diskType; - private String _sourcePath; - private String _diskLabel; - private diskBus _bus; - private diskFmtType _diskFmtType; /* qcow2, raw etc. */ - private boolean _readonly = false; - private boolean _shareable = false; - private boolean _deferAttach = false; - - public void setDeviceType(deviceType deviceType) { - _deviceType = deviceType; - } - - public void defFileBasedDisk(String filePath, String diskLabel, - diskBus bus, diskFmtType diskFmtType) { - _diskType = diskType.FILE; - _deviceType = deviceType.DISK; - _sourcePath = filePath; - _diskLabel = diskLabel; - _diskFmtType = diskFmtType; - _bus = bus; - - } - - /* skip iso label */ - private String getDevLabel(int devId, diskBus bus) { - if (devId == 2) { - devId++; - } - - char suffix = (char) ('a' + devId); - if (bus == diskBus.SCSI) { - return "sd" + suffix; - } else if (bus == diskBus.VIRTIO) { - return "vd" + suffix; - } - return "hd" + suffix; - - } - - public void defFileBasedDisk(String filePath, int devId, diskBus bus, - diskFmtType diskFmtType) { - - _diskType = diskType.FILE; - _deviceType = deviceType.DISK; - _sourcePath = filePath; - _diskLabel = getDevLabel(devId, bus); - _diskFmtType = diskFmtType; - _bus = bus; - - } - - public void defISODisk(String volPath) { - _diskType = diskType.FILE; - _deviceType = deviceType.CDROM; - _sourcePath = volPath; - _diskLabel = "hdc"; - _diskFmtType = diskFmtType.RAW; - _bus = diskBus.IDE; - } - - public void defBlockBasedDisk(String diskName, int devId, diskBus bus) { - _diskType = diskType.BLOCK; - _deviceType = deviceType.DISK; - _diskFmtType = diskFmtType.RAW; - _sourcePath = diskName; - _diskLabel = getDevLabel(devId, bus); - _bus = bus; - } - - public void defBlockBasedDisk(String diskName, String diskLabel, - diskBus bus) { - _diskType = diskType.BLOCK; - _deviceType = deviceType.DISK; - _diskFmtType = diskFmtType.RAW; - _sourcePath = diskName; - _diskLabel = diskLabel; - _bus = bus; - } - - public void setReadonly() { - _readonly = true; - } - - public void setSharable() { - _shareable = true; - } - - public void setAttachDeferred(boolean deferAttach) { - _deferAttach = deferAttach; - } - - public boolean isAttachDeferred() { - return _deferAttach; - } - - public String getDiskPath() { - return _sourcePath; - } - - public String getDiskLabel() { - return _diskLabel; - } - - public deviceType getDeviceType() { - return _deviceType; - } - - public void setDiskPath(String volPath) { - this._sourcePath = volPath; - } - - public diskBus getBusType() { - return _bus; - } - - public int getDiskSeq() { - char suffix = this._diskLabel.charAt(this._diskLabel.length() - 1); - return suffix - 'a'; - } - - @Override - public String toString() { - StringBuilder diskBuilder = new StringBuilder(); - diskBuilder.append("\n"); - diskBuilder.append("\n"); - if (_diskType == diskType.FILE) { - diskBuilder.append("\n"); - } else if (_diskType == diskType.BLOCK) { - diskBuilder.append("\n"); - } - diskBuilder.append("\n"); - diskBuilder.append("\n"); - return diskBuilder.toString(); - } - } - - public static class InterfaceDef { - enum guestNetType { - BRIDGE("bridge"), NETWORK("network"), USER("user"), ETHERNET( - "ethernet"), INTERNAL("internal"); - String _type; - - guestNetType(String type) { - _type = type; - } - - @Override - public String toString() { - return _type; - } - } - - enum nicModel { - E1000("e1000"), VIRTIO("virtio"), RTL8139("rtl8139"), NE2KPCI( - "ne2k_pci"); - String _model; - - nicModel(String model) { - _model = model; - } - - @Override - public String toString() { - return _model; - } - } - - enum hostNicType { - DIRECT_ATTACHED_WITHOUT_DHCP, DIRECT_ATTACHED_WITH_DHCP, VNET, VLAN; - } - - private guestNetType _netType; /* - * bridge, ethernet, network, user, - * internal - */ - private hostNicType _hostNetType; /* Only used by agent java code */ - private String _sourceName; - private String _networkName; - private String _macAddr; - private String _ipAddr; - private String _scriptPath; - private nicModel _model; - - public void defBridgeNet(String brName, String targetBrName, - String macAddr, nicModel model) { - _netType = guestNetType.BRIDGE; - _sourceName = brName; - _networkName = targetBrName; - _macAddr = macAddr; - _model = model; - } - - public void defPrivateNet(String networkName, String targetName, - String macAddr, nicModel model) { - _netType = guestNetType.NETWORK; - _sourceName = networkName; - _networkName = targetName; - _macAddr = macAddr; - _model = model; - } - - public void setHostNetType(hostNicType hostNetType) { - _hostNetType = hostNetType; - } - - public hostNicType getHostNetType() { - return _hostNetType; - } - - public String getBrName() { - return _sourceName; - } - - public guestNetType getNetType() { - return _netType; - } - - public String getDevName() { - return _networkName; - } - - public String getMacAddress() { - return _macAddr; - } - - @Override - public String toString() { - StringBuilder netBuilder = new StringBuilder(); - netBuilder.append("\n"); - if (_netType == guestNetType.BRIDGE) { - netBuilder.append("\n"); - } else if (_netType == guestNetType.NETWORK) { - netBuilder.append("\n"); - } - if (_networkName != null) { - netBuilder.append("\n"); - } - if (_macAddr != null) { - netBuilder.append("\n"); - } - if (_model != null) { - netBuilder.append("\n"); - } - netBuilder.append("\n"); - return netBuilder.toString(); - } - } - - public static class ConsoleDef { - private final String _ttyPath; - private final String _type; - private final String _source; - private short _port = -1; - - public ConsoleDef(String type, String path, String source, short port) { - _type = type; - _ttyPath = path; - _source = source; - _port = port; - } - - @Override - public String toString() { - StringBuilder consoleBuilder = new StringBuilder(); - consoleBuilder.append("\n"); - if (_source != null) { - consoleBuilder.append("\n"); - } - if (_port != -1) { - consoleBuilder.append("\n"); - } - consoleBuilder.append("\n"); - return consoleBuilder.toString(); - } - } - - public static class SerialDef { - private final String _type; - private final String _source; - private short _port = -1; - - public SerialDef(String type, String source, short port) { - _type = type; - _source = source; - _port = port; - } - - @Override - public String toString() { - StringBuilder serialBuidler = new StringBuilder(); - serialBuidler.append("\n"); - if (_source != null) { - serialBuidler.append("\n"); - } - if (_port != -1) { - serialBuidler.append("\n"); - } - serialBuidler.append("\n"); - return serialBuidler.toString(); - } - } - - public static class GraphicDef { - private final String _type; - private short _port = -2; - private boolean _autoPort = false; - private final String _listenAddr; - private final String _passwd; - private final String _keyMap; - - public GraphicDef(String type, short port, boolean autoPort, - String listenAddr, String passwd, String keyMap) { - _type = type; - _port = port; - _autoPort = autoPort; - _listenAddr = listenAddr; - _passwd = passwd; - _keyMap = keyMap; - } - - @Override - public String toString() { - StringBuilder graphicBuilder = new StringBuilder(); - graphicBuilder.append("\n"); - return graphicBuilder.toString(); - } - } - - public static class InputDef { - private final String _type; /* tablet, mouse */ - private final String _bus; /* ps2, usb, xen */ - - public InputDef(String type, String bus) { - _type = type; - _bus = bus; - } - - @Override - public String toString() { - StringBuilder inputBuilder = new StringBuilder(); - inputBuilder.append("\n"); - return inputBuilder.toString(); - } - } - - public void setHvsType(String hvs) { - _hvsType = hvs; - } - - public void setDomainName(String domainName) { - _domName = domainName; - } - - public void setDomUUID(String uuid) { - _domUUID = uuid; - } - - public void setDomDescription(String desc) { - _desc = desc; - } - - public String getGuestOSType() { - return _desc; - } - - public void addComp(Object comp) { - components.put(comp.getClass().toString(), comp); - } - - public DevicesDef getDevices() { - Object o = components.get(DevicesDef.class.toString()); - if (o != null) { - return (DevicesDef) o; - } - return null; - } - - @Override - public String toString() { - StringBuilder vmBuilder = new StringBuilder(); - vmBuilder.append("\n"); - vmBuilder.append("" + _domName + "\n"); - if (_domUUID != null) { - vmBuilder.append("" + _domUUID + "\n"); - } - if (_desc != null) { - vmBuilder.append("" + _desc + "\n"); - } - for (Object o : components.values()) { - vmBuilder.append(o.toString()); - } - vmBuilder.append("\n"); - return vmBuilder.toString(); - } - - public static void main(String[] args) { - System.out.println("testing"); - LibvirtVMDef vm = new LibvirtVMDef(); - vm.setHvsType("kvm"); - vm.setDomainName("testing"); - vm.setDomUUID(UUID.randomUUID().toString()); - - GuestDef guest = new GuestDef(); - guest.setGuestType(GuestDef.guestType.KVM); - guest.setGuestArch("x86_64"); - guest.setMachineType("pc-0.11"); - guest.setBootOrder(GuestDef.bootOrder.HARDISK); - vm.addComp(guest); - - GuestResourceDef grd = new GuestResourceDef(); - grd.setMemorySize(512 * 1024); - grd.setVcpuNum(1); - vm.addComp(grd); - - FeaturesDef features = new FeaturesDef(); - features.addFeatures("pae"); - features.addFeatures("apic"); - features.addFeatures("acpi"); - vm.addComp(features); - - TermPolicy term = new TermPolicy(); - term.setCrashPolicy("destroy"); - term.setPowerOffPolicy("destroy"); - term.setRebootPolicy("destroy"); - vm.addComp(term); - - DevicesDef devices = new DevicesDef(); - devices.setEmulatorPath("/usr/bin/cloud-qemu-system-x86_64"); - - DiskDef hda = new DiskDef(); - hda.defFileBasedDisk("/path/to/hda1", 0, DiskDef.diskBus.VIRTIO, - DiskDef.diskFmtType.QCOW2); - devices.addDevice(hda); - - DiskDef hdb = new DiskDef(); - hdb.defFileBasedDisk("/path/to/hda2", 1, DiskDef.diskBus.VIRTIO, - DiskDef.diskFmtType.QCOW2); - devices.addDevice(hdb); - - InterfaceDef pubNic = new InterfaceDef(); - pubNic.defBridgeNet("cloudbr0", "vnet1", "00:16:3e:77:e2:a1", - InterfaceDef.nicModel.VIRTIO); - devices.addDevice(pubNic); - - InterfaceDef privNic = new InterfaceDef(); - privNic.defPrivateNet("cloud-private", null, "00:16:3e:77:e2:a2", - InterfaceDef.nicModel.VIRTIO); - devices.addDevice(privNic); - - InterfaceDef vlanNic = new InterfaceDef(); - vlanNic.defBridgeNet("vnbr1000", "tap1", "00:16:3e:77:e2:a2", - InterfaceDef.nicModel.VIRTIO); - devices.addDevice(vlanNic); - - SerialDef serial = new SerialDef("pty", null, (short) 0); - devices.addDevice(serial); - - ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0); - devices.addDevice(console); - - GraphicDef grap = new GraphicDef("vnc", (short) 0, true, null, null, - null); - devices.addDevice(grap); - - InputDef input = new InputDef("tablet", "usb"); - devices.addDevice(input); - - vm.addComp(devices); - - System.out.println(vm.toString()); - } + private String _hvsType; + private String _domName; + private String _domUUID; + private String _desc; + private final Map components = new HashMap(); + + public static class GuestDef { + enum guestType { + KVM, XEN, EXE + } + + enum bootOrder { + HARDISK("hd"), CDROM("cdrom"), FLOOPY("fd"), NETWORK("network"); + String _order; + + bootOrder(String order) { + _order = order; + } + + @Override + public String toString() { + return _order; + } + } + + private guestType _type; + private String _arch; + private String _loader; + private String _kernel; + private String _initrd; + private String _root; + private String _cmdline; + private List _bootdevs = new ArrayList(); + private String _machine; + + public void setGuestType(guestType type) { + _type = type; + } + + public void setGuestArch(String arch) { + _arch = arch; + } + + public void setMachineType(String machine) { + _machine = machine; + } + + public void setLoader(String loader) { + _loader = loader; + } + + public void setBootKernel(String kernel, String initrd, String rootdev, + String cmdline) { + _kernel = kernel; + _initrd = initrd; + _root = rootdev; + _cmdline = cmdline; + } + + public void setBootOrder(bootOrder order) { + _bootdevs.add(order); + } + + @Override + public String toString() { + if (_type == guestType.KVM) { + StringBuilder guestDef = new StringBuilder(); + guestDef.append("\n"); + guestDef.append("hvm\n"); + if (!_bootdevs.isEmpty()) { + for (bootOrder bo : _bootdevs) { + guestDef.append("\n"); + } + } + guestDef.append("\n"); + return guestDef.toString(); + } else + return null; + } + } + + public static class GuestResourceDef { + private long _mem; + private int _currentMem = -1; + private String _memBacking; + private int _vcpu = -1; + + public void setMemorySize(long mem) { + _mem = mem; + } + + public void setCurrentMem(int currMem) { + _currentMem = currMem; + } + + public void setMemBacking(String memBacking) { + _memBacking = memBacking; + } + + public void setVcpuNum(int vcpu) { + _vcpu = vcpu; + } + + @Override + public String toString() { + StringBuilder resBuidler = new StringBuilder(); + resBuidler.append("" + _mem + "\n"); + if (_currentMem != -1) { + resBuidler.append("" + _currentMem + + "\n"); + } + if (_memBacking != null) { + resBuidler.append("" + "<" + _memBacking + "/>" + + "\n"); + } + if (_vcpu != -1) { + resBuidler.append("" + _vcpu + "\n"); + } + return resBuidler.toString(); + } + } + + public static class FeaturesDef { + private final List _features = new ArrayList(); + + public void addFeatures(String feature) { + _features.add(feature); + } + + @Override + public String toString() { + StringBuilder feaBuilder = new StringBuilder(); + feaBuilder.append("\n"); + for (String feature : _features) { + feaBuilder.append("<" + feature + "/>\n"); + } + feaBuilder.append("\n"); + return feaBuilder.toString(); + } + } + + public static class TermPolicy { + private String _reboot; + private String _powerOff; + private String _crash; + + public TermPolicy() { + _reboot = _powerOff = _crash = "destroy"; + } + + public void setRebootPolicy(String rbPolicy) { + _reboot = rbPolicy; + } + + public void setPowerOffPolicy(String poPolicy) { + _powerOff = poPolicy; + } + + public void setCrashPolicy(String crashPolicy) { + _crash = crashPolicy; + } + + @Override + public String toString() { + StringBuilder term = new StringBuilder(); + term.append("" + _reboot + "\n"); + term.append("" + _powerOff + "\n"); + term.append("" + _powerOff + "\n"); + return term.toString(); + } + } + + public static class ClockDef { + public enum ClockOffset { + UTC("utc"), LOCALTIME("localtime"), TIMEZONE("timezone"), VARIABLE( + "variable"); + + private String _offset; + + private ClockOffset(String offset) { + _offset = offset; + } + + @Override + public String toString() { + return _offset; + } + } + + private ClockOffset _offset; + private String _timerName; + private String _tickPolicy; + private String _track; + + public ClockDef() { + _offset = ClockOffset.UTC; + } + + public void setClockOffset(ClockOffset offset) { + _offset = offset; + } + + public void setTimer(String timerName, String tickPolicy, String track) { + _timerName = timerName; + _tickPolicy = tickPolicy; + _track = track; + } + + @Override + public String toString() { + StringBuilder clockBuilder = new StringBuilder(); + clockBuilder.append("\n"); + if (_timerName != null) { + clockBuilder.append("\n"); + clockBuilder.append("\n"); + } + clockBuilder.append("\n"); + return clockBuilder.toString(); + } + } + + public static class DevicesDef { + private String _emulator; + private final Map> devices = new HashMap>(); + + public boolean addDevice(Object device) { + Object dev = devices.get(device.getClass().toString()); + if (dev == null) { + List devs = new ArrayList(); + devs.add(device); + devices.put(device.getClass().toString(), devs); + } else { + List devs = (List) dev; + devs.add(device); + } + return true; + } + + public void setEmulatorPath(String emulator) { + _emulator = emulator; + } + + @Override + public String toString() { + StringBuilder devicesBuilder = new StringBuilder(); + devicesBuilder.append("\n"); + if (_emulator != null) { + devicesBuilder.append("" + _emulator + + "\n"); + } + + for (List devs : devices.values()) { + for (Object dev : devs) { + devicesBuilder.append(dev.toString()); + } + } + devicesBuilder.append("\n"); + return devicesBuilder.toString(); + } + + @SuppressWarnings("unchecked") + public List getDisks() { + return (List) devices.get(DiskDef.class.toString()); + } + + @SuppressWarnings("unchecked") + public List getInterfaces() { + return (List) devices.get(InterfaceDef.class + .toString()); + } + + } + + public static class DiskDef { + enum deviceType { + FLOOPY("floopy"), DISK("disk"), CDROM("cdrom"); + String _type; + + deviceType(String type) { + _type = type; + } + + @Override + public String toString() { + return _type; + } + } + + enum diskType { + FILE("file"), BLOCK("block"), DIRECTROY("dir"); + String _diskType; + + diskType(String type) { + _diskType = type; + } + + @Override + public String toString() { + return _diskType; + } + } + + enum diskBus { + IDE("ide"), SCSI("scsi"), VIRTIO("virtio"), XEN("xen"), USB("usb"), UML( + "uml"), FDC("fdc"); + String _bus; + + diskBus(String bus) { + _bus = bus; + } + + @Override + public String toString() { + return _bus; + } + } + + enum diskFmtType { + RAW("raw"), QCOW2("qcow2"); + String _fmtType; + + diskFmtType(String fmt) { + _fmtType = fmt; + } + + @Override + public String toString() { + return _fmtType; + } + } + + private deviceType _deviceType; /* floppy, disk, cdrom */ + private diskType _diskType; + private String _sourcePath; + private String _diskLabel; + private diskBus _bus; + private diskFmtType _diskFmtType; /* qcow2, raw etc. */ + private boolean _readonly = false; + private boolean _shareable = false; + private boolean _deferAttach = false; + + public void setDeviceType(deviceType deviceType) { + _deviceType = deviceType; + } + + public void defFileBasedDisk(String filePath, String diskLabel, + diskBus bus, diskFmtType diskFmtType) { + _diskType = diskType.FILE; + _deviceType = deviceType.DISK; + _sourcePath = filePath; + _diskLabel = diskLabel; + _diskFmtType = diskFmtType; + _bus = bus; + + } + + /* skip iso label */ + private String getDevLabel(int devId, diskBus bus) { + if (devId == 2) { + devId++; + } + + char suffix = (char) ('a' + devId); + if (bus == diskBus.SCSI) { + return "sd" + suffix; + } else if (bus == diskBus.VIRTIO) { + return "vd" + suffix; + } + return "hd" + suffix; + + } + + public void defFileBasedDisk(String filePath, int devId, diskBus bus, + diskFmtType diskFmtType) { + + _diskType = diskType.FILE; + _deviceType = deviceType.DISK; + _sourcePath = filePath; + _diskLabel = getDevLabel(devId, bus); + _diskFmtType = diskFmtType; + _bus = bus; + + } + + public void defISODisk(String volPath) { + _diskType = diskType.FILE; + _deviceType = deviceType.CDROM; + _sourcePath = volPath; + _diskLabel = "hdc"; + _diskFmtType = diskFmtType.RAW; + _bus = diskBus.IDE; + } + + public void defBlockBasedDisk(String diskName, int devId, diskBus bus) { + _diskType = diskType.BLOCK; + _deviceType = deviceType.DISK; + _diskFmtType = diskFmtType.RAW; + _sourcePath = diskName; + _diskLabel = getDevLabel(devId, bus); + _bus = bus; + } + + public void defBlockBasedDisk(String diskName, String diskLabel, + diskBus bus) { + _diskType = diskType.BLOCK; + _deviceType = deviceType.DISK; + _diskFmtType = diskFmtType.RAW; + _sourcePath = diskName; + _diskLabel = diskLabel; + _bus = bus; + } + + public void setReadonly() { + _readonly = true; + } + + public void setSharable() { + _shareable = true; + } + + public void setAttachDeferred(boolean deferAttach) { + _deferAttach = deferAttach; + } + + public boolean isAttachDeferred() { + return _deferAttach; + } + + public String getDiskPath() { + return _sourcePath; + } + + public String getDiskLabel() { + return _diskLabel; + } + + public deviceType getDeviceType() { + return _deviceType; + } + + public void setDiskPath(String volPath) { + this._sourcePath = volPath; + } + + public diskBus getBusType() { + return _bus; + } + + public int getDiskSeq() { + char suffix = this._diskLabel.charAt(this._diskLabel.length() - 1); + return suffix - 'a'; + } + + @Override + public String toString() { + StringBuilder diskBuilder = new StringBuilder(); + diskBuilder.append("\n"); + diskBuilder.append("\n"); + if (_diskType == diskType.FILE) { + diskBuilder.append("\n"); + } else if (_diskType == diskType.BLOCK) { + diskBuilder.append("\n"); + } + diskBuilder.append("\n"); + diskBuilder.append("\n"); + return diskBuilder.toString(); + } + } + + public static class InterfaceDef { + enum guestNetType { + BRIDGE("bridge"), NETWORK("network"), USER("user"), ETHERNET( + "ethernet"), INTERNAL("internal"); + String _type; + + guestNetType(String type) { + _type = type; + } + + @Override + public String toString() { + return _type; + } + } + + enum nicModel { + E1000("e1000"), VIRTIO("virtio"), RTL8139("rtl8139"), NE2KPCI( + "ne2k_pci"); + String _model; + + nicModel(String model) { + _model = model; + } + + @Override + public String toString() { + return _model; + } + } + + enum hostNicType { + DIRECT_ATTACHED_WITHOUT_DHCP, DIRECT_ATTACHED_WITH_DHCP, VNET, VLAN; + } + + private guestNetType _netType; /* + * bridge, ethernet, network, user, + * internal + */ + private hostNicType _hostNetType; /* Only used by agent java code */ + private String _sourceName; + private String _networkName; + private String _macAddr; + private String _ipAddr; + private String _scriptPath; + private nicModel _model; + + public void defBridgeNet(String brName, String targetBrName, + String macAddr, nicModel model) { + _netType = guestNetType.BRIDGE; + _sourceName = brName; + _networkName = targetBrName; + _macAddr = macAddr; + _model = model; + } + + public void defPrivateNet(String networkName, String targetName, + String macAddr, nicModel model) { + _netType = guestNetType.NETWORK; + _sourceName = networkName; + _networkName = targetName; + _macAddr = macAddr; + _model = model; + } + + public void setHostNetType(hostNicType hostNetType) { + _hostNetType = hostNetType; + } + + public hostNicType getHostNetType() { + return _hostNetType; + } + + public String getBrName() { + return _sourceName; + } + + public guestNetType getNetType() { + return _netType; + } + + public String getDevName() { + return _networkName; + } + + public String getMacAddress() { + return _macAddr; + } + + @Override + public String toString() { + StringBuilder netBuilder = new StringBuilder(); + netBuilder.append("\n"); + if (_netType == guestNetType.BRIDGE) { + netBuilder.append("\n"); + } else if (_netType == guestNetType.NETWORK) { + netBuilder.append("\n"); + } + if (_networkName != null) { + netBuilder.append("\n"); + } + if (_macAddr != null) { + netBuilder.append("\n"); + } + if (_model != null) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); + return netBuilder.toString(); + } + } + + public static class ConsoleDef { + private final String _ttyPath; + private final String _type; + private final String _source; + private short _port = -1; + + public ConsoleDef(String type, String path, String source, short port) { + _type = type; + _ttyPath = path; + _source = source; + _port = port; + } + + @Override + public String toString() { + StringBuilder consoleBuilder = new StringBuilder(); + consoleBuilder.append("\n"); + if (_source != null) { + consoleBuilder.append("\n"); + } + if (_port != -1) { + consoleBuilder.append("\n"); + } + consoleBuilder.append("\n"); + return consoleBuilder.toString(); + } + } + + public static class SerialDef { + private final String _type; + private final String _source; + private short _port = -1; + + public SerialDef(String type, String source, short port) { + _type = type; + _source = source; + _port = port; + } + + @Override + public String toString() { + StringBuilder serialBuidler = new StringBuilder(); + serialBuidler.append("\n"); + if (_source != null) { + serialBuidler.append("\n"); + } + if (_port != -1) { + serialBuidler.append("\n"); + } + serialBuidler.append("\n"); + return serialBuidler.toString(); + } + } + + public static class GraphicDef { + private final String _type; + private short _port = -2; + private boolean _autoPort = false; + private final String _listenAddr; + private final String _passwd; + private final String _keyMap; + + public GraphicDef(String type, short port, boolean autoPort, + String listenAddr, String passwd, String keyMap) { + _type = type; + _port = port; + _autoPort = autoPort; + _listenAddr = listenAddr; + _passwd = passwd; + _keyMap = keyMap; + } + + @Override + public String toString() { + StringBuilder graphicBuilder = new StringBuilder(); + graphicBuilder.append("\n"); + return graphicBuilder.toString(); + } + } + + public static class InputDef { + private final String _type; /* tablet, mouse */ + private final String _bus; /* ps2, usb, xen */ + + public InputDef(String type, String bus) { + _type = type; + _bus = bus; + } + + @Override + public String toString() { + StringBuilder inputBuilder = new StringBuilder(); + inputBuilder.append("\n"); + return inputBuilder.toString(); + } + } + + public void setHvsType(String hvs) { + _hvsType = hvs; + } + + public void setDomainName(String domainName) { + _domName = domainName; + } + + public void setDomUUID(String uuid) { + _domUUID = uuid; + } + + public void setDomDescription(String desc) { + _desc = desc; + } + + public String getGuestOSType() { + return _desc; + } + + public void addComp(Object comp) { + components.put(comp.getClass().toString(), comp); + } + + public DevicesDef getDevices() { + Object o = components.get(DevicesDef.class.toString()); + if (o != null) { + return (DevicesDef) o; + } + return null; + } + + @Override + public String toString() { + StringBuilder vmBuilder = new StringBuilder(); + vmBuilder.append("\n"); + vmBuilder.append("" + _domName + "\n"); + if (_domUUID != null) { + vmBuilder.append("" + _domUUID + "\n"); + } + if (_desc != null) { + vmBuilder.append("" + _desc + "\n"); + } + for (Object o : components.values()) { + vmBuilder.append(o.toString()); + } + vmBuilder.append("\n"); + return vmBuilder.toString(); + } + + public static void main(String[] args) { + System.out.println("testing"); + LibvirtVMDef vm = new LibvirtVMDef(); + vm.setHvsType("kvm"); + vm.setDomainName("testing"); + vm.setDomUUID(UUID.randomUUID().toString()); + + GuestDef guest = new GuestDef(); + guest.setGuestType(GuestDef.guestType.KVM); + guest.setGuestArch("x86_64"); + guest.setMachineType("pc-0.11"); + guest.setBootOrder(GuestDef.bootOrder.HARDISK); + vm.addComp(guest); + + GuestResourceDef grd = new GuestResourceDef(); + grd.setMemorySize(512 * 1024); + grd.setVcpuNum(1); + vm.addComp(grd); + + FeaturesDef features = new FeaturesDef(); + features.addFeatures("pae"); + features.addFeatures("apic"); + features.addFeatures("acpi"); + vm.addComp(features); + + TermPolicy term = new TermPolicy(); + term.setCrashPolicy("destroy"); + term.setPowerOffPolicy("destroy"); + term.setRebootPolicy("destroy"); + vm.addComp(term); + + DevicesDef devices = new DevicesDef(); + devices.setEmulatorPath("/usr/bin/cloud-qemu-system-x86_64"); + + DiskDef hda = new DiskDef(); + hda.defFileBasedDisk("/path/to/hda1", 0, DiskDef.diskBus.VIRTIO, + DiskDef.diskFmtType.QCOW2); + devices.addDevice(hda); + + DiskDef hdb = new DiskDef(); + hdb.defFileBasedDisk("/path/to/hda2", 1, DiskDef.diskBus.VIRTIO, + DiskDef.diskFmtType.QCOW2); + devices.addDevice(hdb); + + InterfaceDef pubNic = new InterfaceDef(); + pubNic.defBridgeNet("cloudbr0", "vnet1", "00:16:3e:77:e2:a1", + InterfaceDef.nicModel.VIRTIO); + devices.addDevice(pubNic); + + InterfaceDef privNic = new InterfaceDef(); + privNic.defPrivateNet("cloud-private", null, "00:16:3e:77:e2:a2", + InterfaceDef.nicModel.VIRTIO); + devices.addDevice(privNic); + + InterfaceDef vlanNic = new InterfaceDef(); + vlanNic.defBridgeNet("vnbr1000", "tap1", "00:16:3e:77:e2:a2", + InterfaceDef.nicModel.VIRTIO); + devices.addDevice(vlanNic); + + SerialDef serial = new SerialDef("pty", null, (short) 0); + devices.addDevice(serial); + + ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0); + devices.addDevice(console); + + GraphicDef grap = new GraphicDef("vnc", (short) 0, true, null, null, + null); + devices.addDevice(grap); + + InputDef input = new InputDef("tablet", "usb"); + devices.addDevice(input); + + vm.addComp(devices); + + System.out.println(vm.toString()); + } } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtXMLParser.java index 641e7f67eb7..b73ea0f0c3f 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtXMLParser.java @@ -28,45 +28,45 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class LibvirtXMLParser extends DefaultHandler { - private static final Logger s_logger = Logger - .getLogger(LibvirtXMLParser.class); - protected static SAXParserFactory s_spf; + private static final Logger s_logger = Logger + .getLogger(LibvirtXMLParser.class); + protected static SAXParserFactory s_spf; - static { - s_spf = SAXParserFactory.newInstance(); + static { + s_spf = SAXParserFactory.newInstance(); - } - protected SAXParser _sp; - protected boolean _initialized = false; + } + protected SAXParser _sp; + protected boolean _initialized = false; - public LibvirtXMLParser() { + public LibvirtXMLParser() { - try { - _sp = s_spf.newSAXParser(); - _initialized = true; - } catch (Exception ex) { - } + try { + _sp = s_spf.newSAXParser(); + _initialized = true; + } catch (Exception ex) { + } - } + } - public boolean parseDomainXML(String domXML) { - if (!_initialized) { - return false; - } - try { - _sp.parse(new InputSource(new StringReader(domXML)), this); - return true; - } catch (SAXException se) { - s_logger.warn(se.getMessage()); - } catch (IOException ie) { - s_logger.error(ie.getMessage()); - } - return false; - } + public boolean parseDomainXML(String domXML) { + if (!_initialized) { + return false; + } + try { + _sp.parse(new InputSource(new StringReader(domXML)), this); + return true; + } catch (SAXException se) { + s_logger.warn(se.getMessage()); + } catch (IOException ie) { + s_logger.error(ie.getMessage()); + } + return false; + } - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - } + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + } } diff --git a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyAuthenticationResult.java b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyAuthenticationResult.java index db2424f3347..6ed211a2d2f 100644 --- a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyAuthenticationResult.java +++ b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyAuthenticationResult.java @@ -17,64 +17,64 @@ package com.cloud.agent.resource.consoleproxy; public class ConsoleProxyAuthenticationResult { - private boolean success; - private boolean isReauthentication; - private String host; - private int port; - private String tunnelUrl; - private String tunnelSession; - - public ConsoleProxyAuthenticationResult() { - success = false; - isReauthentication = false; - port = 0; - } + private boolean success; + private boolean isReauthentication; + private String host; + private int port; + private String tunnelUrl; + private String tunnelSession; + + public ConsoleProxyAuthenticationResult() { + success = false; + isReauthentication = false; + port = 0; + } - public boolean isSuccess() { - return success; - } + public boolean isSuccess() { + return success; + } - public void setSuccess(boolean success) { - this.success = success; - } + public void setSuccess(boolean success) { + this.success = success; + } - public boolean isReauthentication() { - return isReauthentication; - } + public boolean isReauthentication() { + return isReauthentication; + } - public void setReauthentication(boolean isReauthentication) { - this.isReauthentication = isReauthentication; - } + public void setReauthentication(boolean isReauthentication) { + this.isReauthentication = isReauthentication; + } - public String getHost() { - return host; - } + public String getHost() { + return host; + } - public void setHost(String host) { - this.host = host; - } + public void setHost(String host) { + this.host = host; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } - public void setPort(int port) { - this.port = port; - } + public void setPort(int port) { + this.port = port; + } - public String getTunnelUrl() { - return tunnelUrl; - } + public String getTunnelUrl() { + return tunnelUrl; + } - public void setTunnelUrl(String tunnelUrl) { - this.tunnelUrl = tunnelUrl; - } + public void setTunnelUrl(String tunnelUrl) { + this.tunnelUrl = tunnelUrl; + } - public String getTunnelSession() { - return tunnelSession; - } + public String getTunnelSession() { + return tunnelSession; + } - public void setTunnelSession(String tunnelSession) { - this.tunnelSession = tunnelSession; - } + public void setTunnelSession(String tunnelSession) { + this.tunnelSession = tunnelSession; + } } diff --git a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java index 575dcf1e5a6..48f507900d6 100644 --- a/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java +++ b/agent/src/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java @@ -78,415 +78,415 @@ import com.google.gson.Gson; * */ public class ConsoleProxyResource extends ServerResourceBase implements - ServerResource { - static final Logger s_logger = Logger.getLogger(ConsoleProxyResource.class); + ServerResource { + static final Logger s_logger = Logger.getLogger(ConsoleProxyResource.class); - private final Properties _properties = new Properties(); - private Thread _consoleProxyMain = null; + private final Properties _properties = new Properties(); + private Thread _consoleProxyMain = null; - long _proxyVmId; - int _proxyPort; + long _proxyVmId; + int _proxyPort; - String _localgw; - String _eth1ip; - String _eth1mask; - String _pubIp; + String _localgw; + String _eth1ip; + String _eth1mask; + String _pubIp; - @Override - public Answer executeRequest(final Command cmd) { - if (cmd instanceof CheckConsoleProxyLoadCommand) { - return execute((CheckConsoleProxyLoadCommand) cmd); - } else if (cmd instanceof WatchConsoleProxyLoadCommand) { - return execute((WatchConsoleProxyLoadCommand) cmd); - } else if (cmd instanceof ReadyCommand) { - s_logger.info("Receive ReadyCommand, response with ReadyAnswer"); - return new ReadyAnswer((ReadyCommand) cmd); - } else if (cmd instanceof CheckHealthCommand) { - return new CheckHealthAnswer((CheckHealthCommand) cmd, true); - } else if (cmd instanceof StartConsoleProxyAgentHttpHandlerCommand) { - return execute((StartConsoleProxyAgentHttpHandlerCommand) cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } + @Override + public Answer executeRequest(final Command cmd) { + if (cmd instanceof CheckConsoleProxyLoadCommand) { + return execute((CheckConsoleProxyLoadCommand) cmd); + } else if (cmd instanceof WatchConsoleProxyLoadCommand) { + return execute((WatchConsoleProxyLoadCommand) cmd); + } else if (cmd instanceof ReadyCommand) { + s_logger.info("Receive ReadyCommand, response with ReadyAnswer"); + return new ReadyAnswer((ReadyCommand) cmd); + } else if (cmd instanceof CheckHealthCommand) { + return new CheckHealthAnswer((CheckHealthCommand) cmd, true); + } else if (cmd instanceof StartConsoleProxyAgentHttpHandlerCommand) { + return execute((StartConsoleProxyAgentHttpHandlerCommand) cmd); + } else { + return Answer.createUnsupportedCommandAnswer(cmd); + } + } - private Answer execute(StartConsoleProxyAgentHttpHandlerCommand cmd) { - launchConsoleProxy(cmd.getKeystoreBits(), cmd.getKeystorePassword(), cmd.getEncryptorPassword()); - return new Answer(cmd); - } + private Answer execute(StartConsoleProxyAgentHttpHandlerCommand cmd) { + launchConsoleProxy(cmd.getKeystoreBits(), cmd.getKeystorePassword(), cmd.getEncryptorPassword()); + return new Answer(cmd); + } - private void disableRpFilter() { - try { - FileWriter fstream = new FileWriter( - "/proc/sys/net/ipv4/conf/eth2/rp_filter"); - BufferedWriter out = new BufferedWriter(fstream); - out.write("0"); - out.close(); - } catch (IOException e) { - s_logger.warn("Unable to disable rp_filter"); - } - } + private void disableRpFilter() { + try { + FileWriter fstream = new FileWriter( + "/proc/sys/net/ipv4/conf/eth2/rp_filter"); + BufferedWriter out = new BufferedWriter(fstream); + out.write("0"); + out.close(); + } catch (IOException e) { + s_logger.warn("Unable to disable rp_filter"); + } + } - private boolean copyCertToDirectory(String certificate, String filePath) - throws IOException { - boolean success; - // copy cert to the dir - FileWriter fstream = new FileWriter(filePath); - BufferedWriter out = new BufferedWriter(fstream); - out.write(certificate); - // Close the output stream - out.close(); - success = true; - return success; - } + private boolean copyCertToDirectory(String certificate, String filePath) + throws IOException { + boolean success; + // copy cert to the dir + FileWriter fstream = new FileWriter(filePath); + BufferedWriter out = new BufferedWriter(fstream); + out.write(certificate); + // Close the output stream + out.close(); + success = true; + return success; + } - protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), - cmd.getProxyVmName(), cmd.getProxyManagementIp(), - cmd.getProxyCmdPort()); - } + protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { + return executeProxyLoadScan(cmd, cmd.getProxyVmId(), + cmd.getProxyVmName(), cmd.getProxyManagementIp(), + cmd.getProxyCmdPort()); + } - protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), - cmd.getProxyVmName(), cmd.getProxyManagementIp(), - cmd.getProxyCmdPort()); - } + protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { + return executeProxyLoadScan(cmd, cmd.getProxyVmId(), + cmd.getProxyVmName(), cmd.getProxyManagementIp(), + cmd.getProxyCmdPort()); + } - private Answer executeProxyLoadScan(final Command cmd, - final long proxyVmId, final String proxyVmName, - final String proxyManagementIp, final int cmdPort) { - String result = null; + private Answer executeProxyLoadScan(final Command cmd, + final long proxyVmId, final String proxyVmName, + final String proxyManagementIp, final int cmdPort) { + String result = null; - final StringBuffer sb = new StringBuffer(); - sb.append("http://").append(proxyManagementIp).append(":" + cmdPort) - .append("/cmd/getstatus"); + final StringBuffer sb = new StringBuffer(); + sb.append("http://").append(proxyManagementIp).append(":" + cmdPort) + .append("/cmd/getstatus"); - boolean success = true; - try { - final URL url = new URL(sb.toString()); - final URLConnection conn = url.openConnection(); + boolean success = true; + try { + final URL url = new URL(sb.toString()); + final URLConnection conn = url.openConnection(); - final InputStream is = conn.getInputStream(); - final BufferedReader reader = new BufferedReader( - new InputStreamReader(is)); - final StringBuilder sb2 = new StringBuilder(); - String line = null; - try { - while ((line = reader.readLine()) != null) - sb2.append(line + "\n"); - result = sb2.toString(); - } catch (final IOException e) { - success = false; - } finally { - try { - is.close(); - } catch (final IOException e) { - s_logger.warn("Exception when closing , console proxy address : " - + proxyManagementIp); - success = false; - } - } - } catch (final IOException e) { - s_logger.warn("Unable to open console proxy command port url, console proxy address : " - + proxyManagementIp); - success = false; - } + final InputStream is = conn.getInputStream(); + final BufferedReader reader = new BufferedReader( + new InputStreamReader(is)); + final StringBuilder sb2 = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) + sb2.append(line + "\n"); + result = sb2.toString(); + } catch (final IOException e) { + success = false; + } finally { + try { + is.close(); + } catch (final IOException e) { + s_logger.warn("Exception when closing , console proxy address : " + + proxyManagementIp); + success = false; + } + } + } catch (final IOException e) { + s_logger.warn("Unable to open console proxy command port url, console proxy address : " + + proxyManagementIp); + success = false; + } - return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, - result); - } + return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, + result); + } - @Override - protected String getDefaultScriptsDir() { - return null; - } + @Override + protected String getDefaultScriptsDir() { + return null; + } - public Type getType() { - return Host.Type.ConsoleProxy; - } + public Type getType() { + return Host.Type.ConsoleProxy; + } - @Override - public synchronized StartupCommand[] initialize() { - final StartupProxyCommand cmd = new StartupProxyCommand(); - fillNetworkInformation(cmd); - cmd.setProxyPort(_proxyPort); - cmd.setProxyVmId(_proxyVmId); - if (_pubIp != null) - cmd.setPublicIpAddress(_pubIp); - return new StartupCommand[] { cmd }; - } + @Override + public synchronized StartupCommand[] initialize() { + final StartupProxyCommand cmd = new StartupProxyCommand(); + fillNetworkInformation(cmd); + cmd.setProxyPort(_proxyPort); + cmd.setProxyVmId(_proxyVmId); + if (_pubIp != null) + cmd.setPublicIpAddress(_pubIp); + return new StartupCommand[] { cmd }; + } - @Override - public void disconnected() { - } + @Override + public void disconnected() { + } - @Override - public PingCommand getCurrentStatus(long id) { - return new PingCommand(Type.ConsoleProxy, id); - } + @Override + public PingCommand getCurrentStatus(long id) { + return new PingCommand(Type.ConsoleProxy, id); + } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - _localgw = (String) params.get("localgw"); - _eth1mask = (String) params.get("eth1mask"); - _eth1ip = (String) params.get("eth1ip"); - if (_eth1ip != null) { - params.put("private.network.device", "eth1"); - } else { - s_logger.warn("WARNING: eth1ip parameter is not found!"); - } + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + _localgw = (String) params.get("localgw"); + _eth1mask = (String) params.get("eth1mask"); + _eth1ip = (String) params.get("eth1ip"); + if (_eth1ip != null) { + params.put("private.network.device", "eth1"); + } else { + s_logger.warn("WARNING: eth1ip parameter is not found!"); + } - String eth2ip = (String) params.get("eth2ip"); - if (eth2ip != null) { - params.put("public.network.device", "eth2"); - } else { - s_logger.warn("WARNING: eth2ip parameter is not found!"); - } + String eth2ip = (String) params.get("eth2ip"); + if (eth2ip != null) { + params.put("public.network.device", "eth2"); + } else { + s_logger.warn("WARNING: eth2ip parameter is not found!"); + } - super.configure(name, params); + super.configure(name, params); - for (Map.Entry entry : params.entrySet()) { - _properties.put(entry.getKey(), entry.getValue()); - } + for (Map.Entry entry : params.entrySet()) { + _properties.put(entry.getKey(), entry.getValue()); + } - String value = (String) params.get("premium"); - if (value != null && value.equals("premium")) - _proxyPort = 443; - else { - value = (String) params.get("consoleproxy.httpListenPort"); - _proxyPort = NumbersUtil.parseInt(value, 80); - } + String value = (String) params.get("premium"); + if (value != null && value.equals("premium")) + _proxyPort = 443; + else { + value = (String) params.get("consoleproxy.httpListenPort"); + _proxyPort = NumbersUtil.parseInt(value, 80); + } - value = (String) params.get("proxy_vm"); - _proxyVmId = NumbersUtil.parseLong(value, 0); + value = (String) params.get("proxy_vm"); + _proxyVmId = NumbersUtil.parseLong(value, 0); - if (_localgw != null) { - String mgmtHost = (String) params.get("host"); - addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, mgmtHost); + if (_localgw != null) { + String mgmtHost = (String) params.get("host"); + addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, mgmtHost); - String internalDns1 = (String) params.get("internaldns1"); - if (internalDns1 == null) { - s_logger.warn("No DNS entry found during configuration of NfsSecondaryStorage"); - } else { - addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, - internalDns1); - } + String internalDns1 = (String) params.get("internaldns1"); + if (internalDns1 == null) { + s_logger.warn("No DNS entry found during configuration of NfsSecondaryStorage"); + } else { + addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, + internalDns1); + } - String internalDns2 = (String) params.get("internaldns2"); - if (internalDns2 != null) { - addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, - internalDns2); - } - } + String internalDns2 = (String) params.get("internaldns2"); + if (internalDns2 != null) { + addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, + internalDns2); + } + } - _pubIp = (String) params.get("public.ip"); + _pubIp = (String) params.get("public.ip"); - value = (String) params.get("disable_rp_filter"); - if (value != null && value.equalsIgnoreCase("true")) { - disableRpFilter(); - } + value = (String) params.get("disable_rp_filter"); + if (value != null && value.equalsIgnoreCase("true")) { + disableRpFilter(); + } - if (s_logger.isInfoEnabled()) - s_logger.info("Receive proxyVmId in ConsoleProxyResource configuration as " - + _proxyVmId); + if (s_logger.isInfoEnabled()) + s_logger.info("Receive proxyVmId in ConsoleProxyResource configuration as " + + _proxyVmId); - return true; - } + return true; + } - private void addRouteToInternalIpOrCidr(String localgw, String eth1ip, - String eth1mask, String destIpOrCidr) { - s_logger.debug("addRouteToInternalIp: localgw=" + localgw + ", eth1ip=" - + eth1ip + ", eth1mask=" + eth1mask + ",destIp=" + destIpOrCidr); - if (destIpOrCidr == null) { - s_logger.debug("addRouteToInternalIp: destIp is null"); - return; - } - if (!NetUtils.isValidIp(destIpOrCidr) - && !NetUtils.isValidCIDR(destIpOrCidr)) { - s_logger.warn(" destIp is not a valid ip address or cidr destIp=" - + destIpOrCidr); - return; - } - boolean inSameSubnet = false; - if (NetUtils.isValidIp(destIpOrCidr)) { - if (eth1ip != null && eth1mask != null) { - inSameSubnet = NetUtils.sameSubnet(eth1ip, destIpOrCidr, - eth1mask); - } else { - s_logger.warn("addRouteToInternalIp: unable to determine same subnet: _eth1ip=" - + eth1ip - + ", dest ip=" - + destIpOrCidr - + ", _eth1mask=" - + eth1mask); - } - } else { - inSameSubnet = NetUtils.isNetworkAWithinNetworkB(destIpOrCidr, - NetUtils.ipAndNetMaskToCidr(eth1ip, eth1mask)); - } - if (inSameSubnet) { - s_logger.debug("addRouteToInternalIp: dest ip " + destIpOrCidr - + " is in the same subnet as eth1 ip " + eth1ip); - return; - } - Script command = new Script("/bin/bash", s_logger); - command.add("-c"); - command.add("ip route delete " + destIpOrCidr); - command.execute(); - command = new Script("/bin/bash", s_logger); - command.add("-c"); - command.add("ip route add " + destIpOrCidr + " via " + localgw); - String result = command.execute(); - if (result != null) { - s_logger.warn("Error in configuring route to internal ip err=" - + result); - } else { - s_logger.debug("addRouteToInternalIp: added route to internal ip=" - + destIpOrCidr + " via " + localgw); - } - } + private void addRouteToInternalIpOrCidr(String localgw, String eth1ip, + String eth1mask, String destIpOrCidr) { + s_logger.debug("addRouteToInternalIp: localgw=" + localgw + ", eth1ip=" + + eth1ip + ", eth1mask=" + eth1mask + ",destIp=" + destIpOrCidr); + if (destIpOrCidr == null) { + s_logger.debug("addRouteToInternalIp: destIp is null"); + return; + } + if (!NetUtils.isValidIp(destIpOrCidr) + && !NetUtils.isValidCIDR(destIpOrCidr)) { + s_logger.warn(" destIp is not a valid ip address or cidr destIp=" + + destIpOrCidr); + return; + } + boolean inSameSubnet = false; + if (NetUtils.isValidIp(destIpOrCidr)) { + if (eth1ip != null && eth1mask != null) { + inSameSubnet = NetUtils.sameSubnet(eth1ip, destIpOrCidr, + eth1mask); + } else { + s_logger.warn("addRouteToInternalIp: unable to determine same subnet: _eth1ip=" + + eth1ip + + ", dest ip=" + + destIpOrCidr + + ", _eth1mask=" + + eth1mask); + } + } else { + inSameSubnet = NetUtils.isNetworkAWithinNetworkB(destIpOrCidr, + NetUtils.ipAndNetMaskToCidr(eth1ip, eth1mask)); + } + if (inSameSubnet) { + s_logger.debug("addRouteToInternalIp: dest ip " + destIpOrCidr + + " is in the same subnet as eth1 ip " + eth1ip); + return; + } + Script command = new Script("/bin/bash", s_logger); + command.add("-c"); + command.add("ip route delete " + destIpOrCidr); + command.execute(); + command = new Script("/bin/bash", s_logger); + command.add("-c"); + command.add("ip route add " + destIpOrCidr + " via " + localgw); + String result = command.execute(); + if (result != null) { + s_logger.warn("Error in configuring route to internal ip err=" + + result); + } else { + s_logger.debug("addRouteToInternalIp: added route to internal ip=" + + destIpOrCidr + " via " + localgw); + } + } - @Override - public String getName() { - return _name; - } + @Override + public String getName() { + return _name; + } - private void launchConsoleProxy(final byte[] ksBits, final String ksPassword, final String encryptorPassword) { - final Object resource = this; - if (_consoleProxyMain == null) { - _consoleProxyMain = new Thread(new Runnable() { - public void run() { - try { - Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); - try { - Method methodSetup = consoleProxyClazz.getMethod( - "setEncryptorPassword", String.class); - methodSetup.invoke(null, encryptorPassword); - - Method method = consoleProxyClazz.getMethod( - "startWithContext", Properties.class, - Object.class, byte[].class, String.class); - method.invoke(null, _properties, resource, ksBits, - ksPassword); - } 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(); - } else { - s_logger.info("com.cloud.consoleproxy.ConsoleProxy is already running"); - - try { - Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); - Method methodSetup = consoleProxyClazz.getMethod("setEncryptorPassword", String.class); - methodSetup.invoke(null, encryptorPassword); - } 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()); - } - } - } + private void launchConsoleProxy(final byte[] ksBits, final String ksPassword, final String encryptorPassword) { + final Object resource = this; + if (_consoleProxyMain == null) { + _consoleProxyMain = new Thread(new Runnable() { + public void run() { + try { + Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); + try { + Method methodSetup = consoleProxyClazz.getMethod( + "setEncryptorPassword", String.class); + methodSetup.invoke(null, encryptorPassword); + + Method method = consoleProxyClazz.getMethod( + "startWithContext", Properties.class, + Object.class, byte[].class, String.class); + method.invoke(null, _properties, resource, ksBits, + ksPassword); + } 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(); + } else { + s_logger.info("com.cloud.consoleproxy.ConsoleProxy is already running"); + + try { + Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); + Method methodSetup = consoleProxyClazz.getMethod("setEncryptorPassword", String.class); + methodSetup.invoke(null, encryptorPassword); + } 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()); + } + } + } - public String authenticateConsoleAccess(String host, String port, - String vmId, String sid, String ticket, Boolean isReauthentication) { - - ConsoleAccessAuthenticationCommand cmd = new ConsoleAccessAuthenticationCommand( - host, port, vmId, sid, ticket); - cmd.setReauthenticating(isReauthentication); - - ConsoleProxyAuthenticationResult result = new ConsoleProxyAuthenticationResult(); - result.setSuccess(false); - result.setReauthentication(isReauthentication); + public String authenticateConsoleAccess(String host, String port, + String vmId, String sid, String ticket, Boolean isReauthentication) { + + ConsoleAccessAuthenticationCommand cmd = new ConsoleAccessAuthenticationCommand( + host, port, vmId, sid, ticket); + cmd.setReauthenticating(isReauthentication); + + ConsoleProxyAuthenticationResult result = new ConsoleProxyAuthenticationResult(); + result.setSuccess(false); + result.setReauthentication(isReauthentication); - try { - AgentControlAnswer answer = getAgentControl().sendRequest(cmd, 10000); - - if (answer != null) { - ConsoleAccessAuthenticationAnswer authAnswer = (ConsoleAccessAuthenticationAnswer)answer; - result.setSuccess(authAnswer.succeeded()); - result.setHost(authAnswer.getHost()); - result.setPort(authAnswer.getPort()); - result.setTunnelUrl(authAnswer.getTunnelUrl()); - result.setTunnelSession(authAnswer.getTunnelSession()); - } else { - s_logger.error("Authentication failed for vm: " + vmId + " with sid: " + sid); - } - } catch (AgentControlChannelException e) { - s_logger.error("Unable to send out console access authentication request due to " - + e.getMessage(), e); - } + try { + AgentControlAnswer answer = getAgentControl().sendRequest(cmd, 10000); + + if (answer != null) { + ConsoleAccessAuthenticationAnswer authAnswer = (ConsoleAccessAuthenticationAnswer)answer; + result.setSuccess(authAnswer.succeeded()); + result.setHost(authAnswer.getHost()); + result.setPort(authAnswer.getPort()); + result.setTunnelUrl(authAnswer.getTunnelUrl()); + result.setTunnelSession(authAnswer.getTunnelSession()); + } else { + s_logger.error("Authentication failed for vm: " + vmId + " with sid: " + sid); + } + } catch (AgentControlChannelException e) { + s_logger.error("Unable to send out console access authentication request due to " + + e.getMessage(), e); + } - return new Gson().toJson(result); - } + return new Gson().toJson(result); + } - public void reportLoadInfo(String gsonLoadInfo) { - ConsoleProxyLoadReportCommand cmd = new ConsoleProxyLoadReportCommand( - _proxyVmId, gsonLoadInfo); - try { - getAgentControl().postRequest(cmd); + public void reportLoadInfo(String gsonLoadInfo) { + ConsoleProxyLoadReportCommand cmd = new ConsoleProxyLoadReportCommand( + _proxyVmId, gsonLoadInfo); + try { + getAgentControl().postRequest(cmd); - if (s_logger.isDebugEnabled()) - s_logger.debug("Report proxy load info, proxy : " + _proxyVmId - + ", load: " + gsonLoadInfo); - } catch (AgentControlChannelException e) { - s_logger.error( - "Unable to send out load info due to " + e.getMessage(), e); - } - } + if (s_logger.isDebugEnabled()) + s_logger.debug("Report proxy load info, proxy : " + _proxyVmId + + ", load: " + gsonLoadInfo); + } catch (AgentControlChannelException e) { + s_logger.error( + "Unable to send out load info due to " + e.getMessage(), e); + } + } - public void ensureRoute(String address) { - if (_localgw != null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Ensure route for " + address + " via " - + _localgw); + public void ensureRoute(String address) { + if (_localgw != null) { + if (s_logger.isDebugEnabled()) + s_logger.debug("Ensure route for " + address + " via " + + _localgw); - // this method won't be called in high frequency, serialize access - // to script execution - synchronized (this) { - try { - addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, - address); - } catch (Throwable e) { - s_logger.warn( - "Unexpected exception while adding internal route to " - + address, e); - } - } - } - } + // this method won't be called in high frequency, serialize access + // to script execution + synchronized (this) { + try { + addRouteToInternalIpOrCidr(_localgw, _eth1ip, _eth1mask, + address); + } catch (Throwable e) { + s_logger.warn( + "Unexpected exception while adding internal route to " + + address, e); + } + } + } + } } diff --git a/agent/src/com/cloud/agent/storage/KVMPhysicalDisk.java b/agent/src/com/cloud/agent/storage/KVMPhysicalDisk.java index 81cd0f307e8..d0e43df9e61 100644 --- a/agent/src/com/cloud/agent/storage/KVMPhysicalDisk.java +++ b/agent/src/com/cloud/agent/storage/KVMPhysicalDisk.java @@ -17,66 +17,66 @@ package com.cloud.agent.storage; public class KVMPhysicalDisk { - private String path; - private String name; - private KVMStoragePool pool; + private String path; + private String name; + private KVMStoragePool pool; - public static enum PhysicalDiskFormat { - RAW("raw"), QCOW2("qcow2"); - String format; + public static enum PhysicalDiskFormat { + RAW("raw"), QCOW2("qcow2"); + String format; - private PhysicalDiskFormat(String format) { - this.format = format; - } + private PhysicalDiskFormat(String format) { + this.format = format; + } - public String toString() { - return this.format; - } - } + public String toString() { + return this.format; + } + } - private PhysicalDiskFormat format; - private long size; - private long virtualSize; + private PhysicalDiskFormat format; + private long size; + private long virtualSize; - public KVMPhysicalDisk(String path, String name, KVMStoragePool pool) { - this.path = path; - this.name = name; - this.pool = pool; - } + public KVMPhysicalDisk(String path, String name, KVMStoragePool pool) { + this.path = path; + this.name = name; + this.pool = pool; + } - public void setFormat(PhysicalDiskFormat format) { - this.format = format; - } + public void setFormat(PhysicalDiskFormat format) { + this.format = format; + } - public PhysicalDiskFormat getFormat() { - return this.format; - } + public PhysicalDiskFormat getFormat() { + return this.format; + } - public void setSize(long size) { - this.size = size; - } + public void setSize(long size) { + this.size = size; + } - public long getSize() { - return this.size; - } + public long getSize() { + return this.size; + } - public void setVirtualSize(long size) { - this.virtualSize = size; - } + public void setVirtualSize(long size) { + this.virtualSize = size; + } - public long getVirtualSize() { - return this.virtualSize; - } + public long getVirtualSize() { + return this.virtualSize; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getPath() { - return this.path; - } + public String getPath() { + return this.path; + } - public KVMStoragePool getPool() { - return this.pool; - } + public KVMStoragePool getPool() { + return this.pool; + } } diff --git a/agent/src/com/cloud/agent/storage/KVMStoragePool.java b/agent/src/com/cloud/agent/storage/KVMStoragePool.java index 22deb5090d1..9961088bc02 100644 --- a/agent/src/com/cloud/agent/storage/KVMStoragePool.java +++ b/agent/src/com/cloud/agent/storage/KVMStoragePool.java @@ -22,34 +22,34 @@ import com.cloud.agent.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; public interface KVMStoragePool { - public KVMPhysicalDisk createPhysicalDisk(String name, - PhysicalDiskFormat format, long size); + public KVMPhysicalDisk createPhysicalDisk(String name, + PhysicalDiskFormat format, long size); - public KVMPhysicalDisk createPhysicalDisk(String name, long size); + public KVMPhysicalDisk createPhysicalDisk(String name, long size); - public KVMPhysicalDisk getPhysicalDisk(String volumeUuid); + public KVMPhysicalDisk getPhysicalDisk(String volumeUuid); - public boolean deletePhysicalDisk(String uuid); + public boolean deletePhysicalDisk(String uuid); - public List listPhysicalDisks(); + public List listPhysicalDisks(); - public String getUuid(); + public String getUuid(); - public long getCapacity(); + public long getCapacity(); - public long getUsed(); + public long getUsed(); - public boolean refresh(); + public boolean refresh(); - public boolean isExternalSnapshot(); + public boolean isExternalSnapshot(); - public String getLocalPath(); + public String getLocalPath(); - public StoragePoolType getType(); + public StoragePoolType getType(); - public boolean delete(); + public boolean delete(); - PhysicalDiskFormat getDefaultFormat(); + PhysicalDiskFormat getDefaultFormat(); - public boolean createFolder(String path); + public boolean createFolder(String path); } diff --git a/agent/src/com/cloud/agent/storage/KVMStoragePoolManager.java b/agent/src/com/cloud/agent/storage/KVMStoragePoolManager.java index 21be5e9f48e..53373e50b45 100644 --- a/agent/src/com/cloud/agent/storage/KVMStoragePoolManager.java +++ b/agent/src/com/cloud/agent/storage/KVMStoragePoolManager.java @@ -27,78 +27,78 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; public class KVMStoragePoolManager { - private StorageAdaptor _storageAdaptor; - private KVMHAMonitor _haMonitor; - private final Map _storagePools = new ConcurrentHashMap(); + private StorageAdaptor _storageAdaptor; + private KVMHAMonitor _haMonitor; + private final Map _storagePools = new ConcurrentHashMap(); - private void addStoragePool(String uuid) { - synchronized (_storagePools) { - if (!_storagePools.containsKey(uuid)) { - _storagePools.put(uuid, new Object()); - } - } - } + private void addStoragePool(String uuid) { + synchronized (_storagePools) { + if (!_storagePools.containsKey(uuid)) { + _storagePools.put(uuid, new Object()); + } + } + } - public KVMStoragePoolManager(StorageLayer storagelayer, KVMHAMonitor monitor) { - this._storageAdaptor = new LibvirtStorageAdaptor(storagelayer); - this._haMonitor = monitor; - } + public KVMStoragePoolManager(StorageLayer storagelayer, KVMHAMonitor monitor) { + this._storageAdaptor = new LibvirtStorageAdaptor(storagelayer); + this._haMonitor = monitor; + } - public KVMStoragePool getStoragePool(String uuid) { - return this._storageAdaptor.getStoragePool(uuid); - } + public KVMStoragePool getStoragePool(String uuid) { + return this._storageAdaptor.getStoragePool(uuid); + } - public KVMStoragePool getStoragePoolByURI(String uri) { - return this._storageAdaptor.getStoragePoolByUri(uri); - } + public KVMStoragePool getStoragePoolByURI(String uri) { + return this._storageAdaptor.getStoragePoolByUri(uri); + } - public KVMStoragePool createStoragePool(String name, String host, - String path, StoragePoolType type) { - KVMStoragePool pool = this._storageAdaptor.createStoragePool(name, - host, path, type); - if (type == StoragePoolType.NetworkFilesystem) { - KVMHABase.NfsStoragePool nfspool = new KVMHABase.NfsStoragePool( - pool.getUuid(), host, path, pool.getLocalPath(), - PoolType.PrimaryStorage); - _haMonitor.addStoragePool(nfspool); - } - addStoragePool(pool.getUuid()); - return pool; - } + public KVMStoragePool createStoragePool(String name, String host, + String path, StoragePoolType type) { + KVMStoragePool pool = this._storageAdaptor.createStoragePool(name, + host, path, type); + if (type == StoragePoolType.NetworkFilesystem) { + KVMHABase.NfsStoragePool nfspool = new KVMHABase.NfsStoragePool( + pool.getUuid(), host, path, pool.getLocalPath(), + PoolType.PrimaryStorage); + _haMonitor.addStoragePool(nfspool); + } + addStoragePool(pool.getUuid()); + return pool; + } - public boolean deleteStoragePool(String uuid) { - _haMonitor.removeStoragePool(uuid); - this._storageAdaptor.deleteStoragePool(uuid); - _storagePools.remove(uuid); - return true; - } + public boolean deleteStoragePool(String uuid) { + _haMonitor.removeStoragePool(uuid); + this._storageAdaptor.deleteStoragePool(uuid); + _storagePools.remove(uuid); + return true; + } - public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, - String name, KVMStoragePool destPool) { - return this._storageAdaptor.createDiskFromTemplate(template, name, - KVMPhysicalDisk.PhysicalDiskFormat.QCOW2, - template.getSize(), destPool); - } + public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, + String name, KVMStoragePool destPool) { + return this._storageAdaptor.createDiskFromTemplate(template, name, + KVMPhysicalDisk.PhysicalDiskFormat.QCOW2, + template.getSize(), destPool); + } - public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, - String name, PhysicalDiskFormat format, long size, - KVMStoragePool destPool) { - return this._storageAdaptor.createTemplateFromDisk(disk, name, format, - size, destPool); - } + public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, + String name, PhysicalDiskFormat format, long size, + KVMStoragePool destPool) { + return this._storageAdaptor.createTemplateFromDisk(disk, name, format, + size, destPool); + } - public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, - KVMStoragePool destPool) { - return this._storageAdaptor.copyPhysicalDisk(disk, name, destPool); - } + public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, + KVMStoragePool destPool) { + return this._storageAdaptor.copyPhysicalDisk(disk, name, destPool); + } - public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, - String snapshotName, String name, KVMStoragePool destPool) { - return this._storageAdaptor.createDiskFromSnapshot(snapshot, - snapshotName, name, destPool); - } + public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, + String snapshotName, String name, KVMStoragePool destPool) { + return this._storageAdaptor.createDiskFromSnapshot(snapshot, + snapshotName, name, destPool); + } - public KVMPhysicalDisk getPhysicalDiskFromUrl(String url) { - return this._storageAdaptor.getPhysicalDiskFromURI(url); - } + public KVMPhysicalDisk getPhysicalDiskFromUrl(String url) { + return this._storageAdaptor.getPhysicalDiskFromURI(url); + } } diff --git a/agent/src/com/cloud/agent/storage/LibvirtStorageAdaptor.java b/agent/src/com/cloud/agent/storage/LibvirtStorageAdaptor.java index 6ee69847d20..e1e050f75d5 100644 --- a/agent/src/com/cloud/agent/storage/LibvirtStorageAdaptor.java +++ b/agent/src/com/cloud/agent/storage/LibvirtStorageAdaptor.java @@ -47,657 +47,657 @@ import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; public class LibvirtStorageAdaptor implements StorageAdaptor { - private static final Logger s_logger = Logger - .getLogger(LibvirtStorageAdaptor.class); - private StorageLayer _storageLayer; - private String _mountPoint = "/mnt"; - private String _manageSnapshotPath; - - public LibvirtStorageAdaptor(StorageLayer storage) { - _storageLayer = storage; - _manageSnapshotPath = Script.findScript("scripts/storage/qcow2/", - "managesnapshot.sh"); - } - - @Override - public boolean createFolder(String uuid, String path) { - String mountPoint = _mountPoint + File.separator + uuid; - File f = new File(mountPoint + path); - if (!f.exists()) { - f.mkdirs(); - } - return true; - } - - public StorageVol getVolume(StoragePool pool, String volName) { - StorageVol vol = null; - - try { - vol = pool.storageVolLookupByName(volName); - } catch (LibvirtException e) { - - } - if (vol == null) { - storagePoolRefresh(pool); - try { - vol = pool.storageVolLookupByName(volName); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - return vol; - } - - public StorageVol createVolume(Connect conn, StoragePool pool, String uuid, - long size, volFormat format) throws LibvirtException { - LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(UUID - .randomUUID().toString(), size, format, null, null); - s_logger.debug(volDef.toString()); - return pool.storageVolCreateXML(volDef.toString(), 0); - } - - public StoragePool getStoragePoolbyURI(Connect conn, URI uri) - throws LibvirtException { - String sourcePath; - String uuid; - String sourceHost = ""; - String protocal; - if (uri.getScheme().equalsIgnoreCase("local")) { - sourcePath = _mountPoint + File.separator - + uri.toString().replace("local:///", ""); - sourcePath = sourcePath.replace("//", "/"); - uuid = UUID.nameUUIDFromBytes(new String(sourcePath).getBytes()) - .toString(); - protocal = "DIR"; - } else { - sourcePath = uri.getPath(); - sourcePath = sourcePath.replace("//", "/"); - sourceHost = uri.getHost(); - uuid = UUID.nameUUIDFromBytes( - new String(sourceHost + sourcePath).getBytes()).toString(); - protocal = "NFS"; - } - - String targetPath = _mountPoint + File.separator + uuid; - StoragePool sp = null; - try { - sp = conn.storagePoolLookupByUUIDString(uuid); - } catch (LibvirtException e) { - } - - if (sp == null) { - try { - LibvirtStoragePoolDef spd = null; - if (protocal.equalsIgnoreCase("NFS")) { - _storageLayer.mkdir(targetPath); - spd = new LibvirtStoragePoolDef(poolType.NETFS, uuid, uuid, - sourceHost, sourcePath, targetPath); - s_logger.debug(spd.toString()); - // addStoragePool(uuid); - - } else if (protocal.equalsIgnoreCase("DIR")) { - _storageLayer.mkdir(targetPath); - spd = new LibvirtStoragePoolDef(poolType.DIR, uuid, uuid, - null, null, sourcePath); - } - - synchronized (getStoragePool(uuid)) { - sp = conn.storagePoolDefineXML(spd.toString(), 0); - - if (sp == null) { - s_logger.debug("Failed to define storage pool"); - return null; - } - sp.create(0); - } - - return sp; - } catch (LibvirtException e) { - try { - if (sp != null) { - sp.undefine(); - sp.free(); - } - } catch (LibvirtException l) { - - } - throw e; - } - } else { - StoragePoolInfo spi = sp.getInfo(); - if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - sp.create(0); - } - return sp; - } - } - - public void storagePoolRefresh(StoragePool pool) { - try { - synchronized (getStoragePool(pool.getUUIDString())) { - pool.refresh(0); - } - } catch (LibvirtException e) { - - } - } - - private StoragePool createNfsStoragePool(Connect conn, String uuid, - String host, String path) { - String targetPath = _mountPoint + File.separator + uuid; - LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.NETFS, - uuid, uuid, host, path, targetPath); - _storageLayer.mkdir(targetPath); - StoragePool sp = null; - try { - s_logger.debug(spd.toString()); - sp = conn.storagePoolDefineXML(spd.toString(), 0); - sp.create(0); - return sp; - } catch (LibvirtException e) { - s_logger.debug(e.toString()); - if (sp != null) { - try { - sp.undefine(); - sp.free(); - } catch (LibvirtException l) { - s_logger.debug("Failed to define nfs storage pool with: " - + l.toString()); - } - } - return null; - } - } - - private StoragePool CreateSharedStoragePool(Connect conn, String uuid, - String host, String path) { - String mountPoint = path; - if (!_storageLayer.exists(mountPoint)) { - return null; - } - LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.DIR, - uuid, uuid, host, path, path); - StoragePool sp = null; - try { - s_logger.debug(spd.toString()); - sp = conn.storagePoolDefineXML(spd.toString(), 0); - sp.create(0); - - return sp; - } catch (LibvirtException e) { - s_logger.debug(e.toString()); - if (sp != null) { - try { - sp.undefine(); - sp.free(); - } catch (LibvirtException l) { - s_logger.debug("Failed to define shared mount point storage pool with: " - + l.toString()); - } - } - return null; - } - } - - private StoragePool createCLVMStoragePool(Connect conn, String uuid, - String host, String path) { - - String volgroupPath = "/dev/" + path; - String volgroupName = path; - volgroupName = volgroupName.replaceFirst("/", ""); - - LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.LOGICAL, - volgroupName, uuid, host, volgroupPath, volgroupPath); - StoragePool sp = null; - try { - s_logger.debug(spd.toString()); - sp = conn.storagePoolDefineXML(spd.toString(), 0); - sp.create(0); - return sp; - } catch (LibvirtException e) { - s_logger.debug(e.toString()); - if (sp != null) { - try { - sp.undefine(); - sp.free(); - } catch (LibvirtException l) { - s_logger.debug("Failed to define clvm storage pool with: " - + l.toString()); - } - } - return null; - } - - } - - public StorageVol copyVolume(StoragePool destPool, - LibvirtStorageVolumeDef destVol, StorageVol srcVol, int timeout) - throws LibvirtException { - StorageVol vol = destPool.storageVolCreateXML(destVol.toString(), 0); - String srcPath = srcVol.getKey(); - String destPath = vol.getKey(); - Script.runSimpleBashScript("cp " + srcPath + " " + destPath, timeout); - return vol; - } - - public boolean copyVolume(String srcPath, String destPath, - String volumeName, int timeout) throws InternalErrorException { - _storageLayer.mkdirs(destPath); - if (!_storageLayer.exists(srcPath)) { - throw new InternalErrorException("volume:" + srcPath - + " is not exits"); - } - String result = Script.runSimpleBashScript("cp " + srcPath + " " - + destPath + File.separator + volumeName, timeout); - if (result != null) { - return false; - } else { - return true; - } - } - - public LibvirtStoragePoolDef getStoragePoolDef(Connect conn, - StoragePool pool) throws LibvirtException { - String poolDefXML = pool.getXMLDesc(0); - LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); - return parser.parseStoragePoolXML(poolDefXML); - } - - public LibvirtStorageVolumeDef getStorageVolumeDef(Connect conn, - StorageVol vol) throws LibvirtException { - String volDefXML = vol.getXMLDesc(0); - LibvirtStorageVolumeXMLParser parser = new LibvirtStorageVolumeXMLParser(); - return parser.parseStorageVolumeXML(volDefXML); - } - - public StorageVol getVolumeFromURI(Connect conn, String volPath) - throws LibvirtException, URISyntaxException { - int index = volPath.lastIndexOf("/"); - URI volDir = null; - StoragePool sp = null; - StorageVol vol = null; - try { - volDir = new URI(volPath.substring(0, index)); - String volName = volPath.substring(index + 1); - sp = getStoragePoolbyURI(conn, volDir); - vol = sp.storageVolLookupByName(volName); - return vol; - } catch (LibvirtException e) { - s_logger.debug("Faild to get vol path: " + e.toString()); - throw e; - } finally { - try { - if (sp != null) { - sp.free(); - } - } catch (LibvirtException e) { - - } - } - } - - public StoragePool createFileBasedStoragePool(Connect conn, - String localStoragePath, String uuid) { - if (!(_storageLayer.exists(localStoragePath) && _storageLayer - .isDirectory(localStoragePath))) { - return null; - } - - File path = new File(localStoragePath); - if (!(path.canWrite() && path.canRead() && path.canExecute())) { - return null; - } - - StoragePool pool = null; - - try { - pool = conn.storagePoolLookupByUUIDString(uuid); - } catch (LibvirtException e) { - - } - - if (pool == null) { - LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.DIR, - uuid, uuid, null, null, localStoragePath); - try { - pool = conn.storagePoolDefineXML(spd.toString(), 0); - pool.create(0); - } catch (LibvirtException e) { - if (pool != null) { - try { - pool.destroy(); - pool.undefine(); - } catch (LibvirtException e1) { - } - pool = null; - } - throw new CloudRuntimeException(e.toString()); - } - } - - try { - StoragePoolInfo spi = pool.getInfo(); - if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - pool.create(0); - } - - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - - return pool; - } - - private void getStats(LibvirtStoragePool pool) { - Script statsScript = new Script("/bin/bash", s_logger); - statsScript.add("-c"); - statsScript.add("stats=$(df --total " + pool.getLocalPath() - + " |grep total|awk '{print $2,$3}');echo $stats"); - final OutputInterpreter.OneLineParser statsParser = new OutputInterpreter.OneLineParser(); - String result = statsScript.execute(statsParser); - if (result == null) { - String stats = statsParser.getLine(); - if (stats != null && !stats.isEmpty()) { - String sizes[] = stats.trim().split(" "); - if (sizes.length == 2) { - pool.setCapacity(Long.parseLong(sizes[0]) * 1024); - pool.setUsed(Long.parseLong(sizes[1]) * 1024); - } - } - } - } - - @Override - public KVMStoragePool getStoragePool(String uuid) { - StoragePool storage = null; - try { - Connect conn = LibvirtConnection.getConnection(); - storage = conn.storagePoolLookupByUUIDString(uuid); - - if (storage.getInfo().state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - storage.create(0); - } - LibvirtStoragePoolDef spd = getStoragePoolDef(conn, storage); - StoragePoolType type = null; - if (spd.getPoolType() == LibvirtStoragePoolDef.poolType.NETFS - || spd.getPoolType() == LibvirtStoragePoolDef.poolType.DIR) { - type = StoragePoolType.Filesystem; - } - LibvirtStoragePool pool = new LibvirtStoragePool(uuid, - storage.getName(), type, this, storage); - pool.setLocalPath(spd.getTargetPath()); - getStats(pool); - return pool; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - - @Override - public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, - KVMStoragePool pool) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - - try { - StorageVol vol = this.getVolume(libvirtPool.getPool(), volumeUuid); - KVMPhysicalDisk disk; - LibvirtStorageVolumeDef voldef = getStorageVolumeDef(libvirtPool - .getPool().getConnect(), vol); - disk = new KVMPhysicalDisk(vol.getPath(), vol.getName(), pool); - disk.setSize(vol.getInfo().allocation); - disk.setVirtualSize(vol.getInfo().capacity); - if (voldef.getFormat() == null) { - disk.setFormat(pool.getDefaultFormat()); - } else if (voldef.getFormat() == LibvirtStorageVolumeDef.volFormat.QCOW2) { - disk.setFormat(KVMPhysicalDisk.PhysicalDiskFormat.QCOW2); - } else if (voldef.getFormat() == LibvirtStorageVolumeDef.volFormat.RAW) { - disk.setFormat(KVMPhysicalDisk.PhysicalDiskFormat.RAW); - } - return disk; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - - } - - @Override - public KVMStoragePool createStoragePool(String name, String host, - String path, StoragePoolType type) { - StoragePool sp = null; - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - - try { - sp = conn.storagePoolLookupByUUIDString(name); - if (sp.getInfo().state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - sp.undefine(); - sp = null; - } - } catch (LibvirtException e) { - - } - - if (sp == null) { - if (type == StoragePoolType.NetworkFilesystem) { - sp = createNfsStoragePool(conn, name, host, path); - } else if (type == StoragePoolType.SharedMountPoint - || type == StoragePoolType.Filesystem) { - sp = CreateSharedStoragePool(conn, name, host, path); - } - } - - try { - StoragePoolInfo spi = sp.getInfo(); - if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { - sp.create(0); - } - - LibvirtStoragePoolDef spd = getStoragePoolDef(conn, sp); - LibvirtStoragePool pool = new LibvirtStoragePool(name, - sp.getName(), type, this, sp); - pool.setLocalPath(spd.getTargetPath()); - - getStats(pool); - - return pool; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - - } - - @Override - public boolean deleteStoragePool(String uuid) { - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - - StoragePool sp = null; - - try { - sp = conn.storagePoolLookupByUUIDString(uuid); - } catch (LibvirtException e) { - return true; - } - - try { - sp.destroy(); - sp.undefine(); - sp.free(); - return true; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - - @Override - public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, - PhysicalDiskFormat format, long size) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - StoragePool virtPool = libvirtPool.getPool(); - LibvirtStorageVolumeDef.volFormat libvirtformat = null; - if (format == PhysicalDiskFormat.QCOW2) { - libvirtformat = LibvirtStorageVolumeDef.volFormat.QCOW2; - } else if (format == PhysicalDiskFormat.RAW) { - libvirtformat = LibvirtStorageVolumeDef.volFormat.RAW; - } - - LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(name, - size, libvirtformat, null, null); - s_logger.debug(volDef.toString()); - try { - StorageVol vol = virtPool.storageVolCreateXML(volDef.toString(), 0); - KVMPhysicalDisk disk = new KVMPhysicalDisk(vol.getPath(), - vol.getName(), pool); - disk.setFormat(format); - disk.setSize(vol.getInfo().allocation); - disk.setVirtualSize(vol.getInfo().capacity); - return disk; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - - @Override - public boolean deletePhysicalDisk(String uuid, KVMStoragePool pool) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - try { - StorageVol vol = this.getVolume(libvirtPool.getPool(), uuid); - vol.delete(0); - vol.free(); - return true; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - - @Override - public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, - String name, PhysicalDiskFormat format, long size, - KVMStoragePool destPool) { - KVMPhysicalDisk disk = destPool.createPhysicalDisk(UUID.randomUUID() - .toString(), format, template.getVirtualSize()); - - if (format == PhysicalDiskFormat.QCOW2) { - Script.runSimpleBashScript("qemu-img create -f " - + template.getFormat() + " -b " + template.getPath() + " " - + disk.getPath()); - } else if (format == PhysicalDiskFormat.RAW) { - Script.runSimpleBashScript("qemu-img convert -f " - + template.getFormat() + " -O raw " + template.getPath() - + " " + disk.getPath()); - } - return disk; - } - - @Override - public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, - String name, PhysicalDiskFormat format, long size, - KVMStoragePool destPool) { - return null; - } - - @Override - public List listPhysicalDisks(String storagePoolUuid, - KVMStoragePool pool) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - StoragePool virtPool = libvirtPool.getPool(); - List disks = new ArrayList(); - try { - String[] vols = virtPool.listVolumes(); - for (String volName : vols) { - KVMPhysicalDisk disk = this.getPhysicalDisk(volName, pool); - disks.add(disk); - } - return disks; - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.toString()); - } - } - - @Override - public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, - KVMStoragePool destPool) { - KVMPhysicalDisk newDisk = destPool.createPhysicalDisk(name, - disk.getVirtualSize()); - String sourcePath = disk.getPath(); - String destPath = newDisk.getPath(); - - Script.runSimpleBashScript("qemu-img convert -f " + disk.getFormat() - + " -O " + newDisk.getFormat() + " " + sourcePath + " " - + destPath); - return newDisk; - } - - @Override - public KVMStoragePool getStoragePoolByUri(String uri) { - URI storageUri = null; - - try { - storageUri = new URI(uri); - } catch (URISyntaxException e) { - throw new CloudRuntimeException(e.toString()); - } - - String sourcePath = null; - String uuid = null; - String sourceHost = ""; - StoragePoolType protocal = null; - if (storageUri.getScheme().equalsIgnoreCase("nfs")) { - sourcePath = storageUri.getPath(); - sourcePath = sourcePath.replace("//", "/"); - sourceHost = storageUri.getHost(); - uuid = UUID.randomUUID().toString(); - protocal = StoragePoolType.NetworkFilesystem; - } - - return createStoragePool(uuid, sourceHost, sourcePath, protocal); - } - - @Override - public KVMPhysicalDisk getPhysicalDiskFromURI(String uri) { - // TODO Auto-generated method stub - return null; - } - - @Override - public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, - String snapshotName, String name, KVMStoragePool destPool) { - return null; - } - - @Override - public boolean refresh(KVMStoragePool pool) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - StoragePool virtPool = libvirtPool.getPool(); - try { - virtPool.refresh(0); - } catch (LibvirtException e) { - return false; - } - return true; - } - - @Override - public boolean deleteStoragePool(KVMStoragePool pool) { - LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; - StoragePool virtPool = libvirtPool.getPool(); - try { - virtPool.destroy(); - virtPool.undefine(); - virtPool.free(); - } catch (LibvirtException e) { - return false; - } - - return true; - } + private static final Logger s_logger = Logger + .getLogger(LibvirtStorageAdaptor.class); + private StorageLayer _storageLayer; + private String _mountPoint = "/mnt"; + private String _manageSnapshotPath; + + public LibvirtStorageAdaptor(StorageLayer storage) { + _storageLayer = storage; + _manageSnapshotPath = Script.findScript("scripts/storage/qcow2/", + "managesnapshot.sh"); + } + + @Override + public boolean createFolder(String uuid, String path) { + String mountPoint = _mountPoint + File.separator + uuid; + File f = new File(mountPoint + path); + if (!f.exists()) { + f.mkdirs(); + } + return true; + } + + public StorageVol getVolume(StoragePool pool, String volName) { + StorageVol vol = null; + + try { + vol = pool.storageVolLookupByName(volName); + } catch (LibvirtException e) { + + } + if (vol == null) { + storagePoolRefresh(pool); + try { + vol = pool.storageVolLookupByName(volName); + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + return vol; + } + + public StorageVol createVolume(Connect conn, StoragePool pool, String uuid, + long size, volFormat format) throws LibvirtException { + LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(UUID + .randomUUID().toString(), size, format, null, null); + s_logger.debug(volDef.toString()); + return pool.storageVolCreateXML(volDef.toString(), 0); + } + + public StoragePool getStoragePoolbyURI(Connect conn, URI uri) + throws LibvirtException { + String sourcePath; + String uuid; + String sourceHost = ""; + String protocal; + if (uri.getScheme().equalsIgnoreCase("local")) { + sourcePath = _mountPoint + File.separator + + uri.toString().replace("local:///", ""); + sourcePath = sourcePath.replace("//", "/"); + uuid = UUID.nameUUIDFromBytes(new String(sourcePath).getBytes()) + .toString(); + protocal = "DIR"; + } else { + sourcePath = uri.getPath(); + sourcePath = sourcePath.replace("//", "/"); + sourceHost = uri.getHost(); + uuid = UUID.nameUUIDFromBytes( + new String(sourceHost + sourcePath).getBytes()).toString(); + protocal = "NFS"; + } + + String targetPath = _mountPoint + File.separator + uuid; + StoragePool sp = null; + try { + sp = conn.storagePoolLookupByUUIDString(uuid); + } catch (LibvirtException e) { + } + + if (sp == null) { + try { + LibvirtStoragePoolDef spd = null; + if (protocal.equalsIgnoreCase("NFS")) { + _storageLayer.mkdir(targetPath); + spd = new LibvirtStoragePoolDef(poolType.NETFS, uuid, uuid, + sourceHost, sourcePath, targetPath); + s_logger.debug(spd.toString()); + // addStoragePool(uuid); + + } else if (protocal.equalsIgnoreCase("DIR")) { + _storageLayer.mkdir(targetPath); + spd = new LibvirtStoragePoolDef(poolType.DIR, uuid, uuid, + null, null, sourcePath); + } + + synchronized (getStoragePool(uuid)) { + sp = conn.storagePoolDefineXML(spd.toString(), 0); + + if (sp == null) { + s_logger.debug("Failed to define storage pool"); + return null; + } + sp.create(0); + } + + return sp; + } catch (LibvirtException e) { + try { + if (sp != null) { + sp.undefine(); + sp.free(); + } + } catch (LibvirtException l) { + + } + throw e; + } + } else { + StoragePoolInfo spi = sp.getInfo(); + if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + sp.create(0); + } + return sp; + } + } + + public void storagePoolRefresh(StoragePool pool) { + try { + synchronized (getStoragePool(pool.getUUIDString())) { + pool.refresh(0); + } + } catch (LibvirtException e) { + + } + } + + private StoragePool createNfsStoragePool(Connect conn, String uuid, + String host, String path) { + String targetPath = _mountPoint + File.separator + uuid; + LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.NETFS, + uuid, uuid, host, path, targetPath); + _storageLayer.mkdir(targetPath); + StoragePool sp = null; + try { + s_logger.debug(spd.toString()); + sp = conn.storagePoolDefineXML(spd.toString(), 0); + sp.create(0); + return sp; + } catch (LibvirtException e) { + s_logger.debug(e.toString()); + if (sp != null) { + try { + sp.undefine(); + sp.free(); + } catch (LibvirtException l) { + s_logger.debug("Failed to define nfs storage pool with: " + + l.toString()); + } + } + return null; + } + } + + private StoragePool CreateSharedStoragePool(Connect conn, String uuid, + String host, String path) { + String mountPoint = path; + if (!_storageLayer.exists(mountPoint)) { + return null; + } + LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.DIR, + uuid, uuid, host, path, path); + StoragePool sp = null; + try { + s_logger.debug(spd.toString()); + sp = conn.storagePoolDefineXML(spd.toString(), 0); + sp.create(0); + + return sp; + } catch (LibvirtException e) { + s_logger.debug(e.toString()); + if (sp != null) { + try { + sp.undefine(); + sp.free(); + } catch (LibvirtException l) { + s_logger.debug("Failed to define shared mount point storage pool with: " + + l.toString()); + } + } + return null; + } + } + + private StoragePool createCLVMStoragePool(Connect conn, String uuid, + String host, String path) { + + String volgroupPath = "/dev/" + path; + String volgroupName = path; + volgroupName = volgroupName.replaceFirst("/", ""); + + LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.LOGICAL, + volgroupName, uuid, host, volgroupPath, volgroupPath); + StoragePool sp = null; + try { + s_logger.debug(spd.toString()); + sp = conn.storagePoolDefineXML(spd.toString(), 0); + sp.create(0); + return sp; + } catch (LibvirtException e) { + s_logger.debug(e.toString()); + if (sp != null) { + try { + sp.undefine(); + sp.free(); + } catch (LibvirtException l) { + s_logger.debug("Failed to define clvm storage pool with: " + + l.toString()); + } + } + return null; + } + + } + + public StorageVol copyVolume(StoragePool destPool, + LibvirtStorageVolumeDef destVol, StorageVol srcVol, int timeout) + throws LibvirtException { + StorageVol vol = destPool.storageVolCreateXML(destVol.toString(), 0); + String srcPath = srcVol.getKey(); + String destPath = vol.getKey(); + Script.runSimpleBashScript("cp " + srcPath + " " + destPath, timeout); + return vol; + } + + public boolean copyVolume(String srcPath, String destPath, + String volumeName, int timeout) throws InternalErrorException { + _storageLayer.mkdirs(destPath); + if (!_storageLayer.exists(srcPath)) { + throw new InternalErrorException("volume:" + srcPath + + " is not exits"); + } + String result = Script.runSimpleBashScript("cp " + srcPath + " " + + destPath + File.separator + volumeName, timeout); + if (result != null) { + return false; + } else { + return true; + } + } + + public LibvirtStoragePoolDef getStoragePoolDef(Connect conn, + StoragePool pool) throws LibvirtException { + String poolDefXML = pool.getXMLDesc(0); + LibvirtStoragePoolXMLParser parser = new LibvirtStoragePoolXMLParser(); + return parser.parseStoragePoolXML(poolDefXML); + } + + public LibvirtStorageVolumeDef getStorageVolumeDef(Connect conn, + StorageVol vol) throws LibvirtException { + String volDefXML = vol.getXMLDesc(0); + LibvirtStorageVolumeXMLParser parser = new LibvirtStorageVolumeXMLParser(); + return parser.parseStorageVolumeXML(volDefXML); + } + + public StorageVol getVolumeFromURI(Connect conn, String volPath) + throws LibvirtException, URISyntaxException { + int index = volPath.lastIndexOf("/"); + URI volDir = null; + StoragePool sp = null; + StorageVol vol = null; + try { + volDir = new URI(volPath.substring(0, index)); + String volName = volPath.substring(index + 1); + sp = getStoragePoolbyURI(conn, volDir); + vol = sp.storageVolLookupByName(volName); + return vol; + } catch (LibvirtException e) { + s_logger.debug("Faild to get vol path: " + e.toString()); + throw e; + } finally { + try { + if (sp != null) { + sp.free(); + } + } catch (LibvirtException e) { + + } + } + } + + public StoragePool createFileBasedStoragePool(Connect conn, + String localStoragePath, String uuid) { + if (!(_storageLayer.exists(localStoragePath) && _storageLayer + .isDirectory(localStoragePath))) { + return null; + } + + File path = new File(localStoragePath); + if (!(path.canWrite() && path.canRead() && path.canExecute())) { + return null; + } + + StoragePool pool = null; + + try { + pool = conn.storagePoolLookupByUUIDString(uuid); + } catch (LibvirtException e) { + + } + + if (pool == null) { + LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.DIR, + uuid, uuid, null, null, localStoragePath); + try { + pool = conn.storagePoolDefineXML(spd.toString(), 0); + pool.create(0); + } catch (LibvirtException e) { + if (pool != null) { + try { + pool.destroy(); + pool.undefine(); + } catch (LibvirtException e1) { + } + pool = null; + } + throw new CloudRuntimeException(e.toString()); + } + } + + try { + StoragePoolInfo spi = pool.getInfo(); + if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + pool.create(0); + } + + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + + return pool; + } + + private void getStats(LibvirtStoragePool pool) { + Script statsScript = new Script("/bin/bash", s_logger); + statsScript.add("-c"); + statsScript.add("stats=$(df --total " + pool.getLocalPath() + + " |grep total|awk '{print $2,$3}');echo $stats"); + final OutputInterpreter.OneLineParser statsParser = new OutputInterpreter.OneLineParser(); + String result = statsScript.execute(statsParser); + if (result == null) { + String stats = statsParser.getLine(); + if (stats != null && !stats.isEmpty()) { + String sizes[] = stats.trim().split(" "); + if (sizes.length == 2) { + pool.setCapacity(Long.parseLong(sizes[0]) * 1024); + pool.setUsed(Long.parseLong(sizes[1]) * 1024); + } + } + } + } + + @Override + public KVMStoragePool getStoragePool(String uuid) { + StoragePool storage = null; + try { + Connect conn = LibvirtConnection.getConnection(); + storage = conn.storagePoolLookupByUUIDString(uuid); + + if (storage.getInfo().state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + storage.create(0); + } + LibvirtStoragePoolDef spd = getStoragePoolDef(conn, storage); + StoragePoolType type = null; + if (spd.getPoolType() == LibvirtStoragePoolDef.poolType.NETFS + || spd.getPoolType() == LibvirtStoragePoolDef.poolType.DIR) { + type = StoragePoolType.Filesystem; + } + LibvirtStoragePool pool = new LibvirtStoragePool(uuid, + storage.getName(), type, this, storage); + pool.setLocalPath(spd.getTargetPath()); + getStats(pool); + return pool; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + + @Override + public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, + KVMStoragePool pool) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + + try { + StorageVol vol = this.getVolume(libvirtPool.getPool(), volumeUuid); + KVMPhysicalDisk disk; + LibvirtStorageVolumeDef voldef = getStorageVolumeDef(libvirtPool + .getPool().getConnect(), vol); + disk = new KVMPhysicalDisk(vol.getPath(), vol.getName(), pool); + disk.setSize(vol.getInfo().allocation); + disk.setVirtualSize(vol.getInfo().capacity); + if (voldef.getFormat() == null) { + disk.setFormat(pool.getDefaultFormat()); + } else if (voldef.getFormat() == LibvirtStorageVolumeDef.volFormat.QCOW2) { + disk.setFormat(KVMPhysicalDisk.PhysicalDiskFormat.QCOW2); + } else if (voldef.getFormat() == LibvirtStorageVolumeDef.volFormat.RAW) { + disk.setFormat(KVMPhysicalDisk.PhysicalDiskFormat.RAW); + } + return disk; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + + } + + @Override + public KVMStoragePool createStoragePool(String name, String host, + String path, StoragePoolType type) { + StoragePool sp = null; + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + + try { + sp = conn.storagePoolLookupByUUIDString(name); + if (sp.getInfo().state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + sp.undefine(); + sp = null; + } + } catch (LibvirtException e) { + + } + + if (sp == null) { + if (type == StoragePoolType.NetworkFilesystem) { + sp = createNfsStoragePool(conn, name, host, path); + } else if (type == StoragePoolType.SharedMountPoint + || type == StoragePoolType.Filesystem) { + sp = CreateSharedStoragePool(conn, name, host, path); + } + } + + try { + StoragePoolInfo spi = sp.getInfo(); + if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) { + sp.create(0); + } + + LibvirtStoragePoolDef spd = getStoragePoolDef(conn, sp); + LibvirtStoragePool pool = new LibvirtStoragePool(name, + sp.getName(), type, this, sp); + pool.setLocalPath(spd.getTargetPath()); + + getStats(pool); + + return pool; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + + } + + @Override + public boolean deleteStoragePool(String uuid) { + Connect conn = null; + try { + conn = LibvirtConnection.getConnection(); + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + + StoragePool sp = null; + + try { + sp = conn.storagePoolLookupByUUIDString(uuid); + } catch (LibvirtException e) { + return true; + } + + try { + sp.destroy(); + sp.undefine(); + sp.free(); + return true; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + + @Override + public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, + PhysicalDiskFormat format, long size) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + StoragePool virtPool = libvirtPool.getPool(); + LibvirtStorageVolumeDef.volFormat libvirtformat = null; + if (format == PhysicalDiskFormat.QCOW2) { + libvirtformat = LibvirtStorageVolumeDef.volFormat.QCOW2; + } else if (format == PhysicalDiskFormat.RAW) { + libvirtformat = LibvirtStorageVolumeDef.volFormat.RAW; + } + + LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(name, + size, libvirtformat, null, null); + s_logger.debug(volDef.toString()); + try { + StorageVol vol = virtPool.storageVolCreateXML(volDef.toString(), 0); + KVMPhysicalDisk disk = new KVMPhysicalDisk(vol.getPath(), + vol.getName(), pool); + disk.setFormat(format); + disk.setSize(vol.getInfo().allocation); + disk.setVirtualSize(vol.getInfo().capacity); + return disk; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + + @Override + public boolean deletePhysicalDisk(String uuid, KVMStoragePool pool) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + try { + StorageVol vol = this.getVolume(libvirtPool.getPool(), uuid); + vol.delete(0); + vol.free(); + return true; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + + @Override + public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, + String name, PhysicalDiskFormat format, long size, + KVMStoragePool destPool) { + KVMPhysicalDisk disk = destPool.createPhysicalDisk(UUID.randomUUID() + .toString(), format, template.getVirtualSize()); + + if (format == PhysicalDiskFormat.QCOW2) { + Script.runSimpleBashScript("qemu-img create -f " + + template.getFormat() + " -b " + template.getPath() + " " + + disk.getPath()); + } else if (format == PhysicalDiskFormat.RAW) { + Script.runSimpleBashScript("qemu-img convert -f " + + template.getFormat() + " -O raw " + template.getPath() + + " " + disk.getPath()); + } + return disk; + } + + @Override + public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, + String name, PhysicalDiskFormat format, long size, + KVMStoragePool destPool) { + return null; + } + + @Override + public List listPhysicalDisks(String storagePoolUuid, + KVMStoragePool pool) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + StoragePool virtPool = libvirtPool.getPool(); + List disks = new ArrayList(); + try { + String[] vols = virtPool.listVolumes(); + for (String volName : vols) { + KVMPhysicalDisk disk = this.getPhysicalDisk(volName, pool); + disks.add(disk); + } + return disks; + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.toString()); + } + } + + @Override + public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, + KVMStoragePool destPool) { + KVMPhysicalDisk newDisk = destPool.createPhysicalDisk(name, + disk.getVirtualSize()); + String sourcePath = disk.getPath(); + String destPath = newDisk.getPath(); + + Script.runSimpleBashScript("qemu-img convert -f " + disk.getFormat() + + " -O " + newDisk.getFormat() + " " + sourcePath + " " + + destPath); + return newDisk; + } + + @Override + public KVMStoragePool getStoragePoolByUri(String uri) { + URI storageUri = null; + + try { + storageUri = new URI(uri); + } catch (URISyntaxException e) { + throw new CloudRuntimeException(e.toString()); + } + + String sourcePath = null; + String uuid = null; + String sourceHost = ""; + StoragePoolType protocal = null; + if (storageUri.getScheme().equalsIgnoreCase("nfs")) { + sourcePath = storageUri.getPath(); + sourcePath = sourcePath.replace("//", "/"); + sourceHost = storageUri.getHost(); + uuid = UUID.randomUUID().toString(); + protocal = StoragePoolType.NetworkFilesystem; + } + + return createStoragePool(uuid, sourceHost, sourcePath, protocal); + } + + @Override + public KVMPhysicalDisk getPhysicalDiskFromURI(String uri) { + // TODO Auto-generated method stub + return null; + } + + @Override + public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, + String snapshotName, String name, KVMStoragePool destPool) { + return null; + } + + @Override + public boolean refresh(KVMStoragePool pool) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + StoragePool virtPool = libvirtPool.getPool(); + try { + virtPool.refresh(0); + } catch (LibvirtException e) { + return false; + } + return true; + } + + @Override + public boolean deleteStoragePool(KVMStoragePool pool) { + LibvirtStoragePool libvirtPool = (LibvirtStoragePool) pool; + StoragePool virtPool = libvirtPool.getPool(); + try { + virtPool.destroy(); + virtPool.undefine(); + virtPool.free(); + } catch (LibvirtException e) { + return false; + } + + return true; + } } diff --git a/agent/src/com/cloud/agent/storage/LibvirtStoragePool.java b/agent/src/com/cloud/agent/storage/LibvirtStoragePool.java index de3e0be69d8..d638bb99c59 100644 --- a/agent/src/com/cloud/agent/storage/LibvirtStoragePool.java +++ b/agent/src/com/cloud/agent/storage/LibvirtStoragePool.java @@ -24,135 +24,135 @@ import com.cloud.agent.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; public class LibvirtStoragePool implements KVMStoragePool { - protected String uuid; - protected String uri; - protected long capacity; - protected long used; - protected String name; - protected String localPath; - protected PhysicalDiskFormat defaultFormat; - protected StoragePoolType type; - protected StorageAdaptor _storageAdaptor; - protected StoragePool _pool; + protected String uuid; + protected String uri; + protected long capacity; + protected long used; + protected String name; + protected String localPath; + protected PhysicalDiskFormat defaultFormat; + protected StoragePoolType type; + protected StorageAdaptor _storageAdaptor; + protected StoragePool _pool; - public LibvirtStoragePool(String uuid, String name, StoragePoolType type, - StorageAdaptor adaptor, StoragePool pool) { - this.uuid = uuid; - this.name = name; - this.type = type; - this._storageAdaptor = adaptor; - this.capacity = 0; - this.used = 0; - this._pool = pool; + public LibvirtStoragePool(String uuid, String name, StoragePoolType type, + StorageAdaptor adaptor, StoragePool pool) { + this.uuid = uuid; + this.name = name; + this.type = type; + this._storageAdaptor = adaptor; + this.capacity = 0; + this.used = 0; + this._pool = pool; - } + } - public void setCapacity(long capacity) { - this.capacity = capacity; - } + public void setCapacity(long capacity) { + this.capacity = capacity; + } - @Override - public long getCapacity() { - return this.capacity; - } + @Override + public long getCapacity() { + return this.capacity; + } - public void setUsed(long used) { - this.used = used; - } + public void setUsed(long used) { + this.used = used; + } - @Override - public long getUsed() { - return this.used; - } + @Override + public long getUsed() { + return this.used; + } - public StoragePoolType getStoragePoolType() { - return this.type; - } + public StoragePoolType getStoragePoolType() { + return this.type; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getUuid() { - return this.uuid; - } + public String getUuid() { + return this.uuid; + } - public String uri() { - return this.uri; - } + public String uri() { + return this.uri; + } - @Override - public PhysicalDiskFormat getDefaultFormat() { - return PhysicalDiskFormat.QCOW2; - } + @Override + public PhysicalDiskFormat getDefaultFormat() { + return PhysicalDiskFormat.QCOW2; + } - @Override - public KVMPhysicalDisk createPhysicalDisk(String name, - PhysicalDiskFormat format, long size) { - return this._storageAdaptor - .createPhysicalDisk(name, this, format, size); - } + @Override + public KVMPhysicalDisk createPhysicalDisk(String name, + PhysicalDiskFormat format, long size) { + return this._storageAdaptor + .createPhysicalDisk(name, this, format, size); + } - @Override - public KVMPhysicalDisk createPhysicalDisk(String name, long size) { - return this._storageAdaptor.createPhysicalDisk(name, this, - this.getDefaultFormat(), size); - } + @Override + public KVMPhysicalDisk createPhysicalDisk(String name, long size) { + return this._storageAdaptor.createPhysicalDisk(name, this, + this.getDefaultFormat(), size); + } - @Override - public KVMPhysicalDisk getPhysicalDisk(String volumeUuid) { - return this._storageAdaptor.getPhysicalDisk(volumeUuid, this); - } + @Override + public KVMPhysicalDisk getPhysicalDisk(String volumeUuid) { + return this._storageAdaptor.getPhysicalDisk(volumeUuid, this); + } - @Override - public boolean deletePhysicalDisk(String uuid) { - return this._storageAdaptor.deletePhysicalDisk(uuid, this); - } + @Override + public boolean deletePhysicalDisk(String uuid) { + return this._storageAdaptor.deletePhysicalDisk(uuid, this); + } - @Override - public List listPhysicalDisks() { - return this._storageAdaptor.listPhysicalDisks(this.uuid, this); - } + @Override + public List listPhysicalDisks() { + return this._storageAdaptor.listPhysicalDisks(this.uuid, this); + } - @Override - public boolean refresh() { - return this._storageAdaptor.refresh(this); - } + @Override + public boolean refresh() { + return this._storageAdaptor.refresh(this); + } - @Override - public boolean isExternalSnapshot() { - if (this.type == StoragePoolType.Filesystem) { - return false; - } + @Override + public boolean isExternalSnapshot() { + if (this.type == StoragePoolType.Filesystem) { + return false; + } - return true; - } + return true; + } - @Override - public String getLocalPath() { - return this.localPath; - } + @Override + public String getLocalPath() { + return this.localPath; + } - public void setLocalPath(String localPath) { - this.localPath = localPath; - } + public void setLocalPath(String localPath) { + this.localPath = localPath; + } - @Override - public StoragePoolType getType() { - return this.type; - } + @Override + public StoragePoolType getType() { + return this.type; + } - public StoragePool getPool() { - return this._pool; - } + public StoragePool getPool() { + return this._pool; + } - @Override - public boolean delete() { - return this._storageAdaptor.deleteStoragePool(this); - } + @Override + public boolean delete() { + return this._storageAdaptor.deleteStoragePool(this); + } - @Override - public boolean createFolder(String path) { - return this._storageAdaptor.createFolder(this.uuid, path); - } + @Override + public boolean createFolder(String path) { + return this._storageAdaptor.createFolder(this.uuid, path); + } } diff --git a/agent/src/com/cloud/agent/storage/StorageAdaptor.java b/agent/src/com/cloud/agent/storage/StorageAdaptor.java index b4dde69bd23..9cc5d14d875 100644 --- a/agent/src/com/cloud/agent/storage/StorageAdaptor.java +++ b/agent/src/com/cloud/agent/storage/StorageAdaptor.java @@ -25,46 +25,46 @@ import com.cloud.storage.Storage.StoragePoolType; public interface StorageAdaptor { - public KVMStoragePool getStoragePool(String uuid); + public KVMStoragePool getStoragePool(String uuid); - public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, - KVMStoragePool pool); + public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, + KVMStoragePool pool); - public KVMStoragePool createStoragePool(String name, String host, - String path, StoragePoolType type); + public KVMStoragePool createStoragePool(String name, String host, + String path, StoragePoolType type); - public boolean deleteStoragePool(String uuid); + public boolean deleteStoragePool(String uuid); - public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, - PhysicalDiskFormat format, long size); + public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, + PhysicalDiskFormat format, long size); - public boolean deletePhysicalDisk(String uuid, KVMStoragePool pool); + public boolean deletePhysicalDisk(String uuid, KVMStoragePool pool); - public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, - String name, PhysicalDiskFormat format, long size, - KVMStoragePool destPool); + public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, + String name, PhysicalDiskFormat format, long size, + KVMStoragePool destPool); - public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, - String name, PhysicalDiskFormat format, long size, - KVMStoragePool destPool); + public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, + String name, PhysicalDiskFormat format, long size, + KVMStoragePool destPool); - public List listPhysicalDisks(String storagePoolUuid, - KVMStoragePool pool); + public List listPhysicalDisks(String storagePoolUuid, + KVMStoragePool pool); - public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, - KVMStoragePool destPools); + public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, + KVMStoragePool destPools); - public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, - String snapshotName, String name, KVMStoragePool destPool); + public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, + String snapshotName, String name, KVMStoragePool destPool); - public KVMStoragePool getStoragePoolByUri(String uri); + public KVMStoragePool getStoragePoolByUri(String uri); - public KVMPhysicalDisk getPhysicalDiskFromURI(String uri); + public KVMPhysicalDisk getPhysicalDiskFromURI(String uri); - public boolean refresh(KVMStoragePool pool); + public boolean refresh(KVMStoragePool pool); - public boolean deleteStoragePool(KVMStoragePool pool); + public boolean deleteStoragePool(KVMStoragePool pool); - public boolean createFolder(String uuid, String path); + public boolean createFolder(String uuid, String path); } diff --git a/agent/src/com/cloud/agent/vmdata/JettyVmDataServer.java b/agent/src/com/cloud/agent/vmdata/JettyVmDataServer.java index 55034cd2bdf..6882b3ea8a0 100644 --- a/agent/src/com/cloud/agent/vmdata/JettyVmDataServer.java +++ b/agent/src/com/cloud/agent/vmdata/JettyVmDataServer.java @@ -66,305 +66,305 @@ import com.cloud.utils.script.Script; */ @Local(value = { VmDataServer.class }) public class JettyVmDataServer implements VmDataServer { - private static final Logger s_logger = Logger - .getLogger(JettyVmDataServer.class); + private static final Logger s_logger = Logger + .getLogger(JettyVmDataServer.class); - public static final String USER_DATA = "user-data"; - public static final String META_DATA = "meta-data"; - protected String _vmDataDir; - protected Server _jetty; - protected String _hostIp; - protected Map _ipVmMap = new HashMap(); - protected StorageLayer _fs = new JavaStorageLayer(); + public static final String USER_DATA = "user-data"; + public static final String META_DATA = "meta-data"; + protected String _vmDataDir; + protected Server _jetty; + protected String _hostIp; + protected Map _ipVmMap = new HashMap(); + protected StorageLayer _fs = new JavaStorageLayer(); - public class VmDataServlet extends HttpServlet { + public class VmDataServlet extends HttpServlet { - private static final long serialVersionUID = -1640031398971742349L; + private static final long serialVersionUID = -1640031398971742349L; - JettyVmDataServer _vmDataServer; - String _dataType; // userdata or meta-data + JettyVmDataServer _vmDataServer; + String _dataType; // userdata or meta-data - public VmDataServlet(JettyVmDataServer dataServer, String dataType) { - this._vmDataServer = dataServer; - this._dataType = dataType; - } + public VmDataServlet(JettyVmDataServer dataServer, String dataType) { + this._vmDataServer = dataServer; + this._dataType = dataType; + } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - int port = req.getServerPort(); - if (port != 80 && port != 8000) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND, - "Request not understood"); - return; - } - if (_dataType.equalsIgnoreCase(USER_DATA)) { - handleUserData(req, resp); - } else if (_dataType.equalsIgnoreCase(META_DATA)) { - handleMetaData(req, resp); - } - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + int port = req.getServerPort(); + if (port != 80 && port != 8000) { + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Request not understood"); + return; + } + if (_dataType.equalsIgnoreCase(USER_DATA)) { + handleUserData(req, resp); + } else if (_dataType.equalsIgnoreCase(META_DATA)) { + handleMetaData(req, resp); + } + } - protected void handleUserData(HttpServletRequest req, - HttpServletResponse resp) throws ServletException, IOException { - String metadataItem = req.getPathInfo(); - String requester = req.getRemoteAddr(); - resp.setContentType("text/html"); - resp.setStatus(HttpServletResponse.SC_OK); - String data = null; - if (metadataItem != null) { - String[] path = metadataItem.split("/"); - if (path.length > 1) { - metadataItem = path[1]; - } - } + protected void handleUserData(HttpServletRequest req, + HttpServletResponse resp) throws ServletException, IOException { + String metadataItem = req.getPathInfo(); + String requester = req.getRemoteAddr(); + resp.setContentType("text/html"); + resp.setStatus(HttpServletResponse.SC_OK); + String data = null; + if (metadataItem != null) { + String[] path = metadataItem.split("/"); + if (path.length > 1) { + metadataItem = path[1]; + } + } - if (metadataItem != null) - data = _vmDataServer.getVmDataItem(requester, metadataItem); + if (metadataItem != null) + data = _vmDataServer.getVmDataItem(requester, metadataItem); - if (data != null) { - resp.getWriter().print(data); - } else { - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - resp.sendError(HttpServletResponse.SC_NOT_FOUND, - "Request not found"); - } + if (data != null) { + resp.getWriter().print(data); + } else { + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Request not found"); + } - } + } - protected void handleMetaData(HttpServletRequest req, - HttpServletResponse resp) throws ServletException, IOException { - String metadataItem = req.getPathInfo(); - String requester = req.getRemoteAddr(); - resp.setContentType("text/html"); - resp.setStatus(HttpServletResponse.SC_OK); - String metaData = _vmDataServer.getVmDataItem(requester, - metadataItem); - if (metaData != null) { - resp.getWriter().print( - _vmDataServer.getVmDataItem(requester, metadataItem)); - } else { - resp.sendError(HttpServletResponse.SC_NOT_FOUND, - "Request not found"); - } - } + protected void handleMetaData(HttpServletRequest req, + HttpServletResponse resp) throws ServletException, IOException { + String metadataItem = req.getPathInfo(); + String requester = req.getRemoteAddr(); + resp.setContentType("text/html"); + resp.setStatus(HttpServletResponse.SC_OK); + String metaData = _vmDataServer.getVmDataItem(requester, + metadataItem); + if (metaData != null) { + resp.getWriter().print( + _vmDataServer.getVmDataItem(requester, metadataItem)); + } else { + resp.sendError(HttpServletResponse.SC_NOT_FOUND, + "Request not found"); + } + } - } + } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - boolean success = true; - try { - int vmDataPort = 80; - int fileservingPort = 8000; - _vmDataDir = (String) params.get("vm.data.dir"); - String port = (String) params.get("vm.data.port"); - if (port != null) { - vmDataPort = Integer.parseInt(port); - } - port = (String) params.get("file.server.port"); - if (port != null) { - fileservingPort = Integer.parseInt(port); - } - _hostIp = (String) params.get("host.ip"); + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + boolean success = true; + try { + int vmDataPort = 80; + int fileservingPort = 8000; + _vmDataDir = (String) params.get("vm.data.dir"); + String port = (String) params.get("vm.data.port"); + if (port != null) { + vmDataPort = Integer.parseInt(port); + } + port = (String) params.get("file.server.port"); + if (port != null) { + fileservingPort = Integer.parseInt(port); + } + _hostIp = (String) params.get("host.ip"); - if (_vmDataDir == null) { - _vmDataDir = "/var/www/html"; - } - success = _fs.mkdirs(_vmDataDir); - success = success && buildIpVmMap(); - if (success) { - setupJetty(vmDataPort, fileservingPort); - } - } catch (Exception e) { - s_logger.warn("Failed to configure jetty", e); - throw new ConfigurationException("Failed to configure jetty!!"); - } - return success; - } + if (_vmDataDir == null) { + _vmDataDir = "/var/www/html"; + } + success = _fs.mkdirs(_vmDataDir); + success = success && buildIpVmMap(); + if (success) { + setupJetty(vmDataPort, fileservingPort); + } + } catch (Exception e) { + s_logger.warn("Failed to configure jetty", e); + throw new ConfigurationException("Failed to configure jetty!!"); + } + return success; + } - protected boolean buildIpVmMap() { - String[] dirs = _fs.listFiles(_vmDataDir); - for (String dir : dirs) { - String[] path = dir.split("/"); - String vm = path[path.length - 1]; - if (vm.startsWith("i-")) { - String[] dataFiles = _fs.listFiles(dir); - for (String dfile : dataFiles) { - String path2[] = dfile.split("/"); - String ipv4file = path2[path2.length - 1]; - if (ipv4file.equalsIgnoreCase("local-ipv4")) { - try { - BufferedReader input = new BufferedReader( - new FileReader(dfile)); - String line = null; - while ((line = input.readLine()) != null) { - if (NetUtils.isValidIp(line)) { - _ipVmMap.put(line, vm); - s_logger.info("Found ip " + line - + " for vm " + vm); - } else { - s_logger.info("Invalid ip " + line - + " for vm " + vm); - } - } - } catch (FileNotFoundException e) { - s_logger.warn("Failed to find file " + dfile); - } catch (IOException e) { - s_logger.warn("Failed to get ip address of " + vm); - } + protected boolean buildIpVmMap() { + String[] dirs = _fs.listFiles(_vmDataDir); + for (String dir : dirs) { + String[] path = dir.split("/"); + String vm = path[path.length - 1]; + if (vm.startsWith("i-")) { + String[] dataFiles = _fs.listFiles(dir); + for (String dfile : dataFiles) { + String path2[] = dfile.split("/"); + String ipv4file = path2[path2.length - 1]; + if (ipv4file.equalsIgnoreCase("local-ipv4")) { + try { + BufferedReader input = new BufferedReader( + new FileReader(dfile)); + String line = null; + while ((line = input.readLine()) != null) { + if (NetUtils.isValidIp(line)) { + _ipVmMap.put(line, vm); + s_logger.info("Found ip " + line + + " for vm " + vm); + } else { + s_logger.info("Invalid ip " + line + + " for vm " + vm); + } + } + } catch (FileNotFoundException e) { + s_logger.warn("Failed to find file " + dfile); + } catch (IOException e) { + s_logger.warn("Failed to get ip address of " + vm); + } - } - } - } - } - return true; - } + } + } + } + } + return true; + } - public String getVmDataItem(String requester, String dataItem) { - String vmName = _ipVmMap.get(requester); - if (vmName == null) { - return null; - } - String vmDataFile = _vmDataDir + File.separator + vmName - + File.separator + dataItem; - try { - BufferedReader input = new BufferedReader( - new FileReader(vmDataFile)); - StringBuilder result = new StringBuilder(); - String line = null; - while ((line = input.readLine()) != null) { - result.append(line); - } - input.close(); - return result.toString(); - } catch (FileNotFoundException e) { - s_logger.warn("Failed to find requested file " + vmDataFile); - return null; - } catch (IOException e) { - s_logger.warn("Failed to read requested file " + vmDataFile); - return null; - } - } + public String getVmDataItem(String requester, String dataItem) { + String vmName = _ipVmMap.get(requester); + if (vmName == null) { + return null; + } + String vmDataFile = _vmDataDir + File.separator + vmName + + File.separator + dataItem; + try { + BufferedReader input = new BufferedReader( + new FileReader(vmDataFile)); + StringBuilder result = new StringBuilder(); + String line = null; + while ((line = input.readLine()) != null) { + result.append(line); + } + input.close(); + return result.toString(); + } catch (FileNotFoundException e) { + s_logger.warn("Failed to find requested file " + vmDataFile); + return null; + } catch (IOException e) { + s_logger.warn("Failed to read requested file " + vmDataFile); + return null; + } + } - private void setupJetty(int vmDataPort, int fileservingPort) - throws Exception { - _jetty = new Server(); + private void setupJetty(int vmDataPort, int fileservingPort) + throws Exception { + _jetty = new Server(); - SelectChannelConnector connector0 = new SelectChannelConnector(); - connector0.setHost(_hostIp); - connector0.setPort(fileservingPort); - connector0.setMaxIdleTime(30000); - connector0.setRequestBufferSize(8192); + SelectChannelConnector connector0 = new SelectChannelConnector(); + connector0.setHost(_hostIp); + connector0.setPort(fileservingPort); + connector0.setMaxIdleTime(30000); + connector0.setRequestBufferSize(8192); - SelectChannelConnector connector1 = new SelectChannelConnector(); - connector1.setHost(_hostIp); - connector1.setPort(vmDataPort); - connector1.setThreadPool(new QueuedThreadPool(5)); - connector1.setMaxIdleTime(30000); - connector1.setRequestBufferSize(8192); + SelectChannelConnector connector1 = new SelectChannelConnector(); + connector1.setHost(_hostIp); + connector1.setPort(vmDataPort); + connector1.setThreadPool(new QueuedThreadPool(5)); + connector1.setMaxIdleTime(30000); + connector1.setRequestBufferSize(8192); - _jetty.setConnectors(new Connector[] { connector0, connector1 }); + _jetty.setConnectors(new Connector[] { connector0, connector1 }); - Context root = new Context(_jetty, "/latest", Context.SESSIONS); - root.setResourceBase(_vmDataDir); - root.addServlet(new ServletHolder(new VmDataServlet(this, USER_DATA)), - "/*"); + Context root = new Context(_jetty, "/latest", Context.SESSIONS); + root.setResourceBase(_vmDataDir); + root.addServlet(new ServletHolder(new VmDataServlet(this, USER_DATA)), + "/*"); - ResourceHandler resource_handler = new ResourceHandler(); - resource_handler.setResourceBase("/var/lib/images/"); + ResourceHandler resource_handler = new ResourceHandler(); + resource_handler.setResourceBase("/var/lib/images/"); - HandlerList handlers = new HandlerList(); - handlers.setHandlers(new Handler[] { root, resource_handler, - new DefaultHandler() }); - _jetty.setHandler(handlers); + HandlerList handlers = new HandlerList(); + handlers.setHandlers(new Handler[] { root, resource_handler, + new DefaultHandler() }); + _jetty.setHandler(handlers); - _jetty.start(); - // _jetty.join(); - } + _jetty.start(); + // _jetty.join(); + } - @Override - public boolean start() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean start() { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean stop() { - return true; - } + @Override + public boolean stop() { + return true; + } - @Override - public String getName() { - return "JettyVmDataServer"; - } + @Override + public String getName() { + return "JettyVmDataServer"; + } - @Override - public Answer handleVmDataCommand(VmDataCommand cmd) { - String vmDataDir = _vmDataDir + File.separator + cmd.getVmName(); + @Override + public Answer handleVmDataCommand(VmDataCommand cmd) { + String vmDataDir = _vmDataDir + File.separator + cmd.getVmName(); - Script.runSimpleBashScript("rm -rf " + vmDataDir); - _fs.mkdirs(vmDataDir); + Script.runSimpleBashScript("rm -rf " + vmDataDir); + _fs.mkdirs(vmDataDir); - for (String[] item : cmd.getVmData()) { - try { - _fs.create(vmDataDir, item[1]); - String vmDataFile = vmDataDir + File.separator + item[1]; - byte[] data; - if (item[2] != null) { - if (item[1].equals("user-data")) { - data = Base64.decodeBase64(item[2]); - } else { - data = item[2].getBytes(); - } - if (data != null && data.length > 0) { - FileOutputStream writer = new FileOutputStream( - vmDataFile); - writer.write(data); - writer.close(); - } - } - } catch (IOException e) { - s_logger.warn("Failed to write vm data item " + item[1], e); - return new Answer(cmd, false, "Failed to write vm data item " - + item[1]); - } - } - return new Answer(cmd); + for (String[] item : cmd.getVmData()) { + try { + _fs.create(vmDataDir, item[1]); + String vmDataFile = vmDataDir + File.separator + item[1]; + byte[] data; + if (item[2] != null) { + if (item[1].equals("user-data")) { + data = Base64.decodeBase64(item[2]); + } else { + data = item[2].getBytes(); + } + if (data != null && data.length > 0) { + FileOutputStream writer = new FileOutputStream( + vmDataFile); + writer.write(data); + writer.close(); + } + } + } catch (IOException e) { + s_logger.warn("Failed to write vm data item " + item[1], e); + return new Answer(cmd, false, "Failed to write vm data item " + + item[1]); + } + } + return new Answer(cmd); - } + } - @Override - public void handleVmStarted(VirtualMachineTO vm) { - for (NicTO nic : vm.getNics()) { - if (nic.getType() == TrafficType.Guest) { - if (nic.getIp() != null) { - String ipv4File = _vmDataDir + File.separator - + vm.getName() + File.separator + "local-ipv4"; - try { - _fs.create(_vmDataDir + File.separator + vm.getName(), - "local-ipv4"); - BufferedWriter writer = new BufferedWriter( - new FileWriter(ipv4File)); - writer.write(nic.getIp()); - _ipVmMap.put(nic.getIp(), vm.getName()); - writer.close(); - } catch (IOException e) { - s_logger.warn( - "Failed to create or write to local-ipv4 file " - + ipv4File, e); - } + @Override + public void handleVmStarted(VirtualMachineTO vm) { + for (NicTO nic : vm.getNics()) { + if (nic.getType() == TrafficType.Guest) { + if (nic.getIp() != null) { + String ipv4File = _vmDataDir + File.separator + + vm.getName() + File.separator + "local-ipv4"; + try { + _fs.create(_vmDataDir + File.separator + vm.getName(), + "local-ipv4"); + BufferedWriter writer = new BufferedWriter( + new FileWriter(ipv4File)); + writer.write(nic.getIp()); + _ipVmMap.put(nic.getIp(), vm.getName()); + writer.close(); + } catch (IOException e) { + s_logger.warn( + "Failed to create or write to local-ipv4 file " + + ipv4File, e); + } - } + } - } - } - } + } + } + } - @Override - public void handleVmStopped(String vmName) { - String vmDataDir = _vmDataDir + File.separator + vmName; - Script.runSimpleBashScript("rm -rf " + vmDataDir); - } + @Override + public void handleVmStopped(String vmName) { + String vmDataDir = _vmDataDir + File.separator + vmName; + Script.runSimpleBashScript("rm -rf " + vmDataDir); + } } diff --git a/agent/src/com/cloud/agent/vmdata/VmDataServer.java b/agent/src/com/cloud/agent/vmdata/VmDataServer.java index e9d328e2080..2d85b9bd87e 100644 --- a/agent/src/com/cloud/agent/vmdata/VmDataServer.java +++ b/agent/src/com/cloud/agent/vmdata/VmDataServer.java @@ -28,9 +28,9 @@ import com.cloud.utils.component.Manager; */ public interface VmDataServer extends Manager { - public Answer handleVmDataCommand(VmDataCommand cmd); + public Answer handleVmDataCommand(VmDataCommand cmd); - public void handleVmStarted(VirtualMachineTO vm); + public void handleVmStarted(VirtualMachineTO vm); - public void handleVmStopped(String vmName); + public void handleVmStopped(String vmName); } diff --git a/agent/test/com/cloud/agent/TestAgentShell.java b/agent/test/com/cloud/agent/TestAgentShell.java index 7b6016193ce..d7210acbef3 100644 --- a/agent/test/com/cloud/agent/TestAgentShell.java +++ b/agent/test/com/cloud/agent/TestAgentShell.java @@ -31,12 +31,12 @@ public class TestAgentShell extends Log4jEnabledTestCase { File file = null; try { file = File.createTempFile("wget", ".html"); - AgentShell.wget("http://www.google.com/", file); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("file saved to " + file.getAbsolutePath()); - } - + AgentShell.wget("http://www.google.com/", file); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("file saved to " + file.getAbsolutePath()); + } + } catch (final IOException e) { s_logger.warn("Exception while downloading agent update package, ", e); }