diff --git a/agent/distro/ubuntu/SYSCONFDIR/init.d/cloud-agent.in b/agent/distro/ubuntu/SYSCONFDIR/init.d/cloud-agent.in index ea47440ecfa..c4607cbb799 100755 --- a/agent/distro/ubuntu/SYSCONFDIR/init.d/cloud-agent.in +++ b/agent/distro/ubuntu/SYSCONFDIR/init.d/cloud-agent.in @@ -50,7 +50,9 @@ wait_for_network() { i=1 while [ $i -lt 10 ] do - if ip addr show cloudbr0 |grep -w inet > /dev/null 2>&1; then + # Under Ubuntu and Debian libvirt by default creates a bridge called virbr0. + # That's why we want more then 3 lines back from brctl, so that there is a manually created bridge + if [ "$(brctl show|wc -l)" -gt 2 ]; then break else sleep 1 @@ -74,9 +76,8 @@ start() { log_end_msg 1 exit 1 fi - - #FIXME: wait for network - wait_for_network + + wait_for_network if start-stop-daemon --start --quiet \ --pidfile "$PIDFILE" \ 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/DhcpPacketParser.java b/agent/src/com/cloud/agent/dhcp/DhcpPacketParser.java deleted file mode 100644 index c25d3906802..00000000000 --- a/agent/src/com/cloud/agent/dhcp/DhcpPacketParser.java +++ /dev/null @@ -1,272 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.agent.dhcp; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Formatter; - -import org.apache.log4j.Logger; -import org.jnetpcap.packet.JMemoryPacket; -import org.jnetpcap.packet.JPacket; -import org.jnetpcap.packet.PcapPacket; -import org.jnetpcap.protocol.lan.Ethernet; -import org.jnetpcap.protocol.lan.IEEE802dot1q; -import org.jnetpcap.protocol.network.Ip4; -import org.jnetpcap.protocol.tcpip.Udp; - -import com.cloud.agent.dhcp.DhcpSnooperImpl.DHCPState; - -public class DhcpPacketParser implements Runnable { - private static final Logger s_logger = Logger - .getLogger(DhcpPacketParser.class); - - private enum DHCPPACKET { - OP(0), HTYPE(1), HLEN(2), HOPS(3), XID(4), SECS(8), FLAGS(10), CIADDR( - 12), YIADDR(16), SIDADDR(20), GIADDR(24), CHADDR(28), SNAME(44), FILE( - 108), MAGIC(236), OPTIONS(240); - int offset; - - DHCPPACKET(int i) { - offset = i; - } - - int getValue() { - return offset; - } - } - - private enum DHCPOPTIONTYPE { - PAD(0), MESSAGETYPE(53), REQUESTEDIP(50), END(255); - int type; - - DHCPOPTIONTYPE(int i) { - type = i; - } - - int getValue() { - return type; - } - } - - private enum DHCPMSGTYPE { - DHCPDISCOVER(1), DHCPOFFER(2), DHCPREQUEST(3), DHCPDECLINE(4), DHCPACK( - 5), DHCPNAK(6), DHCPRELEASE(7), DHCPINFORM(8); - int _type; - - DHCPMSGTYPE(int type) { - _type = type; - } - - int getValue() { - return _type; - } - - public static DHCPMSGTYPE valueOf(int type) { - for (DHCPMSGTYPE t : values()) { - if (type == t.getValue()) { - return t; - } - } - return null; - } - } - - private class DHCPMSG { - DHCPMSGTYPE msgType; - byte[] caddr; - byte[] yaddr; - byte[] chaddr; - byte[] requestedIP; - - public DHCPMSG() { - caddr = new byte[4]; - yaddr = new byte[4]; - chaddr = new byte[6]; - } - } - - private PcapPacket _buffer; - private int _offset; - private int _len; - private DhcpSnooperImpl _manager; - - public DhcpPacketParser(PcapPacket buffer, int offset, int len, - DhcpSnooperImpl manager) { - _buffer = buffer; - _offset = offset; - _len = len; - _manager = manager; - } - - private int getPos(int pos) { - return _offset + pos; - } - - private byte getByte(int offset) { - return _buffer.getByte(getPos(offset)); - } - - private void getByteArray(int offset, byte[] array) { - _buffer.getByteArray(getPos(offset), array); - } - - private long getUInt(int offset) { - return _buffer.getUInt(getPos(offset)); - } - - private DHCPMSG getDhcpMsg() { - long magic = getUInt(DHCPPACKET.MAGIC.getValue()); - if (magic != 0x63538263) { - return null; - } - - DHCPMSG msg = new DHCPMSG(); - - int pos = DHCPPACKET.OPTIONS.getValue(); - while (pos <= _len) { - int type = (int) getByte(pos++) & 0xff; - - if (type == DHCPOPTIONTYPE.END.getValue()) { - break; - } - if (type == DHCPOPTIONTYPE.PAD.getValue()) { - continue; - } - int len = 0; - if (pos <= _len) { - len = ((int) getByte(pos++)) & 0xff; - } - - if (type == DHCPOPTIONTYPE.MESSAGETYPE.getValue() - || type == DHCPOPTIONTYPE.REQUESTEDIP.getValue()) { - /* Read data only if needed */ - byte[] data = null; - if ((len + pos) <= _len) { - data = new byte[len]; - getByteArray(pos, data); - } - - if (type == DHCPOPTIONTYPE.MESSAGETYPE.getValue()) { - msg.msgType = DHCPMSGTYPE.valueOf((int) data[0]); - } else if (type == DHCPOPTIONTYPE.REQUESTEDIP.getValue()) { - msg.requestedIP = data; - } - } - - pos += len; - } - - if (msg.msgType == DHCPMSGTYPE.DHCPREQUEST) { - getByteArray(DHCPPACKET.CHADDR.getValue(), msg.chaddr); - getByteArray(DHCPPACKET.CIADDR.getValue(), msg.caddr); - } else if (msg.msgType == DHCPMSGTYPE.DHCPACK) { - getByteArray(DHCPPACKET.YIADDR.getValue(), msg.yaddr); - } - return msg; - } - - private String formatMacAddress(byte[] mac) { - StringBuffer sb = new StringBuffer(); - Formatter formatter = new Formatter(sb); - for (int i = 0; i < mac.length; i++) { - formatter.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""); - } - return sb.toString(); - } - - private String getDestMacAddress() { - Ethernet ether = new Ethernet(); - if (_buffer.hasHeader(ether)) { - byte[] destMac = ether.destination(); - return formatMacAddress(destMac); - } - return null; - } - - private InetAddress getDHCPServerIP() { - Ip4 ip = new Ip4(); - if (_buffer.hasHeader(ip)) { - try { - return InetAddress.getByAddress(ip.source()); - } catch (UnknownHostException e) { - s_logger.debug("Failed to get dhcp server ip address: " - + e.toString()); - } - } - return null; - } - - @Override - public void run() { - DHCPMSG msg = getDhcpMsg(); - - if (msg == null) { - return; - } - - if (msg.msgType == DHCPMSGTYPE.DHCPACK) { - InetAddress ip = null; - try { - ip = InetAddress.getByAddress(msg.yaddr); - String macAddr = getDestMacAddress(); - _manager.setIPAddr(macAddr, ip, DHCPState.DHCPACKED, - getDHCPServerIP()); - } catch (UnknownHostException e) { - - } - } else if (msg.msgType == DHCPMSGTYPE.DHCPREQUEST) { - InetAddress ip = null; - if (msg.requestedIP != null) { - try { - ip = InetAddress.getByAddress(msg.requestedIP); - } catch (UnknownHostException e) { - } - } - if (ip == null) { - try { - ip = InetAddress.getByAddress(msg.caddr); - } catch (UnknownHostException e) { - } - } - - if (ip != null) { - String macAddr = formatMacAddress(msg.chaddr); - _manager.setIPAddr(macAddr, ip, DHCPState.DHCPREQUESTED, null); - } - } - - } - - private void test() { - JPacket packet = new JMemoryPacket( - Ethernet.ID, - " 06fa 8800 00b3 0656 d200 0027 8100 001a 0800 4500 0156 64bf 0000 4011 f3f2 ac1a 6412 ac1a 649e 0043 0044 0001 0000 0001"); - Ethernet eth = new Ethernet(); - if (packet.hasHeader(eth)) { - System.out.print(" ether:" + eth); - } - IEEE802dot1q vlan = new IEEE802dot1q(); - if (packet.hasHeader(vlan)) { - System.out.print(" vlan: " + vlan); - } - - if (packet.hasHeader(Udp.ID)) { - System.out.print("has udp"); - } - } -} 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/DhcpSnooperImpl.java b/agent/src/com/cloud/agent/dhcp/DhcpSnooperImpl.java deleted file mode 100644 index 7195a7e6ff8..00000000000 --- a/agent/src/com/cloud/agent/dhcp/DhcpSnooperImpl.java +++ /dev/null @@ -1,324 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.agent.dhcp; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; -import org.jnetpcap.Pcap; -import org.jnetpcap.PcapBpfProgram; -import org.jnetpcap.PcapIf; -import org.jnetpcap.packet.PcapPacket; -import org.jnetpcap.packet.PcapPacketHandler; -import org.jnetpcap.protocol.tcpip.Udp; - -import com.cloud.utils.Pair; -import com.cloud.utils.concurrency.NamedThreadFactory; - -@Local(value = { DhcpSnooper.class }) -public class DhcpSnooperImpl implements DhcpSnooper { - private static final Logger s_logger = Logger - .getLogger(DhcpSnooperImpl.class); - - public enum DHCPState { - DHCPACKED, DHCPREQUESTED, DHCPRESET; - } - - public class IPAddr { - String _vmName; - InetAddress _ip; - DHCPState _state; - - public IPAddr(InetAddress ip, DHCPState state, String vmName) { - _ip = ip; - _state = state; - _vmName = vmName; - } - } - - protected ExecutorService _executor; - protected Map _macIpMap; - protected Map _ipMacMap; - private DhcpServer _server; - protected long _timeout = 1200000; - protected InetAddress _dhcpServerIp; - - public DhcpSnooperImpl(String bridge, long timeout) { - - _timeout = timeout; - _executor = new ThreadPoolExecutor(10, 10 * 10, 1, TimeUnit.DAYS, - new LinkedBlockingQueue(), new NamedThreadFactory( - "DhcpListener")); - _macIpMap = new ConcurrentHashMap(); - _ipMacMap = new ConcurrentHashMap(); - _server = new DhcpServer(this, bridge); - _server.start(); - } - - @Override - public InetAddress getIPAddr(String macAddr, String vmName) { - String macAddrLowerCase = macAddr.toLowerCase(); - IPAddr addr = _macIpMap.get(macAddrLowerCase); - if (addr == null) { - addr = new IPAddr(null, DHCPState.DHCPRESET, vmName); - _macIpMap.put(macAddrLowerCase, addr); - } else { - addr._state = DHCPState.DHCPRESET; - } - - synchronized (addr) { - try { - addr.wait(_timeout); - } catch (InterruptedException e) { - } - if (addr._state == DHCPState.DHCPACKED) { - addr._state = DHCPState.DHCPRESET; - return addr._ip; - } - } - - return null; - } - - public InetAddress getDhcpServerIP() { - return _dhcpServerIp; - } - - @Override - public void cleanup(String macAddr, String vmName) { - try { - if (macAddr == null) { - return; - } - _macIpMap.remove(macAddr); - _ipMacMap.values().remove(macAddr); - } catch (Exception e) { - s_logger.debug("Failed to cleanup: " + e.toString()); - } - } - - @Override - public Map syncIpAddr() { - Collection ips = _macIpMap.values(); - HashMap vmIpMap = new HashMap(); - for (IPAddr ip : ips) { - if (ip._state == DHCPState.DHCPACKED) { - vmIpMap.put(ip._vmName, ip._ip); - } - } - return vmIpMap; - } - - @Override - public void initializeMacTable(List> macVmNameList) { - for (Pair macVmname : macVmNameList) { - IPAddr ipAdrr = new IPAddr(null, DHCPState.DHCPRESET, - macVmname.second()); - _macIpMap.put(macVmname.first(), ipAdrr); - } - } - - protected void setIPAddr(String macAddr, InetAddress ip, DHCPState state, - InetAddress dhcpServerIp) { - String macAddrLowerCase = macAddr.toLowerCase(); - if (state == DHCPState.DHCPREQUESTED) { - IPAddr ipAddr = _macIpMap.get(macAddrLowerCase); - if (ipAddr == null) { - return; - } - - _ipMacMap.put(ip, macAddr); - } else if (state == DHCPState.DHCPACKED) { - _dhcpServerIp = dhcpServerIp; - String destMac = macAddrLowerCase; - if (macAddrLowerCase.equalsIgnoreCase("ff:ff:ff:ff:ff:ff")) { - destMac = _ipMacMap.get(ip); - if (destMac == null) { - return; - } - } - - IPAddr addr = _macIpMap.get(destMac); - if (addr != null) { - addr._ip = ip; - addr._state = state; - synchronized (addr) { - addr.notify(); - } - } - } - } - - /* - * (non-Javadoc) - * - * @see com.cloud.agent.dhcp.DhcpSnooper#stop() - */ - @Override - public boolean stop() { - _executor.shutdown(); - _server.StopServer(); - return true; - } - - private class DhcpServer extends Thread { - private DhcpSnooperImpl _manager; - private String _bridge; - private Pcap _pcapedDev; - private boolean _loop; - - public DhcpServer(DhcpSnooperImpl mgt, String bridge) { - _manager = mgt; - _bridge = bridge; - _loop = true; - } - - public void StopServer() { - _loop = false; - _pcapedDev.breakloop(); - _pcapedDev.close(); - } - - private Pcap initializePcap() { - try { - List alldevs = new ArrayList(); - StringBuilder errBuf = new StringBuilder(); - int r = Pcap.findAllDevs(alldevs, errBuf); - if (r == Pcap.NOT_OK || alldevs.isEmpty()) { - return null; - } - - PcapIf dev = null; - for (PcapIf device : alldevs) { - if (device.getName().equalsIgnoreCase(_bridge)) { - dev = device; - break; - } - } - - if (dev == null) { - s_logger.debug("Pcap: Can't find device: " + _bridge - + " to listen on"); - return null; - } - - int snaplen = 64 * 1024; - int flags = Pcap.MODE_PROMISCUOUS; - int timeout = 10 * 1000; - Pcap pcap = Pcap.openLive(dev.getName(), snaplen, flags, - timeout, errBuf); - if (pcap == null) { - s_logger.debug("Pcap: Can't open " + _bridge); - return null; - } - - PcapBpfProgram program = new PcapBpfProgram(); - String expr = "dst port 68 or 67"; - int optimize = 0; - int netmask = 0xFFFFFF00; - if (pcap.compile(program, expr, optimize, netmask) != Pcap.OK) { - s_logger.debug("Pcap: can't compile BPF"); - return null; - } - - if (pcap.setFilter(program) != Pcap.OK) { - s_logger.debug("Pcap: Can't set filter"); - return null; - } - return pcap; - } catch (Exception e) { - s_logger.debug("Failed to initialized: " + e.toString()); - } - return null; - } - - public void run() { - while (_loop) { - try { - _pcapedDev = initializePcap(); - if (_pcapedDev == null) { - return; - } - - PcapPacketHandler jpacketHandler = new PcapPacketHandler() { - public void nextPacket(PcapPacket packet, String user) { - Udp u = new Udp(); - if (packet.hasHeader(u)) { - int offset = u.getOffset() + u.getLength(); - _executor.execute(new DhcpPacketParser(packet, - offset, u.length() - u.getLength(), - _manager)); - } - } - }; - s_logger.debug("Starting DHCP snooping on " + _bridge); - int retValue = _pcapedDev.loop(-1, jpacketHandler, - "pcapPacketHandler"); - if (retValue == -1) { - s_logger.debug("Pcap: failed to set loop handler"); - } else if (retValue == -2 && !_loop) { - s_logger.debug("Pcap: terminated"); - return; - } - _pcapedDev.close(); - } catch (Exception e) { - s_logger.debug("Pcap error:" + e.toString()); - } - } - } - } - - static public void main(String args[]) { - s_logger.addAppender(new org.apache.log4j.ConsoleAppender( - new org.apache.log4j.PatternLayout(), "System.out")); - final DhcpSnooperImpl manager = new DhcpSnooperImpl("cloudbr0", 10000); - s_logger.debug(manager.getIPAddr("02:00:4c:66:00:03", "i-2-5-VM")); - manager.stop(); - - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - // TODO configure timeout here - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public String getName() { - return "DhcpSnooperImpl"; - } - -} 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/CloudZonesComputingResource.java b/agent/src/com/cloud/agent/resource/computing/CloudZonesComputingResource.java deleted file mode 100644 index 37bfc508686..00000000000 --- a/agent/src/com/cloud/agent/resource/computing/CloudZonesComputingResource.java +++ /dev/null @@ -1,293 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.agent.resource.computing; - -import java.net.InetAddress; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; -import org.libvirt.Connect; -import org.libvirt.Domain; -import org.libvirt.LibvirtException; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.StartAnswer; -import com.cloud.agent.api.StartCommand; - -import com.cloud.agent.api.StopAnswer; -import com.cloud.agent.api.StopCommand; - -import com.cloud.agent.api.routing.SavePasswordCommand; -import com.cloud.agent.api.routing.VmDataCommand; -import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.agent.dhcp.DhcpSnooper; -import com.cloud.agent.dhcp.DhcpSnooperImpl; - -import com.cloud.agent.resource.computing.LibvirtComputingResource; -import com.cloud.agent.resource.computing.LibvirtConnection; -import com.cloud.agent.resource.computing.LibvirtVMDef; -import com.cloud.agent.resource.computing.LibvirtVMDef.DiskDef; -import com.cloud.agent.resource.computing.LibvirtVMDef.InterfaceDef; -import com.cloud.agent.vmdata.JettyVmDataServer; -import com.cloud.agent.vmdata.VmDataServer; - -import com.cloud.network.Networks.TrafficType; -import com.cloud.utils.Pair; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; - -/** - * Logic specific to the Cloudzones feature - * - * } - **/ - -public class CloudZonesComputingResource extends LibvirtComputingResource { - private static final Logger s_logger = Logger - .getLogger(CloudZonesComputingResource.class); - protected DhcpSnooper _dhcpSnooper; - String _parent; - long _dhcpTimeout; - protected String _hostIp; - protected String _hostMacAddress; - protected VmDataServer _vmDataServer = new JettyVmDataServer(); - - private void setupDhcpManager(Connect conn, String bridgeName) { - - _dhcpSnooper = new DhcpSnooperImpl(bridgeName, _dhcpTimeout); - - List> macs = new ArrayList>(); - try { - int[] domainIds = conn.listDomains(); - for (int i = 0; i < domainIds.length; i++) { - Domain vm = conn.domainLookupByID(domainIds[i]); - if (vm.getName().startsWith("i-")) { - List nics = getInterfaces(conn, vm.getName()); - InterfaceDef nic = nics.get(0); - macs.add(new Pair(nic.getMacAddress(), vm - .getName())); - } - } - } catch (LibvirtException e) { - s_logger.debug("Failed to get MACs: " + e.toString()); - } - - _dhcpSnooper.initializeMacTable(macs); - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - boolean success = super.configure(name, params); - if (!success) { - return false; - } - - _parent = (String) params.get("mount.path"); - - try { - _dhcpTimeout = Long.parseLong((String) params.get("dhcp.timeout")); - } catch (Exception e) { - _dhcpTimeout = 1200000; - } - - _hostIp = (String) params.get("host.ip"); - _hostMacAddress = (String) params.get("host.mac.address"); - - try { - Connect conn; - conn = LibvirtConnection.getConnection(); - setupDhcpManager(conn, _guestBridgeName); - } catch (LibvirtException e) { - s_logger.debug("Failed to get libvirt connection:" + e.toString()); - return false; - } - - _dhcpSnooper.configure(name, params); - _vmDataServer.configure(name, params); - - return true; - } - - @Override - protected synchronized StartAnswer execute(StartCommand cmd) { - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); - 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()); - - NicTO[] nics = vmSpec.getNics(); - for (NicTO nic : nics) { - if (nic.isSecurityGroupEnabled()) { - if (vmSpec.getType() != VirtualMachine.Type.User) { - default_network_rules_for_systemvm(conn, vmName); - } else { - nic.setIp(null); - default_network_rules(conn, vmName, nic, vmSpec.getId()); - } - } - } - - // Attach each data volume to the VM, if there is a deferred - // attached disk - for (DiskDef disk : vm.getDevices().getDisks()) { - if (disk.isAttachDeferred()) { - attachOrDetachDevice(conn, true, vmName, disk.toString()); - } - } - - if (vmSpec.getType() == VirtualMachine.Type.User) { - for (NicTO nic : nics) { - if (nic.getType() == TrafficType.Guest) { - InetAddress ipAddr = _dhcpSnooper.getIPAddr( - nic.getMac(), vmName); - if (ipAddr == null) { - s_logger.debug("Failed to get guest DHCP ip, stop it"); - StopCommand stpCmd = new StopCommand(vmName); - execute(stpCmd); - return new StartAnswer(cmd, - "Failed to get guest DHCP ip, stop it"); - } - s_logger.debug(ipAddr); - nic.setIp(ipAddr.getHostAddress()); - - post_default_network_rules(conn, vmName, nic, - vmSpec.getId(), _dhcpSnooper.getDhcpServerIP(), - _hostIp, _hostMacAddress); - _vmDataServer.handleVmStarted(cmd.getVirtualMachine()); - } - } - } - - 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); - } - } - } - } - - 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(); - - try { - Domain dm = conn.domainLookupByUUID(UUID - .nameUUIDFromBytes(vmName.getBytes())); - } catch (LibvirtException e) { - state = State.Stopped; - return new StopAnswer(cmd, null, 0, bytesSent, bytesReceived); - } - - String macAddress = null; - if (vmName.startsWith("i-")) { - List nics = getInterfaces(conn, vmName); - if (!nics.isEmpty()) { - macAddress = nics.get(0).getMacAddress(); - } - } - - destroy_network_rules_for_vm(conn, vmName); - String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM); - - try { - cleanupVnet(conn, cmd.getVnet()); - _dhcpSnooper.cleanup(macAddress, vmName); - _vmDataServer.handleVmStopped(cmd.getVmName()); - } catch (Exception e) { - - } - - 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); - } - } - } - } - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof VmDataCommand) { - return execute((VmDataCommand) cmd); - } else if (cmd instanceof SavePasswordCommand) { - return execute((SavePasswordCommand) cmd); - } - return super.executeRequest(cmd); - } - - protected Answer execute(final VmDataCommand cmd) { - return _vmDataServer.handleVmDataCommand(cmd); - } - - protected Answer execute(final SavePasswordCommand cmd) { - return new Answer(cmd); - } - -} 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 9cdd8634f20..e7e19c94928 100755 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -2483,7 +2483,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0); devices.addDevice(console); - GraphicDef grap = new GraphicDef("vnc", (short) 0, true, null, null, + GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null, null); devices.addDevice(grap); @@ -2509,6 +2509,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements protected synchronized StartAnswer execute(StartCommand cmd) { VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + vmSpec.setVncAddr(cmd.getHostIp()); String vmName = vmSpec.getName(); LibvirtVMDef vm = null; @@ -3952,24 +3953,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements if (!_can_bridge_firewall) { return false; } - List intfs = getInterfaces(conn, vmName); - if (intfs.size() < 1) { - return false; - } - /* FIX ME: */ - String brname = null; - if (vmName.startsWith("r-")) { - InterfaceDef intf = intfs.get(0); - brname = intf.getBrName(); - } else { - InterfaceDef intf = intfs.get(intfs.size() - 1); - brname = intf.getBrName(); - } Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); - cmd.add("--brname", brname); + cmd.add("--localbrname", _linkLocalBridgeName); String result = cmd.execute(); if (result != null) { return false; 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 0210351c41d..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 auotPort, - String listenAddr, String passwd, String keyMap) { - _type = type; - _port = port; - _autoPort = auotPort; - _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); } diff --git a/api/src/com/cloud/agent/api/StartCommand.java b/api/src/com/cloud/agent/api/StartCommand.java index fcd8b360fa0..4d871389836 100644 --- a/api/src/com/cloud/agent/api/StartCommand.java +++ b/api/src/com/cloud/agent/api/StartCommand.java @@ -17,12 +17,14 @@ package com.cloud.agent.api; import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.host.Host; /** */ public class StartCommand extends Command { VirtualMachineTO vm; - + String hostIp; + public VirtualMachineTO getVirtualMachine() { return vm; } @@ -34,8 +36,17 @@ public class StartCommand extends Command { protected StartCommand() { } - + public StartCommand(VirtualMachineTO vm) { this.vm = vm; } + + public StartCommand(VirtualMachineTO vm, Host host) { + this.vm = vm; + this.hostIp = host.getPrivateIpAddress(); + } + + public String getHostIp() { + return this.hostIp; + } } diff --git a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java index ec93fc65718..42d91626e35 100644 --- a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java +++ b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java @@ -40,6 +40,7 @@ public class VirtualMachineTO { boolean enableHA; boolean limitCpuUse; String vncPassword; + String vncAddr; Map params; VolumeTO[] disks; @@ -191,6 +192,14 @@ public class VirtualMachineTO { public void setVncPassword(String vncPassword) { this.vncPassword = vncPassword; } + + public String getVncAddr() { + return this.vncAddr; + } + + public void setVncAddr(String vncAddr) { + this.vncAddr = vncAddr; + } public Map getDetails() { return params; diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index 29bae6b7234..67f76eae099 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -361,6 +361,10 @@ public class ApiConstants { public static final String NETWORK = "network"; public static final String VPC_ID = "vpcid"; public static final String GATEWAY_ID = "gatewayid"; + public static final String CAN_USE_FOR_DEPLOY = "canusefordeploy"; + public static final String RESOURCE_IDS = "resourceids"; + public static final String RESOURCE_ID = "resourceid"; + public static final String CUSTOMER = "customer"; public enum HostDetails { all, capacity, events, stats, min; diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/com/cloud/api/BaseCmd.java index 294e2647369..25c54e646d7 100755 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/com/cloud/api/BaseCmd.java @@ -51,6 +51,7 @@ import com.cloud.projects.Project; import com.cloud.projects.ProjectService; import com.cloud.resource.ResourceService; import com.cloud.server.ManagementService; +import com.cloud.server.TaggedResourceService; import com.cloud.storage.StorageService; import com.cloud.storage.snapshot.SnapshotService; import com.cloud.template.TemplateService; @@ -131,6 +132,7 @@ public abstract class BaseCmd { public static StorageNetworkService _storageNetworkService; public static VpcService _vpcService; public static NetworkACLService _networkACLService; + public static TaggedResourceService _taggedResourceService; static void setComponents(ResponseGenerator generator) { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); @@ -160,6 +162,7 @@ public abstract class BaseCmd { _storageNetworkService = locator.getManager(StorageNetworkService.class); _vpcService = locator.getManager(VpcService.class); _networkACLService = locator.getManager(NetworkACLService.class); + _taggedResourceService = locator.getManager(TaggedResourceService.class); } public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index 5f79e197385..35e6972a080 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -58,6 +58,7 @@ import com.cloud.api.response.ProviderResponse; import com.cloud.api.response.RemoteAccessVpnResponse; import com.cloud.api.response.ResourceCountResponse; import com.cloud.api.response.ResourceLimitResponse; +import com.cloud.api.response.ResourceTagResponse; import com.cloud.api.response.SecurityGroupResponse; import com.cloud.api.response.ServiceOfferingResponse; import com.cloud.api.response.ServiceResponse; @@ -124,6 +125,7 @@ import com.cloud.org.Cluster; import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; +import com.cloud.server.ResourceTag; import com.cloud.storage.Snapshot; import com.cloud.storage.StoragePool; import com.cloud.storage.Swift; @@ -292,6 +294,7 @@ public interface ResponseGenerator { Long getIdentiyId(String tableName, String token); /** +<<<<<<< HEAD * @param offering * @return */ @@ -320,4 +323,6 @@ public interface ResponseGenerator { * @return */ StaticRouteResponse createStaticRouteResponse(StaticRoute result); + + ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag); } diff --git a/api/src/com/cloud/api/commands/AddClusterCmd.java b/api/src/com/cloud/api/commands/AddClusterCmd.java index 6688dee008d..0ff77e01c51 100755 --- a/api/src/com/cloud/api/commands/AddClusterCmd.java +++ b/api/src/com/cloud/api/commands/AddClusterCmd.java @@ -31,8 +31,10 @@ import com.cloud.api.ServerApiException; import com.cloud.api.response.ClusterResponse; import com.cloud.api.response.ListResponse; import com.cloud.exception.DiscoveryException; +import com.cloud.exception.ResourceInUseException; import com.cloud.org.Cluster; import com.cloud.user.Account; +import com.cloud.utils.IdentityProxy; @Implementation(description="Adds a new cluster", responseObject=ClusterResponse.class) public class AddClusterCmd extends BaseCmd { @@ -166,7 +168,14 @@ public class AddClusterCmd extends BaseCmd { this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + } catch (ResourceInUseException ex) { + s_logger.warn("Exception: ", ex); + ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + for (IdentityProxy proxyObj : ex.getIdProxyList()) { + e.addProxyObject(proxyObj.getTableName(), proxyObj.getValue(), proxyObj.getidFieldName()); + } + throw e; } } } diff --git a/api/src/com/cloud/api/commands/CreateTagsCmd.java b/api/src/com/cloud/api/commands/CreateTagsCmd.java new file mode 100644 index 00000000000..5a0b56e544e --- /dev/null +++ b/api/src/com/cloud/api/commands/CreateTagsCmd.java @@ -0,0 +1,131 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.api.commands; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.event.EventTypes; +import com.cloud.server.ResourceTag; +import com.cloud.server.ResourceTag.TaggedResourceType; + +/** + * @author Alena Prokharchyk + */ + +@Implementation(description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +public class CreateTagsCmd extends BaseAsyncCmd{ + public static final Logger s_logger = Logger.getLogger(CreateTagsCmd.class.getName()); + + private static final String s_name = "createtagsresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, required=true, description = "Map of tags (key/value pairs)") + private Map tag; + + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="type of the resource") + private String resourceType; + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + collectionType=CommandType.STRING, description="list of resources to create the tags for") + private List resourceIds; + + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="identifies client specific tag. " + + "When the value is not null, the tag can't be used by cloudStack code internally") + private String customer; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public TaggedResourceType getResourceType(){ + return _taggedResourceService.getResourceType(resourceType); + } + + public Map getTags() { + Map tagsMap = null; + if (!tag.isEmpty()) { + tagsMap = new HashMap(); + Collection servicesCollection = tag.values(); + Iterator iter = servicesCollection.iterator(); + while (iter.hasNext()) { + HashMap services = (HashMap) iter.next(); + String key = services.get("key"); + String value = services.get("value"); + tagsMap.put(key, value); + } + } + return tagsMap; + } + + public List getResourceIds() { + return resourceIds; + } + + public String getCustomer() { + return customer; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + //FIXME - validate the owner here + return 1; + } + + @Override + public void execute() { + List tags = _taggedResourceService.createTags(getResourceIds(), getResourceType(), getTags(), getCustomer()); + + if (tags != null && !tags.isEmpty()) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create tags"); + } + } + + @Override + public String getEventType() { + return EventTypes.EVENT_TAGS_CREATE; + } + + @Override + public String getEventDescription() { + return "creating tags"; + } +} diff --git a/api/src/com/cloud/api/commands/DeleteTagsCmd.java b/api/src/com/cloud/api/commands/DeleteTagsCmd.java new file mode 100644 index 00000000000..a84a09ec38b --- /dev/null +++ b/api/src/com/cloud/api/commands/DeleteTagsCmd.java @@ -0,0 +1,112 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +package com.cloud.api.commands; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.event.EventTypes; +import com.cloud.server.ResourceTag; +import com.cloud.server.ResourceTag.TaggedResourceType; + +/** + * @author Alena Prokharchyk + */ + +@Implementation(description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +public class DeleteTagsCmd extends BaseAsyncCmd{ + public static final Logger s_logger = Logger.getLogger(DeleteTagsCmd.class.getName()); + + private static final String s_name = "deleteTagsresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "Delete tags matching key/value pairs") + private Map tag; + + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="Delete tag by resource type") + private String resourceType; + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + collectionType=CommandType.STRING, description="Delete tags for resource id(s)") + private List resourceIds; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public TaggedResourceType getResourceType(){ + return _taggedResourceService.getResourceType(resourceType); + } + + public Map getTags() { + Map tagsMap = null; + if (tag != null && !tag.isEmpty()) { + tagsMap = new HashMap(); + Collection servicesCollection = tag.values(); + Iterator iter = servicesCollection.iterator(); + while (iter.hasNext()) { + HashMap services = (HashMap) iter.next(); + String key = services.get("key"); + String value = services.get("value"); + tagsMap.put(key, value); + } + } + return tagsMap; + } + + public List getResourceIds() { + return resourceIds; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + //FIXME - validate the owner here + return 1; + } + + @Override + public void execute() { + boolean success = _taggedResourceService.deleteTags(getResourceIds(), getResourceType(), getTags()); + + if (success) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete tags"); + } + } + + @Override + public String getEventType() { + return EventTypes.EVENT_TAGS_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting tags"; + } +} diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index 4949cf0ec38..9e2bc24df8f 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -252,9 +253,9 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); } - Map ipToNetworkMap = null; + LinkedHashMap ipToNetworkMap = null; if (ipToNetworkList != null && !ipToNetworkList.isEmpty()) { - ipToNetworkMap = new HashMap(); + ipToNetworkMap = new LinkedHashMap(); Collection ipsCollection = ipToNetworkList.values(); Iterator iter = ipsCollection.iterator(); while (iter.hasNext()) { diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/com/cloud/api/commands/ListNetworksCmd.java index 851b0ec7406..689f1db4e2c 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworksCmd.java @@ -63,10 +63,11 @@ public class ListNetworksCmd extends BaseListProjectAndAccountResourcesCmd { @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="list networks by physical network id") private Long physicalNetworkId; - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list network offerings supporting certain services") + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list networks supporting certain services") private List supportedServices; @Parameter(name=ApiConstants.RESTART_REQUIRED, type=CommandType.BOOLEAN, description="list networks by restartRequired") + private Boolean restartRequired; @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if need to list only networks which support specifying ip ranges") @@ -75,6 +76,9 @@ public class ListNetworksCmd extends BaseListProjectAndAccountResourcesCmd { @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") private Long vpcId; + + @Parameter(name=ApiConstants.CAN_USE_FOR_DEPLOY, type=CommandType.BOOLEAN, description="list networks available for vm deployment") + private Boolean canUseForDeploy; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -122,6 +126,10 @@ public class ListNetworksCmd extends BaseListProjectAndAccountResourcesCmd { public Long getVpcId() { return vpcId; + } + + public Boolean canUseForDeploy() { + return canUseForDeploy; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListTagsCmd.java b/api/src/com/cloud/api/commands/ListTagsCmd.java new file mode 100644 index 00000000000..8b9eae195ed --- /dev/null +++ b/api/src/com/cloud/api/commands/ListTagsCmd.java @@ -0,0 +1,94 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseListProjectAndAccountResourcesCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.ResourceTagResponse; +import com.cloud.server.ResourceTag; + +/** + * @author Alena Prokharchyk + */ + +@Implementation(description = "List resource tag(s)", responseObject = ResourceTagResponse.class, since = "Burbank") +public class ListTagsCmd extends BaseListProjectAndAccountResourcesCmd{ + private static final String s_name = "listtagsresponse"; + + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, description="list by resource type") + private String resourceType; + + @Parameter(name=ApiConstants.RESOURCE_ID, type=CommandType.STRING, description="list by resource id") + private String resourceId; + + @Parameter(name=ApiConstants.KEY, type=CommandType.STRING, description="list by key") + private String key; + + @Parameter(name=ApiConstants.VALUE, type=CommandType.STRING, description="list by value") + private String value; + + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="list by customer name") + private String customer; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + + List tags = _taggedResourceService.listTags(this); + ListResponse response = new ListResponse(); + List tagResponses = new ArrayList(); + for (ResourceTag tag : tags) { + ResourceTagResponse tagResponse = _responseGenerator.createResourceTagResponse(tag); + tagResponses.add(tagResponse); + } + response.setResponses(tagResponses); + + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + public String getResourceType() { + return resourceType; + } + + public String getResourceId() { + return resourceId; + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + @Override + public String getCommandName() { + return s_name; + } + + public String getCustomer() { + return customer; + } +} diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index 867895ee53c..38e4cd42f3a 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -133,6 +133,9 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the network belongs to") private IdentityProxy vpcId = new IdentityProxy("vpc"); + + @SerializedName(ApiConstants.CAN_USE_FOR_DEPLOY) @Param(description="list networks available for vm deployment") + private Boolean canUseForDeploy; public void setId(Long id) { this.id.setValue(id); @@ -279,4 +282,8 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setVpcId(Long vpcId) { this.vpcId.setValue(vpcId); } + + public void setCanUseForDeploy(Boolean canUseForDeploy) { + this.canUseForDeploy = canUseForDeploy; + } } diff --git a/api/src/com/cloud/api/response/ResourceTagResponse.java b/api/src/com/cloud/api/response/ResourceTagResponse.java new file mode 100644 index 00000000000..aa69141113e --- /dev/null +++ b/api/src/com/cloud/api/response/ResourceTagResponse.java @@ -0,0 +1,100 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.api.response; + +import com.cloud.api.ApiConstants; +import com.cloud.serializer.Param; +import com.cloud.utils.IdentityProxy; +import com.google.gson.annotations.SerializedName; + +/** + * @author Alena Prokharchyk + */ + +@SuppressWarnings("unused") +public class ResourceTagResponse extends BaseResponse implements ControlledEntityResponse{ + @SerializedName(ApiConstants.KEY) @Param(description="tag key name") + private String key; + + @SerializedName(ApiConstants.VALUE) @Param(description="tag value") + private String value; + + @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type") + private String resourceType; + + @SerializedName(ApiConstants.RESOURCE_ID) @Param(description="id of the resource") + private String id; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account associated with the tag") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id the tag belongs to") + private IdentityProxy projectId = new IdentityProxy("projects"); + + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name where tag belongs to") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the ID of the domain associated with the tag") + private IdentityProxy domainId = new IdentityProxy("domain"); + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain associated with the tag") + private String domainName; + + @SerializedName(ApiConstants.CUSTOMER) @Param(description="customer associated with the tag") + private String customer; + + public void setKey(String key) { + this.key = key; + } + + public void setValue(String value) { + this.value = value; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public void setId(String id) { + this.id = id; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setDomainId(Long domainId) { + this.domainId.setValue(domainId); + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setProjectId(Long projectId) { + this.projectId.setValue(projectId); + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setCustomer(String customer) { + this.customer = customer; + } +} diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index 5fbb4bfa617..9eae59dff43 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -278,4 +278,9 @@ public class EventTypes { // Static routes public static final String EVENT_STATIC_ROUTE_CREATE = "STATIC.ROUTE.CREATE"; public static final String EVENT_STATIC_ROUTE_DELETE = "STATIC.ROUTE.DELETE"; + + // tag related events + public static final String EVENT_TAGS_CREATE = "CREATE_TAGS"; + public static final String EVENT_TAGS_DELETE = "DELETE_TAGS"; + } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 3ee22a0a0db..be54e840fea 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -168,5 +168,9 @@ public interface NetworkService { Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, String startIp, String endIP, String gateway, String netmask, long networkOwnerId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; - + /** + * @param network + * @return + */ + boolean canUseForDeploy(Network network); } diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index d971a407e05..10654539bb6 100755 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -31,6 +31,7 @@ import com.cloud.api.commands.UpdateHostCmd; import com.cloud.api.commands.UpdateHostPasswordCmd; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceInUseException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; @@ -61,7 +62,7 @@ public interface ResourceService { * @throws IllegalArgumentException * @throws DiscoveryException */ - List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException; + List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException; boolean deleteCluster(DeleteClusterCmd cmd); diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java new file mode 100644 index 00000000000..c3307b6b17b --- /dev/null +++ b/api/src/com/cloud/server/ResourceTag.java @@ -0,0 +1,66 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.server; + +import com.cloud.acl.ControlledEntity; + +/** + * @author Alena Prokharchyk + */ +public interface ResourceTag extends ControlledEntity{ + + public enum TaggedResourceType { + UserVm, + Template, + ISO, + Volume, + Snapshot, + Network, + LoadBalancer, + PortForwardingRule, + FirewallRule, + SecurityGroup, + PublicIpAddress + } + + /** + * @return + */ + long getId(); + + /** + * @return + */ + String getKey(); + + /** + * @return + */ + String getValue(); + + /** + * @return + */ + long getResourceId(); + + /** + * @return + */ + TaggedResourceType getResourceType(); + + /** + * @return + */ + String getCustomer(); + +} diff --git a/api/src/com/cloud/server/TaggedResourceService.java b/api/src/com/cloud/server/TaggedResourceService.java new file mode 100644 index 00000000000..d76d19265df --- /dev/null +++ b/api/src/com/cloud/server/TaggedResourceService.java @@ -0,0 +1,57 @@ +// Copyright 2012 Citrix Systems, Inc. Licensed under the +// Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. Citrix Systems, Inc. +// reserves all rights not expressly granted by the License. +// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Automatically generated by addcopyright.py at 04/03/2012 +package com.cloud.server; + +import java.util.List; +import java.util.Map; + +import com.cloud.api.commands.ListTagsCmd; +import com.cloud.server.ResourceTag.TaggedResourceType; + +/** + * @author Alena Prokharchyk + */ +public interface TaggedResourceService { + + TaggedResourceType getResourceType (String resourceTypeStr); + + /** + * @param resourceIds TODO + * @param resourceType + * @param tags + * @param customer TODO + * @return + */ + List createTags(List resourceIds, TaggedResourceType resourceType, Map tags, String customer); + + /** + * @param resourceId + * @param resourceType + * @return + */ + String getUuid(String resourceId, TaggedResourceType resourceType); + + /** + * @param listTagsCmd + * @return + */ + List listTags(ListTagsCmd listTagsCmd); + + /** + * @param resourceIds + * @param resourceType + * @param tags + * @return + */ + boolean deleteTags(List resourceIds, TaggedResourceType resourceType, Map tags); +} diff --git a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java index 075a92f346b..74eb6393390 100644 --- a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java +++ b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java @@ -23,6 +23,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.net.URLEncoder; import java.security.KeyStore; import java.security.SignatureException; import java.security.cert.Certificate; @@ -178,7 +179,7 @@ public class EC2RestServlet extends HttpServlet { } String keystore = EC2Prop.getProperty( "keystore" ); keystorePassword = EC2Prop.getProperty( "keystorePass" ); - wsdlVersion = EC2Prop.getProperty( "WSDLVersion", "2009-11-30" ); + wsdlVersion = EC2Prop.getProperty( "WSDLVersion", "2010-11-15" ); version = EC2Prop.getProperty( "cloudbridgeVersion", "UNKNOWN VERSION" ); String installedPath = System.getenv("CATALINA_HOME"); @@ -1706,18 +1707,37 @@ public class EC2RestServlet extends HttpServlet { // [C] Verify the signature // -> getting the query-string in this way maintains its URL encoding - EC2RestAuth restAuth = new EC2RestAuth(); - restAuth.setHostHeader( request.getHeader( "Host" )); - String requestUri = request.getRequestURI(); - - //If forwarded from another basepath: - String forwardedPath = (String) request.getAttribute("javax.servlet.forward.request_uri"); - if(forwardedPath!=null){ - requestUri=forwardedPath; - } - restAuth.setHTTPRequestURI( requestUri); - restAuth.setQueryString( request.getQueryString()); - + EC2RestAuth restAuth = new EC2RestAuth(); + restAuth.setHostHeader( request.getHeader( "Host" )); + String requestUri = request.getRequestURI(); + + // If forwarded from another basepath: + String forwardedPath = (String) request.getAttribute("javax.servlet.forward.request_uri"); + if(forwardedPath!=null){ + requestUri=forwardedPath; + } + restAuth.setHTTPRequestURI( requestUri); + + String queryString = request.getQueryString(); + // getQueryString returns null (does it ever NOT return null for these), + // we need to construct queryString to avoid changing the auth code... + if (queryString == null) { + // construct our idea of a queryString with parameters! + Enumeration params = request.getParameterNames(); + if (params != null) { + while(params.hasMoreElements()) { + String paramName = (String) params.nextElement(); + // exclude the signature string obviously. ;) + if (paramName.equalsIgnoreCase("Signature")) continue; + if (queryString == null) + queryString = paramName + "=" + request.getParameter(paramName); + else + queryString = queryString + "&" + paramName + "=" + URLEncoder.encode(request.getParameter(paramName), "UTF-8"); + } + } + } + restAuth.setQueryString(queryString); + if ( restAuth.verifySignature( request.getMethod(), cloudSecretKey, signature, sigMethod )) { UserContext.current().initContext( cloudAccessKey, cloudSecretKey, cloudAccessKey, "REST request", null ); return true; diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2SnapshotFilterSet.java b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2SnapshotFilterSet.java index c69191cba94..9e3e4ade943 100644 --- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2SnapshotFilterSet.java +++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2SnapshotFilterSet.java @@ -18,13 +18,16 @@ package com.cloud.bridge.service.core.ec2; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.TimeZone; import com.cloud.bridge.service.UserContext; import com.cloud.bridge.service.exception.EC2ServiceException; import com.cloud.bridge.util.DateHelper; +import com.cloud.bridge.util.EC2RestAuth; public class EC2SnapshotFilterSet { @@ -121,7 +124,12 @@ public class EC2SnapshotFilterSet { } else if (filterName.equalsIgnoreCase( "status" )) { - return containsString( "completed", valueSet ); + if ( snap.getState().equalsIgnoreCase("backedup")) + return containsString( "completed", valueSet ); + else if (snap.getState().equalsIgnoreCase("creating") || snap.getState().equalsIgnoreCase("backingup")) + return containsString( "pending", valueSet ); + else + return containsString( "error", valueSet ); } else if (filterName.equalsIgnoreCase( "volume-id" )) { @@ -160,11 +168,14 @@ public class EC2SnapshotFilterSet { private boolean containsTime( Calendar lookingFor, String[] set ) throws ParseException { + lookingFor.setTimeZone(TimeZone.getTimeZone("GMT")); + Date lookingForDate = lookingFor.getTime(); for (String s : set) { //System.out.println( "contsinsCalendar: " + lookingFor + " " + set[i] ); - Calendar toMatch = Calendar.getInstance(); - toMatch.setTime( DateHelper.parseISO8601DateString( s )); - if (0 == lookingFor.compareTo( toMatch )) return true; + Calendar toMatch = EC2RestAuth.parseDateString(s); + toMatch.setTimeZone(TimeZone.getTimeZone("GMT")); + Date toMatchDate = toMatch.getTime(); + if ( 0 == lookingForDate.compareTo(toMatchDate)) return true; } return false; } diff --git a/build/build-cloud.xml b/build/build-cloud.xml index 76d2bc85e29..f95768a489c 100755 --- a/build/build-cloud.xml +++ b/build/build-cloud.xml @@ -285,7 +285,6 @@ - @@ -480,7 +479,7 @@ - + @@ -586,24 +585,59 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - diff --git a/build/build-common.xml b/build/build-common.xml index 1d1aa87361d..7240f5323c3 100755 --- a/build/build-common.xml +++ b/build/build-common.xml @@ -73,7 +73,7 @@ - + diff --git a/build/developer.xml b/build/developer.xml index 127581e2d4e..4d466b76478 100755 --- a/build/developer.xml +++ b/build/developer.xml @@ -36,8 +36,6 @@ - - @@ -163,11 +161,7 @@ - - - - - + diff --git a/build/package.xml b/build/package.xml index 7fd7a5d1a5d..0c2ca3a9b4b 100755 --- a/build/package.xml +++ b/build/package.xml @@ -226,6 +226,7 @@ + diff --git a/build/replace.properties b/build/replace.properties deleted file mode 100644 index 7c5fd3de052..00000000000 --- a/build/replace.properties +++ /dev/null @@ -1,10 +0,0 @@ -DBUSER=cloud -DBPW=cloud -MSLOG=vmops.log -APISERVERLOG=api.log -DBHOST=localhost -AGENTLOGDIR=logs -AGENTLOG=logs/agent.log -MSMNTDIR=/mnt -COMPONENTS-SPEC=components-premium.xml -AWSAPILOG=awsapi.log diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index fef9f52b418..82aeb73cbcc 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -333,6 +333,7 @@ addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 +<<<<<<< HEAD ### Network Devices commands addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 @@ -364,4 +365,9 @@ listNetworkACLs=com.cloud.api.commands.ListNetworkACLsCmd;15 #### Static route commands createStaticRoute=com.cloud.api.commands.CreateStaticRouteCmd;15 deleteStaticRoute=com.cloud.api.commands.DeleteStaticRouteCmd;15 -listStaticRoutes=com.cloud.api.commands.ListStaticRoutesCmd;15 +listStaticRoutes=com.cloud.api.commands.ListStaticRoutesCmd;15 + +#### Tags commands +createTags=com.cloud.api.commands.CreateTagsCmd;15 +deleteTags=com.cloud.api.commands.DeleteTagsCmd;15 +listTags=com.cloud.api.commands.ListTagsCmd;15 diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index 8202d70e4bf..107051fe825 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -160,6 +160,10 @@ + + + + diff --git a/console-proxy/conf/log4j-cloud.xml b/console-proxy/conf/log4j-cloud.xml index 9112df7fb5a..7e455c12966 100644 --- a/console-proxy/conf/log4j-cloud.xml +++ b/console-proxy/conf/log4j-cloud.xml @@ -9,7 +9,7 @@ - + diff --git a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index dac8f23c198..72baa5105e8 100644 --- a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -1133,6 +1133,27 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return cdromVBD; } + protected void destroyPatchVbd(Connection conn, String vmName) throws XmlRpcException, XenAPIException { + try { + if( !vmName.startsWith("r-") && !vmName.startsWith("s-") && !vmName.startsWith("v-") ) { + return; + } + Set vms = VM.getByNameLabel(conn, vmName); + for ( VM vm : vms ) { + Set vbds = vm.getVBDs(conn); + for( VBD vbd : vbds ) { + if (vbd.getType(conn) == Types.VbdType.CD ) { + vbd.eject(conn); + vbd.destroy(conn); + break; + } + } + } + } catch (Exception e) { + s_logger.debug("Cannot destory CD-ROM device for VM " + vmName + " due to " + e.toString(), e); + } + } + protected CheckSshAnswer execute(CheckSshCommand cmd) { Connection conn = getConnection(); String vmName = cmd.getName(); @@ -1148,6 +1169,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (result != null) { return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); } + destroyPatchVbd(conn, vmName); } catch (Exception e) { return new CheckSshAnswer(cmd, e); } @@ -2712,7 +2734,15 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe callHostPlugin(conn, "vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); setupLinkLocalNetwork(conn); - + // try to destroy CD-ROM device for all system VMs on this host + try { + Host host = Host.getByUuid(conn, _host.uuid); + Set vms = host.getResidentVMs(conn); + for ( VM vm : vms ) { + destroyPatchVbd(conn, vm.getNameLabel(conn)); + } + } catch (Exception e) { + } try { boolean result = cleanupHaltedVms(conn); if (!result) { diff --git a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java index fd5acc94fa0..2fe18f516b2 100644 --- a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java +++ b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java @@ -39,7 +39,6 @@ import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.log4j.Logger; -import org.jnetpcap.util.resolver.Resolver.ResolverType; import com.cloud.agent.api.storage.DownloadCommand.Proxy; import com.cloud.agent.api.storage.DownloadCommand.ResourceType; diff --git a/debian/cloud-console-proxy.config b/debian/cloud-console-proxy.config deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/debian/control b/debian/control index c5c2eb85460..517366d8797 100644 --- a/debian/control +++ b/debian/control @@ -142,7 +142,7 @@ Provides: vmops-agent Conflicts: vmops-agent Replaces: vmops-agent Architecture: any -Depends: openjdk-6-jre, cloud-utils (= ${source:Version}), cloud-core (= ${source:Version}), cloud-agent-deps (= ${source:Version}), python, cloud-python (= ${source:Version}), cloud-agent-libs (= ${source:Version}), cloud-agent-scripts (= ${source:Version}), libcommons-httpclient-java, libcommons-collections-java, libcommons-dbcp-java, libcommons-pool-java, libcommons-logging-java, libvirt0, cloud-daemonize, sysvinit-utils, chkconfig, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, jnetpcap, ebtables, vlan, libcglib-java, libcommons-httpclient-java, libservlet2.5-java, liblog4j1.2-java, libjna-java, wget +Depends: openjdk-6-jre, cloud-utils (= ${source:Version}), cloud-core (= ${source:Version}), cloud-agent-deps (= ${source:Version}), python, cloud-python (= ${source:Version}), cloud-agent-libs (= ${source:Version}), cloud-agent-scripts (= ${source:Version}), libcommons-httpclient-java, libcommons-collections-java, libcommons-dbcp-java, libcommons-pool-java, libcommons-logging-java, libvirt0, cloud-daemonize, sysvinit-utils, chkconfig, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, ebtables, vlan, libcglib-java, libcommons-httpclient-java, libservlet2.5-java, liblog4j1.2-java, libjna-java, wget Description: CloudStack agent The CloudStack agent is in charge of managing shared computing resources in a CloudStack Cloud Stack-powered cloud. Install this package if this computer diff --git a/plugins/deployment-planners/user-concentrated-pod/.classpath b/plugins/deployment-planners/user-concentrated-pod/.classpath new file mode 100755 index 00000000000..e39771ada09 --- /dev/null +++ b/plugins/deployment-planners/user-concentrated-pod/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/plugins/deployment-planners/user-concentrated-pod/.project b/plugins/deployment-planners/user-concentrated-pod/.project new file mode 100755 index 00000000000..c0cec7eab2a --- /dev/null +++ b/plugins/deployment-planners/user-concentrated-pod/.project @@ -0,0 +1,17 @@ + + + user-concentrated-pod-dp + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/plugins/deployment-planners/user-concentrated-pod/build.xml b/plugins/deployment-planners/user-concentrated-pod/build.xml new file mode 100755 index 00000000000..29d4595b4a2 --- /dev/null +++ b/plugins/deployment-planners/user-concentrated-pod/build.xml @@ -0,0 +1,128 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/deploy/UserConcentratedPodPlanner.java b/plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java similarity index 100% rename from server/src/com/cloud/deploy/UserConcentratedPodPlanner.java rename to plugins/deployment-planners/user-concentrated-pod/src/com/cloud/deploy/UserConcentratedPodPlanner.java diff --git a/plugins/deployment-planners/user-dispersing/.classpath b/plugins/deployment-planners/user-dispersing/.classpath new file mode 100755 index 00000000000..e39771ada09 --- /dev/null +++ b/plugins/deployment-planners/user-dispersing/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/plugins/deployment-planners/user-dispersing/.project b/plugins/deployment-planners/user-dispersing/.project new file mode 100755 index 00000000000..d9b2d401aa8 --- /dev/null +++ b/plugins/deployment-planners/user-dispersing/.project @@ -0,0 +1,17 @@ + + + user-dispersing + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/plugins/deployment-planners/user-dispersing/.settings/org.eclipse.jdt.core.prefs b/plugins/deployment-planners/user-dispersing/.settings/org.eclipse.jdt.core.prefs new file mode 100755 index 00000000000..d0ee7df1827 --- /dev/null +++ b/plugins/deployment-planners/user-dispersing/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Tue Jun 19 15:34:37 PDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/plugins/deployment-planners/user-dispersing/build.xml b/plugins/deployment-planners/user-dispersing/build.xml new file mode 100755 index 00000000000..ba72332586a --- /dev/null +++ b/plugins/deployment-planners/user-dispersing/build.xml @@ -0,0 +1,128 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/deploy/UserDispersingPlanner.java b/plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java old mode 100644 new mode 100755 similarity index 100% rename from server/src/com/cloud/deploy/UserDispersingPlanner.java rename to plugins/deployment-planners/user-dispersing/src/com/cloud/deploy/UserDispersingPlanner.java diff --git a/plugins/host-allocators/random/.classpath b/plugins/host-allocators/random/.classpath new file mode 100755 index 00000000000..e39771ada09 --- /dev/null +++ b/plugins/host-allocators/random/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/plugins/host-allocators/random/.project b/plugins/host-allocators/random/.project new file mode 100755 index 00000000000..d33268dd646 --- /dev/null +++ b/plugins/host-allocators/random/.project @@ -0,0 +1,17 @@ + + + random-host-allocator + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/plugins/host-allocators/random/build.xml b/plugins/host-allocators/random/build.xml new file mode 100755 index 00000000000..6cb8fd8980e --- /dev/null +++ b/plugins/host-allocators/random/build.xml @@ -0,0 +1,128 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java b/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java similarity index 100% rename from server/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java rename to plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java diff --git a/ovm/.classpath b/plugins/hypervisors/ovm/.classpath old mode 100644 new mode 100755 similarity index 100% rename from ovm/.classpath rename to plugins/hypervisors/ovm/.classpath diff --git a/ovm/.project b/plugins/hypervisors/ovm/.project similarity index 95% rename from ovm/.project rename to plugins/hypervisors/ovm/.project index 4b9d34562c4..6ef55a50063 100755 --- a/ovm/.project +++ b/plugins/hypervisors/ovm/.project @@ -1,23 +1,23 @@ - - - ovm - - - - - - org.python.pydev.PyDevBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - org.python.pydev.pythonNature - - + + + ovm + + + + + + org.python.pydev.PyDevBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + org.python.pydev.pythonNature + + diff --git a/plugins/hypervisors/ovm/build.xml b/plugins/hypervisors/ovm/build.xml new file mode 100755 index 00000000000..8113d725daa --- /dev/null +++ b/plugins/hypervisors/ovm/build.xml @@ -0,0 +1,136 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ovm/scripts/vm/hypervisor/ovm/ConfigFileOps.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/ConfigFileOps.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/ConfigFileOps.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/ConfigFileOps.py diff --git a/ovm/scripts/vm/hypervisor/ovm/Fixget_storage_reposExceptionDueToWrongReturnValueCheck.patch b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/Fixget_storage_reposExceptionDueToWrongReturnValueCheck.patch old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/Fixget_storage_reposExceptionDueToWrongReturnValueCheck.patch rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/Fixget_storage_reposExceptionDueToWrongReturnValueCheck.patch diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmCommonModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmCommonModule.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmCommonModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmCommonModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmDiskModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDiskModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmDiskModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDiskModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmDispatcher.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDispatcher.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmDispatcher.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDispatcher.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmDontTouchOCFS2ClusterWhenAgentStart.patch b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDontTouchOCFS2ClusterWhenAgentStart.patch old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmDontTouchOCFS2ClusterWhenAgentStart.patch rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmDontTouchOCFS2ClusterWhenAgentStart.patch diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmFaultConstants.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmFaultConstants.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmFaultConstants.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmFaultConstants.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmHostModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmHostModule.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmHostModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmHostModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmLoggerModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmLoggerModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmLoggerModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmLoggerModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmNetworkModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmNetworkModule.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmNetworkModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmNetworkModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmObjectModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmObjectModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmObjectModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmObjectModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmPatch.patch b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmPatch.patch old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmPatch.patch rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmPatch.patch diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmSecurityGroupModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmSecurityGroupModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmSecurityGroupModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmSecurityGroupModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmStoragePoolModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmStoragePoolModule.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmStoragePoolModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmStoragePoolModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmVifModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVifModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmVifModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVifModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmVmModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVmModule.py similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmVmModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVmModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/OvmVolumeModule.py b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVolumeModule.py old mode 100644 new mode 100755 similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/OvmVolumeModule.py rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/OvmVolumeModule.py diff --git a/ovm/scripts/vm/hypervisor/ovm/configureOvm.sh b/plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/configureOvm.sh similarity index 100% rename from ovm/scripts/vm/hypervisor/ovm/configureOvm.sh rename to plugins/hypervisors/ovm/scripts/vm/hypervisor/ovm/configureOvm.sh diff --git a/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java similarity index 100% rename from ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java diff --git a/ovm/src/com/cloud/ovm/hypervisor/OvmFencer.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmFencer.java similarity index 100% rename from ovm/src/com/cloud/ovm/hypervisor/OvmFencer.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmFencer.java diff --git a/ovm/src/com/cloud/ovm/hypervisor/OvmGuru.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmGuru.java similarity index 100% rename from ovm/src/com/cloud/ovm/hypervisor/OvmGuru.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmGuru.java diff --git a/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java similarity index 100% rename from ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java diff --git a/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java similarity index 100% rename from ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java diff --git a/ovm/src/com/cloud/ovm/object/Coder.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/Coder.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java diff --git a/ovm/src/com/cloud/ovm/object/Connection.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Connection.java similarity index 100% rename from ovm/src/com/cloud/ovm/object/Connection.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/Connection.java diff --git a/ovm/src/com/cloud/ovm/object/OvmBridge.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmBridge.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java diff --git a/ovm/src/com/cloud/ovm/object/OvmDisk.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmDisk.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmDisk.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmDisk.java diff --git a/ovm/src/com/cloud/ovm/object/OvmHost.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmHost.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java diff --git a/ovm/src/com/cloud/ovm/object/OvmObject.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmObject.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmObject.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmObject.java diff --git a/ovm/src/com/cloud/ovm/object/OvmSecurityGroup.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmSecurityGroup.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmSecurityGroup.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmSecurityGroup.java diff --git a/ovm/src/com/cloud/ovm/object/OvmStoragePool.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmStoragePool.java similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmStoragePool.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmStoragePool.java diff --git a/ovm/src/com/cloud/ovm/object/OvmVif.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVif.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmVif.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVif.java diff --git a/ovm/src/com/cloud/ovm/object/OvmVlan.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVlan.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmVlan.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVlan.java diff --git a/ovm/src/com/cloud/ovm/object/OvmVm.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVm.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmVm.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVm.java diff --git a/ovm/src/com/cloud/ovm/object/OvmVolume.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVolume.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/OvmVolume.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmVolume.java diff --git a/ovm/src/com/cloud/ovm/object/Test.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Test.java old mode 100644 new mode 100755 similarity index 100% rename from ovm/src/com/cloud/ovm/object/Test.java rename to plugins/hypervisors/ovm/src/com/cloud/ovm/object/Test.java diff --git a/plugins/network-elements/f5/.classpath b/plugins/network-elements/f5/.classpath new file mode 100644 index 00000000000..a3f5d12a4c8 --- /dev/null +++ b/plugins/network-elements/f5/.classpath @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/tools/testClient/.project b/plugins/network-elements/f5/.project similarity index 67% rename from tools/testClient/.project rename to plugins/network-elements/f5/.project index c6e95d9c21b..d9cfdd7ade4 100644 --- a/tools/testClient/.project +++ b/plugins/network-elements/f5/.project @@ -1,17 +1,17 @@ - testClient + f5 - org.python.pydev.PyDevBuilder + org.eclipse.jdt.core.javabuilder - org.python.pydev.pythonNature + org.eclipse.jdt.core.javanature diff --git a/plugins/network-elements/f5/build.xml b/plugins/network-elements/f5/build.xml new file mode 100755 index 00000000000..47fcb1c6181 --- /dev/null +++ b/plugins/network-elements/f5/build.xml @@ -0,0 +1,129 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java diff --git a/server/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java diff --git a/server/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java rename to plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java diff --git a/api/src/com/cloud/api/response/F5LoadBalancerResponse.java b/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java similarity index 100% rename from api/src/com/cloud/api/response/F5LoadBalancerResponse.java rename to plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java similarity index 100% rename from server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java rename to plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java similarity index 100% rename from server/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java rename to plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java diff --git a/core/src/com/cloud/network/resource/F5BigIpResource.java b/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java similarity index 100% rename from core/src/com/cloud/network/resource/F5BigIpResource.java rename to plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java diff --git a/plugins/network-elements/juniper-srx/.classpath b/plugins/network-elements/juniper-srx/.classpath new file mode 100644 index 00000000000..a3f5d12a4c8 --- /dev/null +++ b/plugins/network-elements/juniper-srx/.classpath @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/plugins/network-elements/juniper-srx/.project b/plugins/network-elements/juniper-srx/.project new file mode 100644 index 00000000000..393b575fdff --- /dev/null +++ b/plugins/network-elements/juniper-srx/.project @@ -0,0 +1,17 @@ + + + srx + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/plugins/network-elements/juniper-srx/build.xml b/plugins/network-elements/juniper-srx/build.xml new file mode 100755 index 00000000000..7b8138a2ee2 --- /dev/null +++ b/plugins/network-elements/juniper-srx/build.xml @@ -0,0 +1,129 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/AddExternalFirewallCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java diff --git a/server/src/com/cloud/api/commands/AddSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/AddSrxFirewallCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java diff --git a/server/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java diff --git a/server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java diff --git a/server/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java diff --git a/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java diff --git a/server/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java diff --git a/server/src/com/cloud/api/commands/ListSrxFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListSrxFirewallsCmd.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java diff --git a/api/src/com/cloud/api/response/SrxFirewallResponse.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java similarity index 100% rename from api/src/com/cloud/api/response/SrxFirewallResponse.java rename to plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java similarity index 100% rename from server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java rename to plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java diff --git a/server/src/com/cloud/network/element/JuniperSRXFirewallElementService.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java similarity index 100% rename from server/src/com/cloud/network/element/JuniperSRXFirewallElementService.java rename to plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java diff --git a/core/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java similarity index 100% rename from core/src/com/cloud/network/resource/JuniperSrxResource.java rename to plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java diff --git a/plugins/network-elements/netscaler/.classpath b/plugins/network-elements/netscaler/.classpath new file mode 100644 index 00000000000..a3f5d12a4c8 --- /dev/null +++ b/plugins/network-elements/netscaler/.classpath @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/plugins/network-elements/netscaler/.project b/plugins/network-elements/netscaler/.project new file mode 100644 index 00000000000..9ec4c239847 --- /dev/null +++ b/plugins/network-elements/netscaler/.project @@ -0,0 +1,17 @@ + + + netscaler + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/plugins/network-elements/netscaler/build.xml b/plugins/network-elements/netscaler/build.xml new file mode 100755 index 00000000000..dcf8663de4b --- /dev/null +++ b/plugins/network-elements/netscaler/build.xml @@ -0,0 +1,129 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java rename to plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java rename to plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java rename to plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java diff --git a/server/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java rename to plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java diff --git a/server/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java similarity index 100% rename from server/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java rename to plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java diff --git a/api/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java similarity index 100% rename from api/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java rename to plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java diff --git a/server/src/com/cloud/network/NetScalerPodVO.java b/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java similarity index 100% rename from server/src/com/cloud/network/NetScalerPodVO.java rename to plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java diff --git a/server/src/com/cloud/network/dao/NetScalerPodDao.java b/plugins/network-elements/netscaler/src/com/cloud/network/dao/NetScalerPodDao.java similarity index 100% rename from server/src/com/cloud/network/dao/NetScalerPodDao.java rename to plugins/network-elements/netscaler/src/com/cloud/network/dao/NetScalerPodDao.java diff --git a/server/src/com/cloud/network/dao/NetScalerPodDaoImpl.java b/plugins/network-elements/netscaler/src/com/cloud/network/dao/NetScalerPodDaoImpl.java similarity index 100% rename from server/src/com/cloud/network/dao/NetScalerPodDaoImpl.java rename to plugins/network-elements/netscaler/src/com/cloud/network/dao/NetScalerPodDaoImpl.java diff --git a/server/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java similarity index 100% rename from server/src/com/cloud/network/element/NetscalerElement.java rename to plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java diff --git a/server/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java similarity index 100% rename from server/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java rename to plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java diff --git a/core/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java similarity index 100% rename from core/src/com/cloud/network/resource/NetscalerResource.java rename to plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java diff --git a/plugins/user-authenticators/ldap/.classpath b/plugins/user-authenticators/ldap/.classpath new file mode 100755 index 00000000000..e39771ada09 --- /dev/null +++ b/plugins/user-authenticators/ldap/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/plugins/user-authenticators/ldap/.project b/plugins/user-authenticators/ldap/.project new file mode 100755 index 00000000000..2f43179ec2e --- /dev/null +++ b/plugins/user-authenticators/ldap/.project @@ -0,0 +1,17 @@ + + + ldap-user-authenticator + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/server/src/com/cloud/server/auth/LDAPUserAuthenticator.java b/plugins/user-authenticators/ldap/LDAPUserAuthenticator.java similarity index 100% rename from server/src/com/cloud/server/auth/LDAPUserAuthenticator.java rename to plugins/user-authenticators/ldap/LDAPUserAuthenticator.java diff --git a/plugins/user-authenticators/ldap/build.xml b/plugins/user-authenticators/ldap/build.xml new file mode 100755 index 00000000000..c0ae8b89d18 --- /dev/null +++ b/plugins/user-authenticators/ldap/build.xml @@ -0,0 +1,128 @@ + + + + + + + Cloud Stack ant build file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/installer/createtmplt.sh b/scripts/installer/createtmplt.sh index ac208e69a66..bd539dd2fb8 100755 --- a/scripts/installer/createtmplt.sh +++ b/scripts/installer/createtmplt.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: createtmplt.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/installer/createtmplt.sh $ # createtmplt.sh -- install a template diff --git a/scripts/installer/createvolume.sh b/scripts/installer/createvolume.sh index cb36898d05b..af33b08c800 100755 --- a/scripts/installer/createvolume.sh +++ b/scripts/installer/createvolume.sh @@ -1,24 +1,23 @@ #!/usr/bin/env bash -# Copyright (C) 2011 Citrix Systems, Inc. All rights reserved -# -# This software is licensed under the GNU General Public License v3 or later. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# It is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or any later version. -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . +# http://www.apache.org/licenses/LICENSE-2.0 # +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - # $Id: createvol.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/installer/createvolume.sh $ # createvolume.sh -- install a volume diff --git a/scripts/installer/installcentos.sh b/scripts/installer/installcentos.sh index 4f368c95dcf..e68e0577a8e 100755 --- a/scripts/installer/installcentos.sh +++ b/scripts/installer/installcentos.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: installcentos.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/installer/installcentos.sh $ # set -x diff --git a/scripts/installer/installdomp.sh b/scripts/installer/installdomp.sh index 1c243c03c73..79ea9fda45c 100755 --- a/scripts/installer/installdomp.sh +++ b/scripts/installer/installdomp.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: installdomp.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/installer/installdomp.sh $ #set -x diff --git a/scripts/installer/run_installer.sh b/scripts/installer/run_installer.sh index 44f32cdb1d9..8452e3773cb 100755 --- a/scripts/installer/run_installer.sh +++ b/scripts/installer/run_installer.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: run_installer.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/installer/run_installer.sh $ installer=$1 diff --git a/scripts/network/domr/bumpUpPriority.sh b/scripts/network/domr/bumpUpPriority.sh index 78adb746e6a..3a7eaf94e4e 100755 --- a/scripts/network/domr/bumpUpPriority.sh +++ b/scripts/network/domr/bumpUpPriority.sh @@ -1,16 +1,21 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + usage() { printf "Usage:\n %s \n" $(basename $0) >&2 diff --git a/scripts/network/domr/call_firewall.sh b/scripts/network/domr/call_firewall.sh index 9130255006e..08da3411cbe 100755 --- a/scripts/network/domr/call_firewall.sh +++ b/scripts/network/domr/call_firewall.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: call_firewall.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/branches/2.0.0/java/scripts/vm/hypervisor/xenserver/patch/call_firewall.sh $ # firewall.sh -- allow some ports / protocols to vm instances usage() { diff --git a/scripts/network/domr/call_loadbalancer.sh b/scripts/network/domr/call_loadbalancer.sh index 6875f9414fe..070947cbb15 100755 --- a/scripts/network/domr/call_loadbalancer.sh +++ b/scripts/network/domr/call_loadbalancer.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: call_loadbalancer.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/branches/2.0.0/java/scripts/vm/hypervisor/xenserver/patch/call_loadbalancer.sh $ # loadbalancer.sh -- reconfigure loadbalancer rules diff --git a/scripts/network/domr/dhcp_entry.sh b/scripts/network/domr/dhcp_entry.sh index 55fc7b2dcf1..c1bf3543dfb 100755 --- a/scripts/network/domr/dhcp_entry.sh +++ b/scripts/network/domr/dhcp_entry.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: dhcp_entry.sh 9804 2010-06-22 18:36:49Z alex $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/network/domr/dhcp_entry.sh $ # dhcp_entry.sh -- add dhcp entry on domr # @VERSION@ diff --git a/scripts/network/domr/router_proxy.sh b/scripts/network/domr/router_proxy.sh index ac0c9cb8df3..bcac4120ece 100755 --- a/scripts/network/domr/router_proxy.sh +++ b/scripts/network/domr/router_proxy.sh @@ -1,16 +1,20 @@ -#!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +#!/bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/network/domr/save_password_to_domr.sh b/scripts/network/domr/save_password_to_domr.sh index 7089075f9a0..7b29472c849 100755 --- a/scripts/network/domr/save_password_to_domr.sh +++ b/scripts/network/domr/save_password_to_domr.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: save_password_to_domr.sh 9804 2010-06-22 18:36:49Z alex $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/network/domr/save_password_to_domr.sh $ # @VERSION@ diff --git a/scripts/network/domr/vm_data.sh b/scripts/network/domr/vm_data.sh index d4c815eac17..c8617234a50 100755 --- a/scripts/network/domr/vm_data.sh +++ b/scripts/network/domr/vm_data.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: vm_data.sh 9307 2010-06-08 00:43:08Z chiradeep $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/vm/hypervisor/xenserver/patch/vm_data.sh $ # @VERSION@ diff --git a/scripts/network/exdhcp/dhcpd_edithosts.py b/scripts/network/exdhcp/dhcpd_edithosts.py index 282ce8823ab..ec64f808fbb 100644 --- a/scripts/network/exdhcp/dhcpd_edithosts.py +++ b/scripts/network/exdhcp/dhcpd_edithosts.py @@ -1,20 +1,20 @@ #!/usr/bin/python -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. # Usage: dhcpd_edithosts.py mac ip hostname dns gateway nextserver diff --git a/scripts/network/exdhcp/dnsmasq_edithosts.sh b/scripts/network/exdhcp/dnsmasq_edithosts.sh index c8c3d0a509e..05285d9accf 100755 --- a/scripts/network/exdhcp/dnsmasq_edithosts.sh +++ b/scripts/network/exdhcp/dnsmasq_edithosts.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # edithosts.sh -- edit the dhcphosts file on the routing domain # $1 : the mac address # $2 : the associated ip address diff --git a/scripts/network/exdhcp/prepare_dhcpd.sh b/scripts/network/exdhcp/prepare_dhcpd.sh index 75b7dda4934..e49d0fa175b 100644 --- a/scripts/network/exdhcp/prepare_dhcpd.sh +++ b/scripts/network/exdhcp/prepare_dhcpd.sh @@ -1,21 +1,22 @@ #!/bin/sh -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # usage prepare_ping.sh subnet dhcpd_conf= diff --git a/scripts/network/exdhcp/prepare_dnsmasq.sh b/scripts/network/exdhcp/prepare_dnsmasq.sh index bc2efad04a5..70aa587e60f 100644 --- a/scripts/network/exdhcp/prepare_dnsmasq.sh +++ b/scripts/network/exdhcp/prepare_dnsmasq.sh @@ -1,20 +1,20 @@ #!/bin/sh -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. # prepare dnsmasq on external dhcp server diff --git a/scripts/network/ping/prepare_tftp_bootfile.py b/scripts/network/ping/prepare_tftp_bootfile.py index cb32dfbd610..fe9bd9bf821 100644 --- a/scripts/network/ping/prepare_tftp_bootfile.py +++ b/scripts/network/ping/prepare_tftp_bootfile.py @@ -1,21 +1,22 @@ #!/usr/bin/python -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # Usage: prepare_tftp_bootfile.py tftp_dir mac cifs_server share directory image_to_restore cifs_username cifs_password import os, sys from sys import exit diff --git a/scripts/storage/checkchildren.sh b/scripts/storage/checkchildren.sh index 2128bd5393e..55122d4f3a0 100755 --- a/scripts/storage/checkchildren.sh +++ b/scripts/storage/checkchildren.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: checkchildren.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/checkchildren.sh $ # checkchdilren.sh -- Does this path has children? diff --git a/scripts/storage/installIso.sh b/scripts/storage/installIso.sh index b43e6b89fa6..fd301bc5ca1 100755 --- a/scripts/storage/installIso.sh +++ b/scripts/storage/installIso.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: installIso.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/installIso.sh $ # installIso.sh -- install an iso diff --git a/scripts/storage/qcow2/cleanupmyvms.sh b/scripts/storage/qcow2/cleanupmyvms.sh index 34296259656..e270a01fe11 100755 --- a/scripts/storage/qcow2/cleanupmyvms.sh +++ b/scripts/storage/qcow2/cleanupmyvms.sh @@ -1,18 +1,20 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/create_private_template.sh b/scripts/storage/qcow2/create_private_template.sh index 946621f65c2..4b93380bc52 100755 --- a/scripts/storage/qcow2/create_private_template.sh +++ b/scripts/storage/qcow2/create_private_template.sh @@ -1,18 +1,20 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/createtmplt.sh b/scripts/storage/qcow2/createtmplt.sh index bc0d84fcb3d..84d2ba80b8c 100755 --- a/scripts/storage/qcow2/createtmplt.sh +++ b/scripts/storage/qcow2/createtmplt.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: createtmplt.sh 11601 2010-08-11 17:26:15Z kris $ $HeadURL: svn://svn.lab.vmops.com/repos/branches/2.1.refactor/java/scripts/storage/qcow2/createtmplt.sh $ # createtmplt.sh -- install a template diff --git a/scripts/storage/qcow2/createvm.sh b/scripts/storage/qcow2/createvm.sh index 9d855e68bfc..0971c9b9255 100755 --- a/scripts/storage/qcow2/createvm.sh +++ b/scripts/storage/qcow2/createvm.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: createvm.sh 10292 2010-07-07 00:24:04Z edison $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/createvm.sh $ # createvm.sh -- create a vm image diff --git a/scripts/storage/qcow2/createvolume.sh b/scripts/storage/qcow2/createvolume.sh index 2bc3cb29866..cfafed156f9 100755 --- a/scripts/storage/qcow2/createvolume.sh +++ b/scripts/storage/qcow2/createvolume.sh @@ -1,21 +1,20 @@ #!/usr/bin/env bash -# Copyright (C) 2011 Citrix Systems, Inc. All rights reserved -# -# This software is licensed under the GNU General Public License v3 or later. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# It is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or any later version. -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# http://www.apache.org/licenses/LICENSE-2.0 # -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - - +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/delvm.sh b/scripts/storage/qcow2/delvm.sh index 68a4a69443c..6c8341c7029 100755 --- a/scripts/storage/qcow2/delvm.sh +++ b/scripts/storage/qcow2/delvm.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: delvm.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/delvm.sh $ # delvm.sh -- delete a cloned image used for a vm diff --git a/scripts/storage/qcow2/get_domr_kernel.sh b/scripts/storage/qcow2/get_domr_kernel.sh index a5e5122a7f1..d411a568dd6 100644 --- a/scripts/storage/qcow2/get_domr_kernel.sh +++ b/scripts/storage/qcow2/get_domr_kernel.sh @@ -1,21 +1,22 @@ #/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: get_domr_kernel.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/get_domr_kernel.sh $ set -x diff --git a/scripts/storage/qcow2/get_iqn.sh b/scripts/storage/qcow2/get_iqn.sh index 41eb96743e2..c8cb4c0caf1 100755 --- a/scripts/storage/qcow2/get_iqn.sh +++ b/scripts/storage/qcow2/get_iqn.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: get_iqn.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/get_iqn.sh $ # get_iqn.sh -- return iSCSI iqn of initiator (Linux) or target (OpenSolaris) diff --git a/scripts/storage/qcow2/importmpl.sh b/scripts/storage/qcow2/importmpl.sh index 48d11eae044..4e7cdae059a 100755 --- a/scripts/storage/qcow2/importmpl.sh +++ b/scripts/storage/qcow2/importmpl.sh @@ -1,21 +1,22 @@ #!/bin/bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: importmpl.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/importmtpl.sh $ #set -x usage() { diff --git a/scripts/storage/qcow2/listvmdisk.sh b/scripts/storage/qcow2/listvmdisk.sh index a7db64e7414..40932a27022 100755 --- a/scripts/storage/qcow2/listvmdisk.sh +++ b/scripts/storage/qcow2/listvmdisk.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: listvmdisk.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/listvmdisk.sh $ # listvmdisk.sh -- list disks of a VM diff --git a/scripts/storage/qcow2/listvmdisksize.sh b/scripts/storage/qcow2/listvmdisksize.sh index 3e1c44f7cde..2082558a2fe 100755 --- a/scripts/storage/qcow2/listvmdisksize.sh +++ b/scripts/storage/qcow2/listvmdisksize.sh @@ -1,18 +1,20 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/listvmtmplt.sh b/scripts/storage/qcow2/listvmtmplt.sh index b6217e1988e..86e8903e6f4 100755 --- a/scripts/storage/qcow2/listvmtmplt.sh +++ b/scripts/storage/qcow2/listvmtmplt.sh @@ -1,18 +1,20 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/listvolume.sh b/scripts/storage/qcow2/listvolume.sh index aa5a04467b5..b951b21a1bd 100755 --- a/scripts/storage/qcow2/listvolume.sh +++ b/scripts/storage/qcow2/listvolume.sh @@ -1,21 +1,20 @@ #!/usr/bin/env bash -# Copyright (C) 2011 Citrix Systems, Inc. All rights reserved -# -# This software is licensed under the GNU General Public License v3 or later. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# It is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or any later version. -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# http://www.apache.org/licenses/LICENSE-2.0 # -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - - +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/managesnapshot.sh b/scripts/storage/qcow2/managesnapshot.sh index 273b8dc9990..a305ba83a98 100755 --- a/scripts/storage/qcow2/managesnapshot.sh +++ b/scripts/storage/qcow2/managesnapshot.sh @@ -1,18 +1,20 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/managevolume.sh b/scripts/storage/qcow2/managevolume.sh index 8f25a945cee..abf8dd62dbe 100644 --- a/scripts/storage/qcow2/managevolume.sh +++ b/scripts/storage/qcow2/managevolume.sh @@ -1,18 +1,20 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 - - +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/scripts/storage/qcow2/modifyvlan.sh b/scripts/storage/qcow2/modifyvlan.sh index a15cb196fb4..5e26af0ba02 100644 --- a/scripts/storage/qcow2/modifyvlan.sh +++ b/scripts/storage/qcow2/modifyvlan.sh @@ -1,21 +1,22 @@ #!/usr/bin/env bash -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Automatically generated by addcopyright.py at 04/03/2012 +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. - - - # $Id: modifyvlan.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/modifyvlan.sh $ # modifyvlan.sh -- adds and deletes VLANs from a Routing Server # set -x diff --git a/scripts/storage/secondary/cloud-install-sys-tmplt b/scripts/storage/secondary/cloud-install-sys-tmplt index 2f282997910..12e8ea9b59d 100755 --- a/scripts/storage/secondary/cloud-install-sys-tmplt +++ b/scripts/storage/secondary/cloud-install-sys-tmplt @@ -1,7 +1,26 @@ #!/bin/bash # $Id: installrtng.sh 11251 2010-07-23 23:40:44Z abhishek $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/secondary/installrtng.sh $ + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + usage() { - printf "Usage: %s: -m -f [-h ] [ -s ][-u ] [-F ] [-e