Return-Path: X-Original-To: apmail-cloudstack-commits-archive@www.apache.org Delivered-To: apmail-cloudstack-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id B5D31183E2 for ; Tue, 25 Aug 2015 18:49:38 +0000 (UTC) Received: (qmail 67834 invoked by uid 500); 25 Aug 2015 18:49:27 -0000 Delivered-To: apmail-cloudstack-commits-archive@cloudstack.apache.org Received: (qmail 67739 invoked by uid 500); 25 Aug 2015 18:49:27 -0000 Mailing-List: contact commits-help@cloudstack.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@cloudstack.apache.org Delivered-To: mailing list commits@cloudstack.apache.org Received: (qmail 66600 invoked by uid 99); 25 Aug 2015 18:49:27 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 25 Aug 2015 18:49:27 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 6B0FAE35D0; Tue, 25 Aug 2015 18:49:26 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: remi@apache.org To: commits@cloudstack.apache.org Date: Tue, 25 Aug 2015 18:49:46 -0000 Message-Id: <3b3371a15e4d40c98db49ece01d13b61@git.apache.org> In-Reply-To: <4dd6a75df8c6474683ffca09cf957425@git.apache.org> References: <4dd6a75df8c6474683ffca09cf957425@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [22/45] git commit: updated refs/heads/master to 44ba14d http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UriUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/com/cloud/utils/UriUtils.java deleted file mode 100644 index 631c629..0000000 --- a/utils/src/com/cloud/utils/UriUtils.java +++ /dev/null @@ -1,394 +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.utils; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; -import java.util.StringTokenizer; - -import javax.net.ssl.HttpsURLConnection; - -import org.apache.commons.httpclient.Credentials; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.auth.AuthScope; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.HeadMethod; -import org.apache.commons.httpclient.util.URIUtil; -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.client.utils.URLEncodedUtils; - -import org.apache.http.message.BasicNameValuePair; -import org.apache.log4j.Logger; - -import com.cloud.utils.crypt.DBEncryptionUtil; -import com.cloud.utils.exception.CloudRuntimeException; - -public class UriUtils { - - public static final Logger s_logger = Logger.getLogger(UriUtils.class.getName()); - - public static String formNfsUri(String host, String path) { - try { - URI uri = new URI("nfs", host, path, null); - return uri.toString(); - } catch (URISyntaxException e) { - throw new CloudRuntimeException("Unable to form nfs URI: " + host + " - " + path); - } - } - - public static String formIscsiUri(String host, String iqn, Integer lun) { - try { - String path = iqn; - if (lun != null) { - path += "/" + lun.toString(); - } - URI uri = new URI("iscsi", host, path, null); - return uri.toString(); - } catch (URISyntaxException e) { - throw new CloudRuntimeException("Unable to form iscsi URI: " + host + " - " + iqn + " - " + lun); - } - } - - public static String formFileUri(String path) { - File file = new File(path); - - return file.toURI().toString(); - } - - // a simple URI component helper (Note: it does not deal with URI paramemeter area) - public static String encodeURIComponent(String url) { - int schemeTail = url.indexOf("://"); - - int pathStart = 0; - if (schemeTail > 0) - pathStart = url.indexOf('/', schemeTail + 3); - else - pathStart = url.indexOf('/'); - - if (pathStart > 0) { - String[] tokens = url.substring(pathStart + 1).split("/"); - StringBuilder sb = new StringBuilder(url.substring(0, pathStart)); - for (String token : tokens) { - sb.append("/").append(URLEncoder.encode(token)); - } - - return sb.toString(); - } - - // no need to do URL component encoding - return url; - } - - public static String getCifsUriParametersProblems(URI uri) { - if (!UriUtils.hostAndPathPresent(uri)) { - String errMsg = "cifs URI missing host and/or path. Make sure it's of the format cifs://hostname/path"; - s_logger.warn(errMsg); - return errMsg; - } - return null; - } - - public static boolean hostAndPathPresent(URI uri) { - return !(uri.getHost() == null || uri.getHost().trim().isEmpty() || uri.getPath() == null || uri.getPath().trim().isEmpty()); - } - - public static boolean cifsCredentialsPresent(URI uri) { - List args = URLEncodedUtils.parse(uri, "UTF-8"); - boolean foundUser = false; - boolean foundPswd = false; - for (NameValuePair nvp : args) { - String name = nvp.getName(); - if (name.equals("user")) { - foundUser = true; - s_logger.debug("foundUser is" + foundUser); - } else if (name.equals("password")) { - foundPswd = true; - s_logger.debug("foundPswd is" + foundPswd); - } - } - return (foundUser && foundPswd); - } - - public static String getUpdateUri(String url, boolean encrypt) { - String updatedPath = null; - try { - String query = URIUtil.getQuery(url); - URIBuilder builder = new URIBuilder(url); - builder.removeQuery(); - - StringBuilder updatedQuery = new StringBuilder(); - List queryParams = getUserDetails(query); - ListIterator iterator = queryParams.listIterator(); - while (iterator.hasNext()) { - NameValuePair param = iterator.next(); - String value = null; - if ("password".equalsIgnoreCase(param.getName()) && - param.getValue() != null) { - value = encrypt ? DBEncryptionUtil.encrypt(param.getValue()) : DBEncryptionUtil.decrypt(param.getValue()); - } else { - value = param.getValue(); - } - - if (updatedQuery.length() == 0) { - updatedQuery.append(param.getName()).append('=') - .append(value); - } else { - updatedQuery.append('&').append(param.getName()) - .append('=').append(value); - } - } - - String schemeAndHost = ""; - URI newUri = builder.build(); - if (newUri.getScheme() != null) { - schemeAndHost = newUri.getScheme() + "://" + newUri.getHost(); - } - - updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery; - } catch (URISyntaxException e) { - throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage()); - } - - return updatedPath; - } - - private static List getUserDetails(String query) { - List details = new ArrayList(); - if (query != null && !query.isEmpty()) { - StringTokenizer allParams = new StringTokenizer(query, "&"); - while (allParams.hasMoreTokens()) { - String param = allParams.nextToken(); - details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), - param.substring(param.indexOf("=") + 1))); - } - } - - return details; - } - - // Get the size of a file from URL response header. - public static Long getRemoteSize(String url) { - Long remoteSize = (long)0; - HttpURLConnection httpConn = null; - HttpsURLConnection httpsConn = null; - try { - URI uri = new URI(url); - if (uri.getScheme().equalsIgnoreCase("http")) { - httpConn = (HttpURLConnection)uri.toURL().openConnection(); - if (httpConn != null) { - httpConn.setConnectTimeout(2000); - httpConn.setReadTimeout(5000); - String contentLength = httpConn.getHeaderField("content-length"); - if (contentLength != null) { - remoteSize = Long.parseLong(contentLength); - } - httpConn.disconnect(); - } - } else if (uri.getScheme().equalsIgnoreCase("https")) { - httpsConn = (HttpsURLConnection)uri.toURL().openConnection(); - if (httpsConn != null) { - String contentLength = httpsConn.getHeaderField("content-length"); - if (contentLength != null) { - remoteSize = Long.parseLong(contentLength); - } - httpsConn.disconnect(); - } - } - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid URL " + url); - } catch (IOException e) { - throw new IllegalArgumentException("Unable to establish connection with URL " + url); - } - return remoteSize; - } - - public static Pair validateUrl(String url) throws IllegalArgumentException { - return validateUrl(null, url); - } - - public static Pair validateUrl(String format, String url) throws IllegalArgumentException { - try { - URI uri = new URI(url); - if ((uri.getScheme() == null) || - (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { - throw new IllegalArgumentException("Unsupported scheme for url: " + url); - } - int port = uri.getPort(); - if (!(port == 80 || port == 8080 || port == 443 || port == -1)) { - throw new IllegalArgumentException("Only ports 80, 8080 and 443 are allowed"); - } - - if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) { - port = 443; - } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) { - port = 80; - } - - String host = uri.getHost(); - try { - InetAddress hostAddr = InetAddress.getByName(host); - if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { - throw new IllegalArgumentException("Illegal host specified in url"); - } - if (hostAddr instanceof Inet6Address) { - throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); - } - } catch (UnknownHostException uhe) { - throw new IllegalArgumentException("Unable to resolve " + host); - } - - // verify format - if (format != null) { - String uripath = uri.getPath(); - checkFormat(format, uripath); - } - return new Pair(host, port); - } catch (URISyntaxException use) { - throw new IllegalArgumentException("Invalid URL: " + url); - } - } - - // use http HEAD method to validate url - public static void checkUrlExistence(String url) { - if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) { - HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); - HeadMethod httphead = new HeadMethod(url); - try { - if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) { - throw new IllegalArgumentException("Invalid URL: " + url); - } - } catch (HttpException hte) { - throw new IllegalArgumentException("Cannot reach URL: " + url); - } catch (IOException ioe) { - throw new IllegalArgumentException("Cannot reach URL: " + url); - } - } - } - - // verify if a URI path is compliance with the file format given - private static void checkFormat(String format, String uripath) { - if ((!uripath.toLowerCase().endsWith("vhd")) && (!uripath.toLowerCase().endsWith("vhd.zip")) && (!uripath.toLowerCase().endsWith("vhd.bz2")) && - (!uripath.toLowerCase().endsWith("vhdx")) && (!uripath.toLowerCase().endsWith("vhdx.gz")) && - (!uripath.toLowerCase().endsWith("vhdx.bz2")) && (!uripath.toLowerCase().endsWith("vhdx.zip")) && - (!uripath.toLowerCase().endsWith("vhd.gz")) && (!uripath.toLowerCase().endsWith("qcow2")) && (!uripath.toLowerCase().endsWith("qcow2.zip")) && - (!uripath.toLowerCase().endsWith("qcow2.bz2")) && (!uripath.toLowerCase().endsWith("qcow2.gz")) && (!uripath.toLowerCase().endsWith("ova")) && - (!uripath.toLowerCase().endsWith("ova.zip")) && (!uripath.toLowerCase().endsWith("ova.bz2")) && (!uripath.toLowerCase().endsWith("ova.gz")) && - (!uripath.toLowerCase().endsWith("tar")) && (!uripath.toLowerCase().endsWith("tar.zip")) && (!uripath.toLowerCase().endsWith("tar.bz2")) && - (!uripath.toLowerCase().endsWith("tar.gz")) && (!uripath.toLowerCase().endsWith("vmdk")) && (!uripath.toLowerCase().endsWith("vmdk.gz")) && - (!uripath.toLowerCase().endsWith("vmdk.zip")) && (!uripath.toLowerCase().endsWith("vmdk.bz2")) && (!uripath.toLowerCase().endsWith("img")) && - (!uripath.toLowerCase().endsWith("img.gz")) && (!uripath.toLowerCase().endsWith("img.zip")) && (!uripath.toLowerCase().endsWith("img.bz2")) && - (!uripath.toLowerCase().endsWith("raw")) && (!uripath.toLowerCase().endsWith("raw.gz")) && (!uripath.toLowerCase().endsWith("raw.bz2")) && - (!uripath.toLowerCase().endsWith("raw.zip")) && (!uripath.toLowerCase().endsWith("iso")) && (!uripath.toLowerCase().endsWith("iso.zip")) - && (!uripath.toLowerCase().endsWith("iso.bz2")) && (!uripath.toLowerCase().endsWith("iso.gz"))) { - throw new IllegalArgumentException("Please specify a valid " + format.toLowerCase()); - } - - if ((format.equalsIgnoreCase("vhd") - && (!uripath.toLowerCase().endsWith("vhd") - && !uripath.toLowerCase().endsWith("vhd.zip") - && !uripath.toLowerCase().endsWith("vhd.bz2") - && !uripath.toLowerCase().endsWith("vhd.gz"))) - || (format.equalsIgnoreCase("vhdx") - && (!uripath.toLowerCase().endsWith("vhdx") - && !uripath.toLowerCase().endsWith("vhdx.zip") - && !uripath.toLowerCase().endsWith("vhdx.bz2") - && !uripath.toLowerCase().endsWith("vhdx.gz"))) - || (format.equalsIgnoreCase("qcow2") - && (!uripath.toLowerCase().endsWith("qcow2") - && !uripath.toLowerCase().endsWith("qcow2.zip") - && !uripath.toLowerCase().endsWith("qcow2.bz2") - && !uripath.toLowerCase().endsWith("qcow2.gz"))) - || (format.equalsIgnoreCase("ova") - && (!uripath.toLowerCase().endsWith("ova") - && !uripath.toLowerCase().endsWith("ova.zip") - && !uripath.toLowerCase().endsWith("ova.bz2") - && !uripath.toLowerCase().endsWith("ova.gz"))) - || (format.equalsIgnoreCase("tar") - && (!uripath.toLowerCase().endsWith("tar") - && !uripath.toLowerCase().endsWith("tar.zip") - && !uripath.toLowerCase().endsWith("tar.bz2") - && !uripath.toLowerCase().endsWith("tar.gz"))) - || (format.equalsIgnoreCase("raw") - && (!uripath.toLowerCase().endsWith("img") - && !uripath.toLowerCase().endsWith("img.zip") - && !uripath.toLowerCase().endsWith("img.bz2") - && !uripath.toLowerCase().endsWith("img.gz") - && !uripath.toLowerCase().endsWith("raw") - && !uripath.toLowerCase().endsWith("raw.bz2") - && !uripath.toLowerCase().endsWith("raw.zip") - && !uripath.toLowerCase().endsWith("raw.gz"))) - || (format.equalsIgnoreCase("vmdk") - && (!uripath.toLowerCase().endsWith("vmdk") - && !uripath.toLowerCase().endsWith("vmdk.zip") - && !uripath.toLowerCase().endsWith("vmdk.bz2") - && !uripath.toLowerCase().endsWith("vmdk.gz"))) - || (format.equalsIgnoreCase("iso") - && (!uripath.toLowerCase().endsWith("iso") - && !uripath.toLowerCase().endsWith("iso.zip") - && !uripath.toLowerCase().endsWith("iso.bz2") - && !uripath.toLowerCase().endsWith("iso.gz")))) { - throw new IllegalArgumentException("Please specify a valid URL. URL:" + uripath + " is an invalid for the format " + format.toLowerCase()); - } - - } - - public static InputStream getInputStreamFromUrl(String url, String user, String password) { - - try { - Pair hostAndPort = validateUrl(url); - HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager()); - if ((user != null) && (password != null)) { - httpclient.getParams().setAuthenticationPreemptive(true); - Credentials defaultcreds = new UsernamePasswordCredentials(user, password); - httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); - s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); - } - // Execute the method. - GetMethod method = new GetMethod(url); - int statusCode = httpclient.executeMethod(method); - - if (statusCode != HttpStatus.SC_OK) { - s_logger.error("Failed to read from URL: " + url); - return null; - } - - return method.getResponseBodyAsStream(); - } catch (Exception ex) { - s_logger.error("Failed to read from URL: " + url); - return null; - } - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UsernamePasswordValidator.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/UsernamePasswordValidator.java b/utils/src/com/cloud/utils/UsernamePasswordValidator.java deleted file mode 100644 index f11186c..0000000 --- a/utils/src/com/cloud/utils/UsernamePasswordValidator.java +++ /dev/null @@ -1,49 +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.utils; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class UsernamePasswordValidator { - private Pattern usernamePattern; - private Pattern passwordPattern; - private Matcher matcher; - - private static final String USERNAME_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$"; - private static final String PASSWORD_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$"; - - public UsernamePasswordValidator() { - usernamePattern = Pattern.compile(USERNAME_PATTERN); - passwordPattern = Pattern.compile(PASSWORD_PATTERN); - - } - - public boolean validateUsername(final String username) { - matcher = usernamePattern.matcher(username); - return matcher.matches(); - } - - public boolean validatePassword(final String password) { - matcher = passwordPattern.matcher(password); - return matcher.matches(); - } - -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/UuidUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/UuidUtils.java b/utils/src/com/cloud/utils/UuidUtils.java deleted file mode 100644 index 9c4a756..0000000 --- a/utils/src/com/cloud/utils/UuidUtils.java +++ /dev/null @@ -1,34 +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.utils; - -import org.apache.xerces.impl.xpath.regex.RegularExpression; - -public class UuidUtils { - - public final static String first(String uuid) { - return uuid.substring(0, uuid.indexOf('-')); - } - - public static boolean validateUUID(String uuid) { - RegularExpression regex = new RegularExpression("[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"); - return regex.matches(uuid); - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java b/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java deleted file mode 100644 index b8f3f00..0000000 --- a/utils/src/com/cloud/utils/backoff/BackoffAlgorithm.java +++ /dev/null @@ -1,38 +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.utils.backoff; - -import com.cloud.utils.component.Adapter; - -/** - * BackoffAlgorithm implements multiple BackoffAlgorithm. - */ -public interface BackoffAlgorithm extends Adapter { - - /** - */ - void waitBeforeRetry(); - - /** - * no longer need to backoff. reset to beginning. - */ - void reset(); - -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java b/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java deleted file mode 100644 index 14eae16..0000000 --- a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoff.java +++ /dev/null @@ -1,102 +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.utils.backoff.impl; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.ejb.Local; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.backoff.BackoffAlgorithm; -import com.cloud.utils.component.AdapterBase; - -/** - * An implementation of BackoffAlgorithm that waits for some seconds. - * After the time the client can try to perform the operation again. - * - * @config - * {@table - * || Param Name | Description | Values | Default || - * || seconds | seconds to sleep | integer | 5 || - * } - **/ -@Local(value = {BackoffAlgorithm.class}) -public class ConstantTimeBackoff extends AdapterBase implements BackoffAlgorithm, ConstantTimeBackoffMBean { - long _time; - private final Map _asleep = new ConcurrentHashMap(); - private final static Log LOG = LogFactory.getLog(ConstantTimeBackoff.class); - - @Override - public void waitBeforeRetry() { - Thread current = Thread.currentThread(); - try { - _asleep.put(current.getName(), current); - Thread.sleep(_time); - } catch (InterruptedException e) { - // JMX or other threads may interrupt this thread, but let's log it - // anyway, no exception to log as this is not an error - LOG.info("Thread " + current.getName() + " interrupted while waiting for retry"); - } finally { - _asleep.remove(current.getName()); - } - return; - } - - @Override - public void reset() { - } - - @Override - public boolean configure(String name, Map params) { - _time = NumbersUtil.parseLong((String)params.get("seconds"), 5) * 1000; - return true; - } - - @Override - public Collection getWaiters() { - return _asleep.keySet(); - } - - @Override - public boolean wakeup(String threadName) { - Thread th = _asleep.get(threadName); - if (th != null) { - th.interrupt(); - return true; - } - - return false; - } - - @Override - public long getTimeToWait() { - return _time; - } - - @Override - public void setTimeToWait(long seconds) { - _time = seconds * 1000; - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java b/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java deleted file mode 100644 index 4dc9f9c..0000000 --- a/utils/src/com/cloud/utils/backoff/impl/ConstantTimeBackoffMBean.java +++ /dev/null @@ -1,35 +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.utils.backoff.impl; - -import java.util.Collection; - -import com.cloud.utils.mgmt.ManagementBean; - -public interface ConstantTimeBackoffMBean extends ManagementBean { - public long getTimeToWait(); - - public void setTimeToWait(long seconds); - - Collection getWaiters(); - - boolean wakeup(String threadName); - -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java deleted file mode 100644 index a6d905d..0000000 --- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/NetconfHelper.java +++ /dev/null @@ -1,355 +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.utils.cisco.n1kv.vsm; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.trilead.ssh2.Connection; -import com.trilead.ssh2.Session; - -import com.cloud.utils.Pair; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.ssh.SSHCmdHelper; - -public class NetconfHelper { - private static final Logger s_logger = Logger.getLogger(NetconfHelper.class); - - private static final String SSH_NETCONF_TERMINATOR = "]]>]]>"; - - private Connection _connection; - - private Session _session; - - public NetconfHelper(String ip, String username, String password) throws CloudRuntimeException { - _connection = SSHCmdHelper.acquireAuthorizedConnection(ip, username, password); - if (_connection == null) { - throw new CloudRuntimeException("Error opening ssh connection."); - } - - try { - _session = _connection.openSession(); - _session.startSubSystem("xmlagent"); - exchangeHello(); - } catch (final Exception e) { - disconnect(); - s_logger.error("Failed to connect to device SSH server: " + e.getMessage()); - throw new CloudRuntimeException("Failed to connect to SSH server: " + _connection.getHostname()); - } - } - - public void disconnect() { - if (_session != null) { - _session.close(); - } - SSHCmdHelper.releaseSshConnection(_connection); - } - - public void queryStatus() throws CloudRuntimeException { - // This command is used to query the server status. - String status = - "" + "" + - " " + " " + " " + " " + " " + " " + - " " + " " + " " + " " + " " + "" + SSH_NETCONF_TERMINATOR; - send(status); - // parse the rpc reply. - parseOkReply(receive()); - } - - public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) - throws CloudRuntimeException { - String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid, vdc, espName); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for adding port profile."); - } - } - - public void addPortProfile(String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid) throws CloudRuntimeException { - String command = VsmCommand.getAddPortProfile(name, type, binding, mode, vlanid); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for adding port profile."); - } - } - - public void updatePortProfile(String name, SwitchPortMode mode, List> params) throws CloudRuntimeException { - String command = VsmCommand.getUpdatePortProfile(name, mode, params); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for updating port profile."); - } - } - - public void deletePortProfile(String name) throws CloudRuntimeException { - String command = VsmCommand.getDeletePortProfile(name); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for deleting port profile."); - } - } - - public void addPolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException { - String command = VsmCommand.getAddPolicyMap(name, averageRate, maxRate, burstRate); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for adding/updating policy map."); - } - } - - public void deletePolicyMap(String name) throws CloudRuntimeException { - String command = VsmCommand.getDeletePolicyMap(name); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for deleting policy map."); - } - } - - public void updatePolicyMap(String name, int averageRate, int maxRate, int burstRate) throws CloudRuntimeException { - // Add and update of policy map work in the exact same way. - addPolicyMap(name, averageRate, maxRate, burstRate); - } - - public void attachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException { - String command = VsmCommand.getServicePolicy(policyMap, portProfile, true); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for adding policy map."); - } - } - - public void detachServicePolicy(String policyMap, String portProfile) throws CloudRuntimeException { - String command = VsmCommand.getServicePolicy(policyMap, portProfile, false); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for removing policy map."); - } - } - - public void addVServiceNode(String vlanId, String ipAddr) throws CloudRuntimeException { - String command = VsmCommand.getVServiceNode(vlanId, ipAddr); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - parseOkReply(sendAndReceive(command)); - } else { - throw new CloudRuntimeException("Error generating rpc request for adding vservice node for vlan " + vlanId); - } - } - - public PortProfile getPortProfileByName(String name) throws CloudRuntimeException { - String command = VsmCommand.getPortProfile(name); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - String received = sendAndReceive(command); - VsmPortProfileResponse response = new VsmPortProfileResponse(received.trim()); - if (!response.isResponseOk()) { - throw new CloudRuntimeException(response.toString()); - } else { - return response.getPortProfile(); - } - } else { - throw new CloudRuntimeException("Error generating rpc request for getting port profile."); - } - } - - public PolicyMap getPolicyMapByName(String name) throws CloudRuntimeException { - String command = VsmCommand.getPolicyMap(name); - if (command != null) { - command = command.concat(SSH_NETCONF_TERMINATOR); - String received = sendAndReceive(command); - VsmPolicyMapResponse response = new VsmPolicyMapResponse(received.trim()); - if (!response.isResponseOk()) { - throw new CloudRuntimeException(response.toString()); - } else { - return response.getPolicyMap(); - } - } else { - throw new CloudRuntimeException("Error generating rpc request for getting policy map."); - } - } - - private void exchangeHello() { - String ack = receive(); - String hello = VsmCommand.getHello() + SSH_NETCONF_TERMINATOR; - send(hello); - } - - private String sendAndReceive(String command) { - String received; - synchronized (NetconfHelper.class) { - send(command); - received = receive(); - } - return received; - } - - private void send(String message) { - try { - OutputStream outputStream = _session.getStdin(); - outputStream.write(message.getBytes()); - outputStream.flush(); - } catch (Exception e) { - s_logger.error("Failed to send message: " + e.getMessage()); - throw new CloudRuntimeException("Failed to send message: " + e.getMessage()); - } - } - - private String receive() { - String response = new String(""); - InputStream inputStream = _session.getStdout(); - - try { - Delimiter delimiter = new Delimiter(); - byte[] buffer = new byte[1024]; - int count = 0; - - // Read the input stream till we find the end sequence ']]>]]>'. - while (true) { - int data = inputStream.read(); - if (data != -1) { - byte[] dataStream = delimiter.parse(data); - if (delimiter.endReached()) { - response += new String(buffer, 0, count); - break; - } - - if (dataStream != null) { - for (int i = 0; i < dataStream.length; i++) { - buffer[count] = dataStream[i]; - count++; - if (count == 1024) { - response += new String(buffer, 0, count); - count = 0; - } - } - } - } else { - break; - } - } - } catch (final Exception e) { - throw new CloudRuntimeException("Error occured while reading from the stream: " + e.getMessage()); - } - - return response; - } - - private void parseOkReply(String reply) throws CloudRuntimeException { - VsmOkResponse response = new VsmOkResponse(reply.trim()); - if (!response.isResponseOk()) { - throw new CloudRuntimeException(response.toString()); - } - } - - private static class Delimiter { - private boolean _endReached = false; - - // Used to accumulate response read while searching for end of response. - private byte[] _gatherResponse = new byte[6]; - - // Index into number of bytes read. - private int _offset = 0; - - // True if ']]>]]>' detected. - boolean endReached() { - return _endReached; - } - - // Parses the input stream and checks if end sequence is reached. - byte[] parse(int input) throws RuntimeException { - boolean collect = false; - byte[] streamRead = null; - - // Check if end sequence matched. - switch (_offset) { - case 0: - if (input == ']') { - collect = true; - } - break; - case 1: - if (input == ']') { - collect = true; - } - break; - case 2: - if (input == '>') { - collect = true; - } - break; - case 3: - if (input == ']') { - collect = true; - } - break; - case 4: - if (input == ']') { - collect = true; - } - break; - case 5: - if (input == '>') { - collect = true; - _endReached = true; - } - break; - default: - throw new RuntimeException("Invalid index value: " + _offset); - } - - if (collect) { - _gatherResponse[_offset++] = (byte)input; - } else { - // End sequence not yet reached. Return the stream of bytes collected so far. - streamRead = new byte[_offset + 1]; - for (int index = 0; index < _offset; ++index) { - streamRead[index] = _gatherResponse[index]; - } - - streamRead[_offset] = (byte)input; - _offset = 0; - } - - return streamRead; - } - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java deleted file mode 100644 index 01605d7..0000000 --- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PolicyMap.java +++ /dev/null @@ -1,34 +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.utils.cisco.n1kv.vsm; - -public class PolicyMap { - public String policyMapName; - public int committedRate; - public int burstRate; - public int peakRate; - - PolicyMap() { - policyMapName = null; - committedRate = 0; - burstRate = 0; - peakRate = 0; - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java b/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java deleted file mode 100644 index 53d9728..0000000 --- a/utils/src/com/cloud/utils/cisco/n1kv/vsm/PortProfile.java +++ /dev/null @@ -1,48 +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.utils.cisco.n1kv.vsm; - -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.BindingType; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.PortProfileType; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode; - -public class PortProfile { - public PortProfileType type; - public SwitchPortMode mode; - public BindingType binding; - public String profileName; - public String inputPolicyMap; - public String outputPolicyMap; - public String vlan; - public boolean status; - public int maxPorts; - - PortProfile() { - profileName = null; - inputPolicyMap = null; - outputPolicyMap = null; - vlan = null; - status = false; - maxPorts = 32; - type = PortProfileType.none; - mode = SwitchPortMode.none; - binding = BindingType.none; - } -}