Return-Path: X-Original-To: apmail-brooklyn-commits-archive@minotaur.apache.org Delivered-To: apmail-brooklyn-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 5D87A182B4 for ; Mon, 1 Feb 2016 17:47:40 +0000 (UTC) Received: (qmail 52857 invoked by uid 500); 1 Feb 2016 17:47:40 -0000 Delivered-To: apmail-brooklyn-commits-archive@brooklyn.apache.org Received: (qmail 52797 invoked by uid 500); 1 Feb 2016 17:47:40 -0000 Mailing-List: contact commits-help@brooklyn.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@brooklyn.apache.org Delivered-To: mailing list commits@brooklyn.apache.org Received: (qmail 51687 invoked by uid 99); 1 Feb 2016 17:47:38 -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; Mon, 01 Feb 2016 17:47:38 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id BA8B8E0994; Mon, 1 Feb 2016 17:47:38 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: heneveld@apache.org To: commits@brooklyn.apache.org Date: Mon, 01 Feb 2016 17:48:22 -0000 Message-Id: <3e186b4a7a8f4853bb17f198f107a2ce@git.apache.org> In-Reply-To: <4df94285a12940a89c0b8693de0e15c6@git.apache.org> References: <4df94285a12940a89c0b8693de0e15c6@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [46/51] [abbrv] [partial] brooklyn-library git commit: move subdir from incubator up a level as it is promoted to its own repo (first non-incubator commit!) http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/Monitor.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/Monitor.java b/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/Monitor.java deleted file mode 100644 index b5ae0e4..0000000 --- a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/Monitor.java +++ /dev/null @@ -1,260 +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 org.apache.brooklyn.qa.longevity; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.brooklyn.qa.longevity.StatusRecorder.Factory.chain; -import static org.apache.brooklyn.qa.longevity.StatusRecorder.Factory.noop; -import static org.apache.brooklyn.qa.longevity.StatusRecorder.Factory.toFile; -import static org.apache.brooklyn.qa.longevity.StatusRecorder.Factory.toLog; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import org.apache.brooklyn.util.collections.TimeWindowedList; -import org.apache.brooklyn.util.collections.TimestampedValue; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Charsets; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Range; -import com.google.common.io.Files; - -public class Monitor { - - private static final Logger LOG = LoggerFactory.getLogger(Monitor.class); - - private static final int checkPeriodMs = 1000; - - private static final OptionParser parser = new OptionParser() { - { - acceptsAll(ImmutableList.of("help", "?", "h"), "show help"); - accepts("webUrl", "Web-app url") - .withRequiredArg().ofType(URL.class); - accepts("brooklynPid", "Brooklyn pid") - .withRequiredArg().ofType(Integer.class); - accepts("logFile", "Brooklyn log file") - .withRequiredArg().ofType(File.class); - accepts("logGrep", "Grep in log file (defaults to 'SEVERE|ERROR|WARN|Exception|Error'") - .withRequiredArg().ofType(String.class); - accepts("logGrepExclusionsFile", "File of expressions to be ignored in log file") - .withRequiredArg().ofType(File.class); - accepts("webProcesses", "Name (for `ps ax | grep` of web-processes") - .withRequiredArg().ofType(String.class); - accepts("numWebProcesses", "Number of web-processes expected (e.g. 1 or 1-3)") - .withRequiredArg().ofType(String.class); - accepts("webProcessesCyclingPeriod", "The period (in seconds) for cycling through the range of numWebProcesses") - .withRequiredArg().ofType(Integer.class); - accepts("outFile", "File to write monitor status info") - .withRequiredArg().ofType(File.class); - accepts("abortOnError", "Exit the JVM on error, with exit code 1") - .withRequiredArg().ofType(Boolean.class); - } - }; - - public static void main(String[] argv) throws InterruptedException, IOException { - OptionSet options = parse(argv); - - if (options == null || options.has("help")) { - parser.printHelpOn(System.out); - System.exit(0); - } - - MonitorPrefs prefs = new MonitorPrefs(); - prefs.webUrl = options.hasArgument("webUrl") ? (URL) options.valueOf("webUrl") : null; - prefs.brooklynPid = options.hasArgument("brooklynPid") ? (Integer) options.valueOf("brooklynPid") : -1; - prefs.logFile = options.hasArgument("logFile") ? (File) options.valueOf("logFile") : null; - prefs.logGrep = options.hasArgument("logGrep") ? (String) options.valueOf("logGrep") : "SEVERE|ERROR|WARN|Exception|Error"; - prefs.logGrepExclusionsFile = options.hasArgument("logGrepExclusionsFile") ? (File) options.valueOf("logGrepExclusionsFile") : null; - prefs.webProcessesRegex = options.hasArgument("webProcesses") ? (String) options.valueOf("webProcesses") : null; - prefs.numWebProcesses = options.hasArgument("numWebProcesses") ? parseRange((String) options.valueOf("numWebProcesses")) : null; - prefs.webProcessesCyclingPeriod = options.hasArgument("webProcessesCyclingPeriod") ? (Integer) options.valueOf("webProcessesCyclingPeriod") : -1; - prefs.outFile = options.hasArgument("outFile") ? (File) options.valueOf("outFile") : null; - prefs.abortOnError = options.hasArgument("abortOnError") ? (Boolean) options.valueOf("abortOnError") : false; - Monitor main = new Monitor(prefs, MonitorListener.NOOP); - main.start(); - } - - private static Range parseRange(String range) { - if (range.contains("-")) { - String[] parts = range.split("-"); - return Range.closed(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); - } else { - return Range.singleton(Integer.parseInt(range)); - } - } - - private static OptionSet parse(String...argv) { - try { - return parser.parse(argv); - } catch (Exception e) { - System.out.println("Error in parsing options: " + e.getMessage()); - return null; - } - } - - private final MonitorPrefs prefs; - private final StatusRecorder recorder; - private final MonitorListener listener; - - public Monitor(MonitorPrefs prefs, MonitorListener listener) { - this.prefs = prefs; - this.listener = listener; - this.recorder = chain(toLog(LOG), (prefs.outFile != null ? toFile(prefs.outFile) : noop())); - } - - private void start() throws IOException { - LOG.info("Monitoring: "+prefs); - ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - - final AtomicReference> previousLogLines = new AtomicReference>(Collections.emptyList()); - final TimeWindowedList numWebProcessesHistory = new TimeWindowedList( - ImmutableMap.of("timePeriod", Duration.seconds(prefs.webProcessesCyclingPeriod), "minExpiredVals", 1)); - final Set logGrepExclusions = ImmutableSet.copyOf(Files.readLines(prefs.logGrepExclusionsFile, Charsets.UTF_8)); - - executor.scheduleAtFixedRate(new Runnable() { - @Override public void run() { - StatusRecorder.Record record = new StatusRecorder.Record(); - StringBuilder failureMsg = new StringBuilder(); - try { - if (prefs.brooklynPid > 0) { - boolean pidRunning = MonitorUtils.isPidRunning(prefs.brooklynPid, "java"); - MonitorUtils.MemoryUsage memoryUsage = MonitorUtils.getMemoryUsage(prefs.brooklynPid, ".*brooklyn.*", 1000); - record.put("pidRunning", pidRunning); - record.put("totalMemoryBytes", memoryUsage.getTotalMemoryBytes()); - record.put("totalMemoryInstances", memoryUsage.getTotalInstances()); - record.put("instanceCounts", memoryUsage.getInstanceCounts()); - - if (!pidRunning) { - failureMsg.append("pid "+prefs.brooklynPid+" is not running"+"\n"); - } - } - if (prefs.webUrl != null) { - boolean webUrlUp = MonitorUtils.isUrlUp(prefs.webUrl); - record.put("webUrlUp", webUrlUp); - - if (!webUrlUp) { - failureMsg.append("web URL "+prefs.webUrl+" is not available"+"\n"); - } - } - if (prefs.logFile != null) { - List logLines = MonitorUtils.searchLog(prefs.logFile, prefs.logGrep, logGrepExclusions); - List newLogLines = getAdditions(previousLogLines.get(), logLines); - previousLogLines.set(logLines); - record.put("logLines", newLogLines); - - if (newLogLines.size() > 0) { - failureMsg.append("Log contains warnings/errors: "+newLogLines+"\n"); - } - } - if (prefs.webProcessesRegex != null) { - List pids = MonitorUtils.getRunningPids(prefs.webProcessesRegex, "--webProcesses"); - pids.remove((Object)MonitorUtils.findOwnPid()); - - record.put("webPids", pids); - record.put("numWebPids", pids.size()); - numWebProcessesHistory.add(pids.size()); - - if (prefs.numWebProcesses != null) { - boolean numWebPidsInRange = prefs.numWebProcesses.apply(pids.size()); - record.put("numWebPidsInRange", numWebPidsInRange); - - if (!numWebPidsInRange) { - failureMsg.append("num web processes out-of-range: pids="+pids+"; size="+pids.size()+"; expected="+prefs.numWebProcesses); - } - - if (prefs.webProcessesCyclingPeriod > 0) { - List> values = numWebProcessesHistory.getValues(); - long valuesTimeRange = (values.get(values.size()-1).getTimestamp() - values.get(0).getTimestamp()); - if (values.size() > 0 && valuesTimeRange > SECONDS.toMillis(prefs.webProcessesCyclingPeriod)) { - int min = -1; - int max = -1; - for (TimestampedValue val : values) { - min = (min < 0) ? val.getValue() : Math.min(val.getValue(), min); - max = Math.max(val.getValue(), max); - } - record.put("minWebSizeInPeriod", min); - record.put("maxWebSizeInPeriod", max); - - if (min > prefs.numWebProcesses.lowerEndpoint() || max < prefs.numWebProcesses.upperEndpoint()) { - failureMsg.append("num web processes not increasing/decreasing correctly: " + - "pids="+pids+"; size="+pids.size()+"; cyclePeriod="+prefs.webProcessesCyclingPeriod+ - "; expectedRange="+prefs.numWebProcesses+"; min="+min+"; max="+max+"; history="+values); - } - } else { - int numVals = values.size(); - long startTime = (numVals > 0) ? values.get(0).getTimestamp() : 0; - long endTime = (numVals > 0) ? values.get(values.size()-1).getTimestamp() : 0; - LOG.info("Insufficient vals in time-window to determine cycling behaviour over period ("+prefs.webProcessesCyclingPeriod+"secs): "+ - "numVals="+numVals+"; startTime="+startTime+"; endTime="+endTime+"; periodCovered="+(endTime-startTime)/1000); - } - } - } - } - - } catch (Throwable t) { - LOG.error("Error during periodic checks", t); - throw Throwables.propagate(t); - } - - try { - recorder.record(record); - listener.onRecord(record); - - if (failureMsg.length() > 0) { - listener.onFailure(record, failureMsg.toString()); - - if (prefs.abortOnError) { - LOG.error("Aborting on error: "+failureMsg); - System.exit(1); - } - } - - } catch (Throwable t) { - LOG.warn("Error recording monitor info ("+record+")", t); - throw Throwables.propagate(t); - } - } - }, 0, checkPeriodMs, TimeUnit.MILLISECONDS); - } - - // TODO What is the guava equivalent? Don't want Set.difference, because duplicates/ordered. - private static List getAdditions(List prev, List next) { - List result = Lists.newArrayList(next); - result.removeAll(prev); - return result; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorListener.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorListener.java b/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorListener.java deleted file mode 100644 index 11fdd3f..0000000 --- a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorListener.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 org.apache.brooklyn.qa.longevity; - -import org.apache.brooklyn.qa.longevity.StatusRecorder.Record; - -public interface MonitorListener { - - public static final MonitorListener NOOP = new MonitorListener() { - @Override public void onRecord(Record record) { - } - @Override public void onFailure(Record record, String msg) { - } - }; - - public void onRecord(Record record); - - public void onFailure(Record record, String msg); -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorPrefs.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorPrefs.java b/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorPrefs.java deleted file mode 100644 index 4d74045..0000000 --- a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorPrefs.java +++ /dev/null @@ -1,54 +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 org.apache.brooklyn.qa.longevity; - -import java.io.File; -import java.net.URL; - -import com.google.common.base.Objects; -import com.google.common.collect.Range; - -public class MonitorPrefs { - - public URL webUrl; - public int brooklynPid; - public File logFile; - public String logGrep; - public File logGrepExclusionsFile; - public String webProcessesRegex; - public Range numWebProcesses; - public int webProcessesCyclingPeriod; - public File outFile; - public boolean abortOnError; - - @Override - public String toString() { - return Objects.toStringHelper(this) - .add("webUrl", webUrl) - .add("brooklynPid", brooklynPid) - .add("logFile", logFile) - .add("logGrep", logGrep) - .add("logGrepExclusionsFile", logGrepExclusionsFile) - .add("outFile", outFile) - .add("webProcessesRegex", webProcessesRegex) - .add("numWebProcesses", numWebProcesses) - .add("webProcessesCyclingPeriod", webProcessesCyclingPeriod) - .toString(); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorUtils.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorUtils.java b/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorUtils.java deleted file mode 100644 index c9ce875..0000000 --- a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/MonitorUtils.java +++ /dev/null @@ -1,328 +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 org.apache.brooklyn.qa.longevity; - -import static com.google.common.base.Strings.isNullOrEmpty; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.brooklyn.util.http.HttpTool; -import org.apache.brooklyn.util.http.HttpToolResponse; -import org.apache.brooklyn.util.stream.StreamGobbler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Objects; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.io.ByteStreams; - -public class MonitorUtils { - - private static final Logger LOG = LoggerFactory.getLogger(MonitorUtils.class); - - private static volatile int ownPid = -1; - - /** - * Confirm can read from URL. - * - * @param url - */ - public static boolean isUrlUp(URL url) { - try { - HttpToolResponse result = HttpTool.httpGet( - HttpTool.httpClientBuilder().trustAll().build(), - URI.create(url.toString()), - ImmutableMap.of()); - int statuscode = result.getResponseCode(); - - if (statuscode != 200) { - LOG.info("Error reading URL {}: {}, {}", new Object[]{url, statuscode, result.getReasonPhrase()}); - return false; - } else { - return true; - } - } catch (Exception e) { - LOG.info("Error reading URL {}: {}", url, e); - return false; - } - } - - public static boolean isPidRunning(int pid) { - return isPidRunning(pid, null); - } - - /** - * Confirm the given pid is running, and that the the process matches the given regex. - * - * @param pid - * @param regex - */ - public static boolean isPidRunning(int pid, String regex) { - Process process = exec("ps -p " + pid); - String out = waitFor(process); - if (process.exitValue() > 0) { - String err = toString(process.getErrorStream()); - LOG.info(String.format("pid %s not running: %s", pid, err)); - return false; - } - - if (regex != null) { - String regex2 = "^\\s*" + pid + ".*" + regex; - boolean found = false; - for (String line : out.split("\n")) { - if (hasAtLeastOneMatch(line, regex2)) { - found = true; - break; - } - } - - if (!found) { - String txt = toString(process.getInputStream()); - LOG.info("process did not match regular expression: "+txt); - return false; - } - } - - return true; - } - - private static boolean hasAtLeastOneMatch(String line, String regex) { - return Pattern.matches(".*"+regex+".*", line); - } - - private static String toString(InputStream in){ - try { - byte[] bytes = ByteStreams.toByteArray(in); - return new String(bytes); - } catch (IOException e) { - throw Throwables.propagate(e); - } - - } - - public static List getRunningPids(String regex) { - return getRunningPids(regex, null); - } - - /** - * Confirm the given pid is running, and that the the process matches the given regex. - * - * @param regex - * @param excludingRegex - */ - public static List getRunningPids(String regex, String excludingRegex) { - Process process = exec("ps ax"); - String out = waitFor(process); - - List result = new LinkedList(); - for (String line : out.split("\n")) { - if (excludingRegex != null && hasAtLeastOneMatch(line, excludingRegex)) { - continue; - } - if (hasAtLeastOneMatch(line, regex)) { - String[] linesplit = line.trim().split("\\s+"); - result.add(Integer.parseInt(linesplit[0])); - } - } - return result; - } - - public static MemoryUsage getMemoryUsage(int pid){ - return getMemoryUsage(pid, null,0); - } - - /** - * @param pid - */ - public static MemoryUsage getMemoryUsage(int pid, String clazzRegexOfInterest, int minInstancesOfInterest) { - Process process = exec(String.format("jmap -histo %s", pid)); - String out = waitFor(process); - - Map instanceCounts = Maps.newLinkedHashMap(); - long totalInstances=0; - long totalMemoryBytes=0; - - for (String line : out.split("\n")) { - if (clazzRegexOfInterest!=null && hasAtLeastOneMatch(line, clazzRegexOfInterest)) { - // Format is: - // num #instances #bytes class name - // 1: 43506 8047096 example.MyClazz - - String[] parts = line.trim().split("\\s+"); - String clazz = parts[3]; - int instanceCount = Integer.parseInt(parts[1]); - if (instanceCount >= minInstancesOfInterest) { - instanceCounts.put(clazz, instanceCount); - } - } - if (hasAtLeastOneMatch(line, "^Total.*")) { - String[] parts = line.split("\\s+"); - totalInstances = Long.parseLong(parts[1]); - totalMemoryBytes = Long.parseLong(parts[2]); - } - } - - return new MemoryUsage(totalInstances, totalMemoryBytes, instanceCounts); - } - - public static class MemoryUsage { - final long totalInstances; - final long totalMemoryBytes; - final Map instanceCounts; - - MemoryUsage(long totalInstances, long totalMemoryBytes, Map instanceCounts) { - this.totalInstances = totalInstances; - this.totalMemoryBytes = totalMemoryBytes; - this.instanceCounts = instanceCounts; - } - - public String toString() { - return Objects.toStringHelper(this) - .add("totalInstances", totalInstances) - .add("totalMemoryBytes", totalMemoryBytes) - .add("instanceCounts", instanceCounts) - .toString(); - } - - public long getTotalInstances() { - return totalInstances; - } - - public long getTotalMemoryBytes() { - return totalMemoryBytes; - } - - public Map getInstanceCounts() { - return instanceCounts; - } - } - - public static List searchLog(File file, String grepOfInterest) { - return searchLog(file, grepOfInterest, new LinkedHashSet()); - } - - /** - * Find lines in the given file that match given given regex. - * - * @param file - * @param grepOfInterest - */ - public static List searchLog(File file, String grepOfInterest, Set grepExclusions) { - Process process = exec(String.format("grep -E %s %s", grepOfInterest, file.getAbsoluteFile())); - String out = waitFor(process); - - // TODO Annoying that String.split() returns size 1 when empty string; lookup javadoc when back online... - if (out.length() == 0) return Collections.emptyList(); - - List result = new ArrayList(); - for (String line : out.trim().split("\n")) { - boolean excluded = false; - for (String exclusion : grepExclusions) { - if (!isNullOrEmpty(exclusion) && hasAtLeastOneMatch(line, exclusion)) { - excluded = true; - } - } - if (!excluded) { - result.add(line); - } - } - return result; - } - - public static Process exec(String cmd) { - LOG.info("executing cmd: " + cmd); - - try { - return Runtime.getRuntime().exec(cmd); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - - public static class ProcessHasStderr extends IllegalStateException { - private static final long serialVersionUID = -937871002993888405L; - - byte[] stderrBytes; - public ProcessHasStderr(byte[] stderrBytes) { - this("Process printed to stderr: " + new String(stderrBytes), stderrBytes); - } - public ProcessHasStderr(String message, byte[] stderrBytes) { - super(message); - this.stderrBytes = stderrBytes; - } - } - - /** - * Waits for the given process to complete, consuming its stdout and returning it as a string. - * If there is any output on stderr an exception will be thrown. - */ - public static String waitFor(Process process) { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - @SuppressWarnings("resource") //Closeable doesn't seem appropriate for StreamGobbler since it isn't expected to be called every time - StreamGobbler gobblerOut = new StreamGobbler(process.getInputStream(), bytesOut, null); - gobblerOut.start(); - - ByteArrayOutputStream bytesErr = new ByteArrayOutputStream(); - @SuppressWarnings("resource") - StreamGobbler gobblerErr = new StreamGobbler(process.getErrorStream(), bytesErr, null); - gobblerErr.start(); - - try { - process.waitFor(); - gobblerOut.blockUntilFinished(); - gobblerErr.blockUntilFinished(); - - if (bytesErr.size() > 0) { - throw new ProcessHasStderr(bytesErr.toByteArray()); - } - - return new String(bytesOut.toByteArray()); - } catch (Exception e) { - throw Throwables.propagate(e); - } finally { - if (gobblerOut.isAlive()) gobblerOut.interrupt(); - if (gobblerErr.isAlive()) gobblerErr.interrupt(); - } - } - - public static int findOwnPid() throws IOException { - if (ownPid >= 0) return ownPid; - - String[] cmd = new String[]{"bash", "-c", "echo $PPID"}; - Process process = Runtime.getRuntime().exec(cmd); - String out = MonitorUtils.waitFor(process); - ownPid = Integer.parseInt(out.trim()); - return ownPid; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/StatusRecorder.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/StatusRecorder.java b/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/StatusRecorder.java deleted file mode 100644 index 210e0a2..0000000 --- a/brooklyn-library/qa/src/main/java/org/apache/brooklyn/qa/longevity/StatusRecorder.java +++ /dev/null @@ -1,130 +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 org.apache.brooklyn.qa.longevity; - -import java.io.File; -import java.io.IOException; -import java.util.Map; - -import org.slf4j.Logger; - -import com.google.common.base.Charsets; -import com.google.common.collect.Maps; -import com.google.common.io.Files; - -public interface StatusRecorder { - - public void record(Record record) throws IOException; - - public static class Factory { - public static final StatusRecorder NOOP = new StatusRecorder() { - @Override public void record(Record record) {} - }; - - public static StatusRecorder noop() { - return NOOP; - } - public static StatusRecorder toFile(File outFile) { - return new FileBasedStatusRecorder(outFile); - } - public static StatusRecorder toSysout() { - return new SysoutBasedStatusRecorder(); - } - public static StatusRecorder toLog(Logger log) { - return new LogBasedStatusRecorder(log); - } - public static StatusRecorder chain(StatusRecorder...recorders) { - return new ChainingStatusRecorder(recorders); - } - } - - public static class Record { - private final Map fields = Maps.newLinkedHashMap(); - - public void putAll(Map entries) { - fields.putAll(entries); - } - - public void putAll(String keyPrefix, Map entries) { - for (Map.Entry entry : entries.entrySet()) { - fields.put(keyPrefix+entry.getKey(), entry.getValue()); - } - } - - public void put(String key, Object val) { - fields.put(key, val); - } - - @Override - public String toString() { - return fields.toString(); - } - } - - public static class FileBasedStatusRecorder implements StatusRecorder { - private final File outFile; - - public FileBasedStatusRecorder(File outFile) { - this.outFile = outFile; - } - - @Override - public void record(Record record) throws IOException { - Files.append(record.fields.toString()+"\n", outFile, Charsets.UTF_8); - } - } - - public static class SysoutBasedStatusRecorder implements StatusRecorder { - public SysoutBasedStatusRecorder() { - } - - @Override - public void record(Record record) { - System.out.println(record.fields); - } - } - - public static class LogBasedStatusRecorder implements StatusRecorder { - private final Logger log; - - public LogBasedStatusRecorder(Logger log) { - this.log = log; - } - - @Override - public void record(Record record) { - log.info("{}", record.fields); - } - } - - public static class ChainingStatusRecorder implements StatusRecorder { - private final StatusRecorder[] recorders; - - public ChainingStatusRecorder(StatusRecorder... recorders) { - this.recorders = recorders; - } - - @Override - public void record(Record record) throws IOException { - for (StatusRecorder recorder : recorders) { - recorder.record(record); - } - } - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/resources/hello-world.txt ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/resources/hello-world.txt b/brooklyn-library/qa/src/main/resources/hello-world.txt deleted file mode 100644 index ac2e350..0000000 --- a/brooklyn-library/qa/src/main/resources/hello-world.txt +++ /dev/null @@ -1,24 +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. - -The file hello-world.war contains its source code. - -It is the same as core/src/test/resources/hello-world-no-mapping.war, but is included here -as a (small) binary to prevent build complication and leakage of test dependencies. This -QA module contains useful building blocks for downstream projects/customers doing -performance and longevity testing, rather than it just being for the Brooklyn automated build. - http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/main/resources/hello-world.war ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/main/resources/hello-world.war b/brooklyn-library/qa/src/main/resources/hello-world.war deleted file mode 100644 index 0e17460..0000000 Binary files a/brooklyn-library/qa/src/main/resources/hello-world.war and /dev/null differ http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java deleted file mode 100644 index 9f351ce..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/brooklynnode/SoftlayerObtainPrivateLiveTest.java +++ /dev/null @@ -1,225 +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 org.apache.brooklyn.qa.brooklynnode; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.core.entity.lifecycle.ServiceStateLogic; -import org.apache.brooklyn.core.objs.BrooklynObjectInternal.ConfigurationSupportInternal; -import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirror; -import org.apache.brooklyn.entity.brooklynnode.BrooklynNode; -import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector; -import org.apache.brooklyn.entity.machine.MachineEntity; -import org.apache.brooklyn.launcher.BrooklynLauncher; -import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.BrooklynMavenArtifacts; -import org.apache.brooklyn.util.maven.MavenRetriever; -import org.apache.brooklyn.util.text.Strings; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Joiner; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -/** - * Tests obtaining a machine with a private IP only. For the machine to be - * accessible we should have a gateway machine already running in the same - * network. - * - * Starts a BrooklynNode with a public IP and on it starts two machines - - * one with public and one with private only IP. - * - * The test lives here so it has access to the dist archive. - */ -public class SoftlayerObtainPrivateLiveTest { - - // Expects that the location is already configured in brooklyn.properties - private static final String LOCATION_SPEC = "jclouds:aws-ec2"; - - - private static final Logger log = LoggerFactory.getLogger(SoftlayerObtainPrivateLiveTest.class); - - private static final ImmutableMap TIMEOUT = ImmutableMap.of("timeout", Duration.ONE_HOUR); - // Should this be a black list instead? - private Set LOCATION_CONFIG_WHITE_LIST = ImmutableSet.of( - JcloudsLocationConfig.CLOUD_REGION_ID.getName(), - JcloudsLocationConfig.ACCESS_IDENTITY.getName(), - JcloudsLocationConfig.ACCESS_CREDENTIAL.getName(), - JcloudsLocationConfig.IMAGE_ID.getName(), - JcloudsLocationConfig.HARDWARE_ID.getName(), - JcloudsLocationConfig.TEMPLATE_OPTIONS.getName()); - - private static final String NAMED_LOCATION_PREFIX = "brooklyn.location.named."; - private static final String TEST_LOCATION = "test-location"; - private static final String TEST_LOCATION_PRIVATE = TEST_LOCATION + "-private"; - private static final String TEST_LOCATION_PUBLIC = TEST_LOCATION + "-public"; - - private BrooklynLauncher launcher; - private ManagementContext mgmt; - private TestApplication app; - private Location loc; - - @BeforeMethod(alwaysRun=true) - public void setUp() { - mgmt = LocalManagementContextForTests.builder(true) - .useDefaultProperties() - .build(); - launcher = BrooklynLauncher - .newInstance() - .managementContext(mgmt) - .start(); - app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class)); - mgmt.getEntityManager().manage(app); - loc = createLocation(); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() { - Entities.destroyAll(mgmt); - launcher.terminate(); - } - - private Location createLocation() { - return mgmt.getLocationRegistry().resolve(LOCATION_SPEC); - } - - @Test(groups="Live") - public void testObtain() { - String localUrl = MavenRetriever.localUrl(BrooklynMavenArtifacts.artifact("", "brooklyn-dist", "tar.gz", "dist")); - String userName = "admin"; - String userPassword = Strings.makeRandomId(6); - String remoteConfig = Joiner.on('\n').join(MutableList.of( - "brooklyn.webconsole.security.users=" + userName, - "brooklyn.webconsole.security.user.admin.password=" + userPassword) - .appendAll(getLocationConfig()) - .append("\n")); - - log.info("Using distribution {}", localUrl); - log.info("Remote credentials are {}:{}", userName, userPassword); - log.info("Remote config \n{}", remoteConfig); - - EntitySpec nodeSpec = EntitySpec.create(BrooklynNode.class) - .configure(BrooklynNode.DISTRO_UPLOAD_URL, localUrl) - .configure(BrooklynNode.MANAGEMENT_USER, userName) - .configure(BrooklynNode.MANAGEMENT_PASSWORD, userPassword) - .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, remoteConfig); - - BrooklynNode node = app.createAndManageChild(nodeSpec); - app.start(ImmutableList.of(loc)); - try { - // TODO Assumes that the second-level machines will be in the same private network as the BrooklynNode machine. - // The private network id can be set explicitly in templateOptions.primaryBackendNetworkComponentNetworkVlanId. - BrooklynEntityMirror publicApp = deployTestApp(node, true); - BrooklynEntityMirror privateApp = deployTestApp(node, false); - - EntityTestUtils.assertAttributeEventually(TIMEOUT, publicApp, ServiceStateLogic.SERVICE_STATE_ACTUAL, - Predicates.in(ImmutableList.of(Lifecycle.RUNNING, Lifecycle.ON_FIRE))); - EntityTestUtils.assertAttributeEventually(TIMEOUT, privateApp, ServiceStateLogic.SERVICE_STATE_ACTUAL, - Predicates.in(ImmutableList.of(Lifecycle.RUNNING, Lifecycle.ON_FIRE))); - - EntityTestUtils.assertAttributeEquals(publicApp, ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); - EntityTestUtils.assertAttributeEquals(privateApp, ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); - - EntityTestUtils.assertAttributeEqualsEventually(publicApp, Attributes.SERVICE_UP, Boolean.TRUE); - EntityTestUtils.assertAttributeEqualsEventually(privateApp, Attributes.SERVICE_UP, Boolean.TRUE); - } finally { - node.invoke(BrooklynNode.STOP_NODE_AND_KILL_APPS, ImmutableMap.of()).getUnchecked(); - } - } - - private BrooklynEntityMirror deployTestApp(BrooklynNode node, boolean hasPublicNetwork) { - String entityId = node.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ImmutableMap.of(DeployBlueprintEffector.BLUEPRINT_CAMP_PLAN.getName(), getBlueprintPlan(hasPublicNetwork))).getUnchecked(); - return node.addChild(EntitySpec.create(BrooklynEntityMirror.class) - .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, entityId) - .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, node.getAttribute(BrooklynNode.WEB_CONSOLE_URI).toString() + "/v1/applications/"+entityId+"/entities/"+entityId)); - } - - private Collection getLocationConfig() { - Map config = MutableMap.copyOf(((ConfigurationSupportInternal)loc.config()).getBag().getAllConfig()); - config.putAll(customizeSharedLocation()); - return MutableList.of() - .appendAll(createLocationConfig(NAMED_LOCATION_PREFIX + TEST_LOCATION, (String)config.get("spec.original"), config)) - .appendAll(createLocationConfig(NAMED_LOCATION_PREFIX + TEST_LOCATION_PUBLIC, "named:" + TEST_LOCATION, customizePublicLocation())) - .appendAll(createLocationConfig(NAMED_LOCATION_PREFIX + TEST_LOCATION_PRIVATE, "named:" + TEST_LOCATION, customizePrivateLocation())); - } - - private Collection createLocationConfig(String prefix, String parent, Map config) { - return MutableList.of() - .append(prefix + "=" + parent) - .appendAll(locationConfigToProperties(prefix, config)); - } - - protected Collection locationConfigToProperties(String prefix, Map config) { - Collection loc = new ArrayList(); - for (String key : config.keySet()) { - if (LOCATION_CONFIG_WHITE_LIST.contains(key)) { - loc.add(prefix + "." + key + "=" + config.get(key)); - } - } - return loc; - } - - protected Map customizeSharedLocation() { - return ImmutableMap.of(); - } - - protected Map customizePublicLocation() { - return ImmutableMap.of(); - } - - protected Map customizePrivateLocation() { - return ImmutableMap.of( - "templateOptions", "{privateNetworkOnlyFlag: true}"); - } - - protected String getBlueprintPlan(boolean hasPublicNetwork) { - return Joiner.on('\n').join(ImmutableList.of( - "location: " + getTestLocation(hasPublicNetwork), - "services:", - "- type: "+MachineEntity.class.getName(), - " name: " + (hasPublicNetwork ? "Public" : "Private") - )); - } - - private static String getTestLocation(boolean hasPublicNetwork) { - return hasPublicNetwork ? TEST_LOCATION_PUBLIC : TEST_LOCATION_PRIVATE; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EnrichersSlightlySimplerYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EnrichersSlightlySimplerYamlTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EnrichersSlightlySimplerYamlTest.java deleted file mode 100644 index c24ead1..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EnrichersSlightlySimplerYamlTest.java +++ /dev/null @@ -1,134 +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 org.apache.brooklyn.qa.camp; - -import java.net.URI; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.camp.brooklyn.AbstractYamlTest; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityInternal; -import org.apache.brooklyn.core.sensor.Sensors; -import org.apache.brooklyn.entity.group.DynamicCluster; -import org.apache.brooklyn.entity.webapp.JavaWebAppSoftwareProcess; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.CollectionFunctionals; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.math.MathPredicates; -import org.apache.brooklyn.util.text.StringPredicates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - -/** Tests some improvements to enricher classes to make them a bit more yaml friendly. - * Called "SlightlySimpler" as it would be nice to make enrichers a lot more yaml friendly! */ -@Test -public class EnrichersSlightlySimplerYamlTest extends AbstractYamlTest { - private static final Logger log = LoggerFactory.getLogger(EnrichersSlightlySimplerYamlTest.class); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testWithAppEnricher() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-app-with-enrichers-slightly-simpler.yaml")); - waitForApplicationTasks(app); - log.info("Started "+app+":"); - Entities.dumpInfo(app); - - Entity cluster = Iterables.getOnlyElement( app.getChildren() ); - Collection leafs = ((DynamicCluster)cluster).getMembers(); - Iterator li = leafs.iterator(); - - Entity e1 = li.next(); - ((EntityInternal)e1).sensors().set(Sensors.newStringSensor("ip"), "127.0.0.1"); - EntityTestUtils.assertAttributeEqualsEventually(e1, Sensors.newStringSensor("url"), "http://127.0.0.1/"); - EntityTestUtils.assertAttributeEqualsEventually(e1, Attributes.MAIN_URI, URI.create("http://127.0.0.1/")); - - int i=2; - while (li.hasNext()) { - Entity ei = li.next(); - ((EntityInternal)ei).sensors().set(Sensors.newStringSensor("ip"), "127.0.0."+i); - i++; - } - - EntityTestUtils.assertAttributeEventually(cluster, Sensors.newSensor(Iterable.class, "urls.list"), - (Predicate)CollectionFunctionals.sizeEquals(3)); - - EntityTestUtils.assertAttributeEventually(cluster, Sensors.newSensor(String.class, "urls.list.comma_separated.max_2"), - StringPredicates.matchesRegex("\"http:\\/\\/127[^\"]*\\/\",\"http:\\/\\/127[^\"]*\\/\"")); - - EntityTestUtils.assertAttributeEventually(cluster, Attributes.MAIN_URI, Predicates.notNull()); - URI main = cluster.getAttribute(Attributes.MAIN_URI); - Assert.assertTrue(main.toString().matches("http:\\/\\/127.0.0..\\/"), "Wrong URI: "+main); - - EntityTestUtils.assertAttributeEventually(app, Attributes.MAIN_URI, Predicates.notNull()); - main = app.getAttribute(Attributes.MAIN_URI); - Assert.assertTrue(main.toString().matches("http:\\/\\/127.0.0..\\/"), "Wrong URI: "+main); - - // TODO would we want to allow "all-but-usual" as the default if nothing specified - } - - @Test(groups="Integration") - public void testWebappWithAveragingEnricher() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-webapp-with-averaging-enricher.yaml")); - waitForApplicationTasks(app); - log.info("Started "+app+":"); - Entities.dumpInfo(app); - - List appservers = MutableList.copyOf(Entities.descendants(app, JavaWebAppSoftwareProcess.class)); - Assert.assertEquals(appservers.size(), 3); - - EntityInternal srv0 = (EntityInternal) appservers.get(0); - EntityInternal dwac = (EntityInternal) srv0.getParent(); - EntityInternal cdwac = (EntityInternal) dwac.getParent(); - - srv0.sensors().set(Sensors.newDoubleSensor("my.load"), 20.0); - - EntityTestUtils.assertAttributeEventually(dwac, Sensors.newSensor(Double.class, "my.load.averaged"), - MathPredicates.equalsApproximately(20)); - EntityTestUtils.assertAttributeEventually(cdwac, Sensors.newSensor(Double.class, "my.load.averaged"), - MathPredicates.equalsApproximately(20)); - - srv0.sensors().set(Sensors.newDoubleSensor("my.load"), null); - EntityTestUtils.assertAttributeEventually(cdwac, Sensors.newSensor(Double.class, "my.load.averaged"), - Predicates.isNull()); - - ((EntityInternal) appservers.get(1)).sensors().set(Sensors.newDoubleSensor("my.load"), 10.0); - ((EntityInternal) appservers.get(2)).sensors().set(Sensors.newDoubleSensor("my.load"), 20.0); - EntityTestUtils.assertAttributeEventually(cdwac, Sensors.newSensor(Double.class, "my.load.averaged"), - MathPredicates.equalsApproximately(15)); - srv0.sensors().set(Sensors.newDoubleSensor("my.load"), 0.0); - EntityTestUtils.assertAttributeEventually(cdwac, Sensors.newSensor(Double.class, "my.load.averaged"), - MathPredicates.equalsApproximately(10)); - } - - @Override - protected Logger getLogger() { - return log; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EntitiesYamlIntegrationTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EntitiesYamlIntegrationTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EntitiesYamlIntegrationTest.java deleted file mode 100644 index f92af6c..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/EntitiesYamlIntegrationTest.java +++ /dev/null @@ -1,71 +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 org.apache.brooklyn.qa.camp; - -import static org.testng.Assert.*; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.camp.brooklyn.AbstractYamlTest; -import org.apache.brooklyn.entity.group.DynamicCluster; -import org.apache.brooklyn.entity.proxy.nginx.NginxController; -import org.apache.brooklyn.entity.webapp.ControlledDynamicWebAppCluster; -import org.apache.brooklyn.entity.webapp.tomcat.TomcatServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; - -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Iterables; - -public class EntitiesYamlIntegrationTest extends AbstractYamlTest { - - private static final Logger LOG = LoggerFactory.getLogger(EntitiesYamlIntegrationTest.class); - - @Test(groups = "Integration") - public void testStartTomcatCluster() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-tomcat-cluster.yaml")); - waitForApplicationTasks(app); - - assertNotNull(app); - assertEquals(app.getChildren().size(), 1); - final Entity entity = Iterables.getOnlyElement(app.getChildren()); - assertTrue(entity instanceof ControlledDynamicWebAppCluster, "entity="+entity); - ControlledDynamicWebAppCluster cluster = (ControlledDynamicWebAppCluster) entity; - - assertTrue(cluster.getController() instanceof NginxController, "controller="+cluster.getController()); - Iterable tomcats = FluentIterable.from(cluster.getCluster().getMembers()).filter(TomcatServer.class); - assertEquals(Iterables.size(tomcats), 2); - for (TomcatServer tomcat : tomcats) { - assertTrue(tomcat.getAttribute(TomcatServer.SERVICE_UP), "serviceup"); - } - - EntitySpec spec = entity.getConfig(DynamicCluster.MEMBER_SPEC); - assertNotNull(spec); - assertEquals(spec.getType(), TomcatServer.class); - assertEquals(spec.getConfig().get(DynamicCluster.QUARANTINE_FAILED_ENTITIES), Boolean.FALSE); - assertEquals(spec.getConfig().get(DynamicCluster.INITIAL_QUORUM_SIZE), 2); - } - - - @Override - protected Logger getLogger() { - return LOG; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsIntegrationTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsIntegrationTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsIntegrationTest.java deleted file mode 100644 index 1367ddd..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsIntegrationTest.java +++ /dev/null @@ -1,273 +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 org.apache.brooklyn.qa.camp; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.IOException; -import java.io.Reader; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.api.policy.Policy; -import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatform; -import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherNoServer; -import org.apache.brooklyn.camp.spi.Assembly; -import org.apache.brooklyn.camp.spi.AssemblyTemplate; -import org.apache.brooklyn.camp.spi.PlatformComponent; -import org.apache.brooklyn.camp.spi.PlatformRootSummary; -import org.apache.brooklyn.camp.spi.collection.ResolvableLink; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; -import org.apache.brooklyn.entity.webapp.DynamicWebAppCluster; -import org.apache.brooklyn.entity.webapp.JavaWebAppService; -import org.apache.brooklyn.entity.webapp.WebAppService; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.ResourceUtils; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.net.Urls; -import org.apache.brooklyn.util.stream.Streams; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy; - -import com.google.common.collect.Iterables; - -@Test(groups="Integration") -public class JavaWebAppsIntegrationTest { - - private static final Logger log = LoggerFactory.getLogger(JavaWebAppsIntegrationTest.class); - - private ManagementContext brooklynMgmt; - private BrooklynCampPlatform platform; - - @BeforeMethod(alwaysRun=true) - public void setup() { - BrooklynCampPlatformLauncherNoServer launcher = new BrooklynCampPlatformLauncherNoServer(); - launcher.launch(); - brooklynMgmt = launcher.getBrooklynMgmt(); - - platform = new BrooklynCampPlatform( - PlatformRootSummary.builder().name("Brooklyn CAMP Platform").build(), - brooklynMgmt); - } - - @AfterMethod - public void teardown() { - if (brooklynMgmt!=null) Entities.destroyAll(brooklynMgmt); - } - - public void testSimpleYamlDeploy() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-simple.yaml")); - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input); - - try { - Assembly assembly = at.getInstantiator().newInstance().instantiate(at, platform); - log.info("Test - created "+assembly); - - final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId()); - log.info("App - "+app); - Assert.assertEquals(app.getDisplayName(), "sample-single-jboss"); - - // locations set on AT in this yaml - Assert.assertEquals(app.getLocations().size(), 1); - - Set> tasks = BrooklynTaskTags.getTasksInEntityContext(brooklynMgmt.getExecutionManager(), app); - log.info("Waiting on "+tasks.size()+" task(s)"); - for (Task t: tasks) { - t.blockUntilEnded(); - } - - log.info("App started:"); - Entities.dumpInfo(app); - - Assert.assertEquals(app.getChildren().size(), 1); - Assert.assertEquals(app.getChildren().iterator().next().getDisplayName(), "tomcat1"); - Assert.assertEquals(app.getChildren().iterator().next().getLocations().size(), 1); - - final String url = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - String url = app.getChildren().iterator().next().getAttribute(JavaWebAppService.ROOT_URL); - return checkNotNull(url, "url of %s", app); - }}); - - String site = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - return new ResourceUtils(this).getResourceAsString(url); - }}); - - log.info("App URL for "+app+": "+url); - Assert.assertTrue(url.contains("928"), "URL should be on port 9280+ based on config set in yaml, url "+url+", app "+app); - Assert.assertTrue(site.toLowerCase().contains("hello"), site); - Assert.assertTrue(!platform.assemblies().isEmpty()); - } catch (Exception e) { - log.warn("Unable to instantiate "+at+" (rethrowing): "+e); - throw Exceptions.propagate(e); - } - } - - public void testWithDbDeploy() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-and-db-with-function.yaml")); - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input); - - try { - Assembly assembly = at.getInstantiator().newInstance().instantiate(at, platform); - log.info("Test - created "+assembly); - - final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId()); - log.info("App - "+app); - - // locations set on individual services here - Assert.assertEquals(app.getLocations().size(), 0); - - Iterator> pcs = assembly.getPlatformComponents().links().iterator(); - PlatformComponent pc1 = pcs.next().resolve(); - Entity cluster = brooklynMgmt.getEntityManager().getEntity(pc1.getId()); - log.info("pc1 - "+pc1+" - "+cluster); - - PlatformComponent pc2 = pcs.next().resolve(); - log.info("pc2 - "+pc2); - - Set> tasks = BrooklynTaskTags.getTasksInEntityContext(brooklynMgmt.getExecutionManager(), app); - log.info("Waiting on "+tasks.size()+" task(s)"); - AtomicInteger i = new AtomicInteger(0); - for (Task t: tasks) { - t.blockUntilEnded(); - log.info("Completed task #" + i.incrementAndGet()); - } - - log.info("App started:"); - Entities.dumpInfo(app); - - EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); - Assert.assertEquals(app.getAttribute(Attributes.SERVICE_UP), Boolean.TRUE); - - final String url = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - Entity cluster = Iterables.getOnlyElement( Iterables.filter(app.getChildren(), WebAppService.class) ); - String url = cluster.getAttribute(JavaWebAppService.ROOT_URL); - return checkNotNull(url, "url of %s", cluster); - }}); - - String site = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - return new ResourceUtils(this).getResourceAsString(url); - }}); - - log.info("App URL for "+app+": "+url); - Assert.assertTrue(url.contains("921"), "URL should be on port 9280+ based on config set in yaml, url "+url+", app "+app); - Assert.assertTrue(site.toLowerCase().contains("hello"), site); - Assert.assertTrue(!platform.assemblies().isEmpty()); - - String dbPage = new ResourceUtils(this).getResourceAsString(Urls.mergePaths(url, "db.jsp")); - Assert.assertTrue(dbPage.contains("Isaac Asimov"), "db.jsp does not mention Isaac Asimov, probably the DB did not get initialised:\n"+dbPage); - } catch (Exception e) { - log.warn("Unable to instantiate "+at+" (rethrowing): "+e); - throw Exceptions.propagate(e); - } - } - - public void testWithPolicyDeploy() { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-and-db-with-policy.yaml")); - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input); - - try { - Assembly assembly = at.getInstantiator().newInstance().instantiate(at, platform); - log.info("Test - created "+assembly); - - final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId()); - log.info("App - "+app); - - // locations set on individual services here - Assert.assertEquals(app.getLocations().size(), 0); - - Set> tasks = BrooklynTaskTags.getTasksInEntityContext(brooklynMgmt.getExecutionManager(), app); - log.info("Waiting on "+tasks.size()+" task(s)"); - for (Task t: tasks) { - t.blockUntilEnded(); - } - - log.info("App started:"); - Entities.dumpInfo(app); - - Iterator> pcs = assembly.getPlatformComponents().links().iterator(); - PlatformComponent clusterComponent = null; - while (pcs.hasNext() && clusterComponent == null) { - PlatformComponent component = pcs.next().resolve(); - if (component.getName().equals("My Web with Policy")) - clusterComponent = component; - } - Assert.assertNotNull(clusterComponent, "Database PlatformComponent not found"); - Entity cluster = brooklynMgmt.getEntityManager().getEntity(clusterComponent.getId()); - log.info("pc1 - "+clusterComponent+" - "+cluster); - - Assert.assertEquals(cluster.policies().size(), 1); - Policy policy = cluster.policies().iterator().next(); - Assert.assertNotNull(policy); - Assert.assertTrue(policy instanceof AutoScalerPolicy, "policy="+policy); - Assert.assertEquals(policy.getConfig(AutoScalerPolicy.MAX_POOL_SIZE), (Integer)5); - Assert.assertEquals(policy.getConfig(AutoScalerPolicy.MIN_POOL_SIZE), (Integer)1); - Assert.assertEquals(policy.getConfig(AutoScalerPolicy.METRIC), DynamicWebAppCluster.REQUESTS_PER_SECOND_IN_WINDOW_PER_NODE); - Assert.assertEquals(policy.getConfig(AutoScalerPolicy.METRIC_LOWER_BOUND), (Integer)10); - Assert.assertEquals(policy.getConfig(AutoScalerPolicy.METRIC_UPPER_BOUND), (Integer)100); - Assert.assertTrue(policy.isRunning()); - - EntityTestUtils.assertAttributeEqualsEventually(app, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); - Assert.assertEquals(app.getAttribute(Attributes.SERVICE_UP), Boolean.TRUE); - - final String url = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - Entity cluster = Iterables.getOnlyElement( Iterables.filter(app.getChildren(), WebAppService.class) ); - String url = cluster.getAttribute(JavaWebAppService.ROOT_URL); - return checkNotNull(url, "url of %s", cluster); - }}); - - String site = Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TEN_SECONDS), new Callable() { - @Override public String call() throws Exception { - return new ResourceUtils(this).getResourceAsString(url); - }}); - - log.info("App URL for "+app+": "+url); - Assert.assertTrue(url.contains("921"), "URL should be on port 9280+ based on config set in yaml, url "+url+", app "+app); - Assert.assertTrue(site.toLowerCase().contains("hello"), site); - Assert.assertTrue(!platform.assemblies().isEmpty()); - - String dbPage = new ResourceUtils(this).getResourceAsString(Urls.mergePaths(url, "db.jsp")); - Assert.assertTrue(dbPage.contains("Isaac Asimov"), "db.jsp does not mention Isaac Asimov, probably the DB did not get initialised:\n"+dbPage); - } catch (Exception e) { - log.warn("Unable to instantiate "+at+" (rethrowing): "+e); - throw Exceptions.propagate(e); - } - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsMatchingTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsMatchingTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsMatchingTest.java deleted file mode 100644 index 92e29b9..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/camp/JavaWebAppsMatchingTest.java +++ /dev/null @@ -1,144 +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 org.apache.brooklyn.qa.camp; - -import java.io.IOException; -import java.io.Reader; -import java.util.Iterator; -import java.util.Map; - -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatform; -import org.apache.brooklyn.camp.brooklyn.BrooklynCampReservedKeys; -import org.apache.brooklyn.camp.spi.AssemblyTemplate; -import org.apache.brooklyn.camp.spi.PlatformComponentTemplate; -import org.apache.brooklyn.camp.spi.PlatformRootSummary; -import org.apache.brooklyn.camp.spi.collection.ResolvableLink; -import org.apache.brooklyn.camp.spi.pdp.DeploymentPlan; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.ResourceUtils; -import org.apache.brooklyn.util.core.task.DeferredSupplier; -import org.apache.brooklyn.util.stream.Streams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -@Test -public class JavaWebAppsMatchingTest { - - private static final Logger log = LoggerFactory.getLogger(JavaWebAppsMatchingTest.class); - - private ManagementContext brooklynMgmt; - private BrooklynCampPlatform platform; - - @BeforeMethod(alwaysRun=true) - public void setup() { - brooklynMgmt = new LocalManagementContextForTests(); - platform = new BrooklynCampPlatform( - PlatformRootSummary.builder().name("Brooklyn CAMP Platform").build(), - brooklynMgmt); - } - - // FIXME all commented-out lines require camp server - - @AfterMethod(alwaysRun=true) - public void teardown() { - if (brooklynMgmt!=null) Entities.destroyAll(brooklynMgmt); - } - - public void testSimpleYamlParse() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-simple.yaml")); - DeploymentPlan plan = platform.pdp().parseDeploymentPlan(input); - log.info("DP is:\n"+plan.toString()); - Assert.assertEquals(plan.getServices().size(), 1); - Assert.assertEquals(plan.getName(), "sample-single-jboss"); - } - - public void testSimpleYamlMatch() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-simple.yaml")); - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input); - - Assert.assertEquals(at.getName(), "sample-single-jboss"); - } - - public void testExampleFunctionsYamlMatch() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("example-with-function.yaml")); - - DeploymentPlan plan = platform.pdp().parseDeploymentPlan(input); - log.info("DP is:\n"+plan.toString()); - Map cfg1 = (Map) plan.getServices().get(0).getCustomAttributes().get(BrooklynCampReservedKeys.BROOKLYN_CONFIG); - Map cfg = MutableMap.copyOf(cfg1); - - Assert.assertEquals(cfg.remove("literalValue1"), "$brooklyn: is a fun place"); - Assert.assertEquals(cfg.remove("literalValue2"), "$brooklyn: is a fun place"); - Assert.assertEquals(cfg.remove("literalValue3"), "$brooklyn: is a fun place"); - Assert.assertEquals(cfg.remove("literalValue4"), "$brooklyn: is a fun place"); - Assert.assertEquals(cfg.remove("$brooklyn:1"), "key to the city"); - Assert.assertTrue(cfg.isEmpty(), ""+cfg); - - Assert.assertEquals(plan.getName(), "example-with-function"); - Assert.assertEquals(plan.getCustomAttributes().get("location"), "localhost"); - - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(plan); - - Assert.assertEquals(at.getName(), "example-with-function"); - Assert.assertEquals(at.getCustomAttributes().get("location"), "localhost"); - - PlatformComponentTemplate pct = at.getPlatformComponentTemplates().links().iterator().next().resolve(); - Object cfg2 = pct.getCustomAttributes().get(BrooklynCampReservedKeys.BROOKLYN_CONFIG); - Assert.assertEquals(cfg2, cfg1); - } - - public void testJavaAndDbWithFunctionYamlMatch() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-and-db-with-function.yaml")); - assertWebDbWithFunctionValid(input); - } - - public void testJavaAndDbWithFunctionYamlMatch2() throws IOException { - Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("java-web-app-and-db-with-function-2.yaml")); - assertWebDbWithFunctionValid(input); - } - - protected void assertWebDbWithFunctionValid(Reader input) { - DeploymentPlan plan = platform.pdp().parseDeploymentPlan(input); - log.info("DP is:\n"+plan.toString()); - - AssemblyTemplate at = platform.pdp().registerDeploymentPlan(plan); - - Assert.assertEquals(at.getName(), "java-cluster-db-example"); - - Iterator> pcti = at.getPlatformComponentTemplates().links().iterator(); - PlatformComponentTemplate pct1 = pcti.next().resolve(); - - PlatformComponentTemplate pct2 = pcti.next().resolve(); - - Map config = (Map) pct1.getCustomAttributes().get(BrooklynCampReservedKeys.BROOKLYN_CONFIG); - Map javaSysProps = (Map) config.get("java.sysprops"); - Object dbUrl = javaSysProps.get("brooklyn.example.db.url"); - Assert.assertTrue(dbUrl instanceof DeferredSupplier, "url is: "+dbUrl); - - Assert.assertEquals(pct2.getCustomAttributes().get("planId"), "db"); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-library/blob/02abbab0/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/downstreamparent/DownstreamParentTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/downstreamparent/DownstreamParentTest.java b/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/downstreamparent/DownstreamParentTest.java deleted file mode 100644 index 33c4c42..0000000 --- a/brooklyn-library/qa/src/test/java/org/apache/brooklyn/qa/downstreamparent/DownstreamParentTest.java +++ /dev/null @@ -1,64 +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 org.apache.brooklyn.qa.downstreamparent; - -import static org.testng.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.apache.brooklyn.util.net.Networking; -import org.apache.maven.it.Verifier; -import org.apache.maven.shared.utils.io.FileUtils; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -public class DownstreamParentTest { - - private static final String PROJECTS_DIR = "src/test/projects"; - private static final String WORK_DIR = "target/ut/"; - - /** - * Asserts that a trivial project using brooklyn-downstream-parent can be - * loaded into Brooklyn's catalogue and its entities deployed. - */ - @Test(groups = "Integration") - public void testDownstreamProjectsCanBeLoadedIntoBrooklynCatalogByDefault() throws Exception { - int port = Networking.nextAvailablePort(57000); - File dir = getBasedir("downstream-parent-test"); - Verifier verifier = new Verifier(dir.getAbsolutePath()); - verifier.setMavenDebug(true); - verifier.executeGoal("post-integration-test", ImmutableMap.of( - "bindPort", String.valueOf(port))); - verifier.verifyErrorFreeLog(); - verifier.verifyTextInLog("Hello from the init method of the HelloEntity"); - } - - /** Replicates the behaviour of getBasedir in JUnit's TestResources class */ - public File getBasedir(String project) throws IOException { - File src = (new File(PROJECTS_DIR, project)).getCanonicalFile(); - assertTrue(src.isDirectory(), "Test project directory does not exist: " + src.getPath()); - File basedir = (new File(WORK_DIR, getClass().getSimpleName() + "_" + project)).getCanonicalFile(); - FileUtils.deleteDirectory(basedir); - assertTrue(basedir.mkdirs(), "Test project working directory created"); - FileUtils.copyDirectoryStructure(src, basedir); - return basedir; - } -}