id
stringlengths 27
31
| content
stringlengths 14
287k
| max_stars_repo_path
stringlengths 52
57
|
|---|---|---|
crossvul-java_data_bad_4727_2
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.kernel.templateparser.TemplateContext;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Theme;
import com.liferay.portal.template.TemplateContextHelper;
import com.liferay.portal.template.TemplatePortletPreferences;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PropsValues;
import com.liferay.portal.util.WebKeys;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.utility.ObjectConstructor;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/**
* @author Mika Koivisto
* @author Raymond Augé
*/
public class FreeMarkerTemplateContextHelper extends TemplateContextHelper {
@Override
public Map<String, Object> getHelperUtilities() {
Map<String, Object> helperUtilities = super.getHelperUtilities();
// Enum util
helperUtilities.put(
"enumUtil", BeansWrapper.getDefaultInstance().getEnumModels());
// Object util
helperUtilities.put("objectUtil", new ObjectConstructor());
// Portlet preferences
helperUtilities.put(
"freeMarkerPortletPreferences", new TemplatePortletPreferences());
// Static class util
helperUtilities.put(
"staticUtil", BeansWrapper.getDefaultInstance().getStaticModels());
return helperUtilities;
}
@Override
public Set<String> getRestrictedVariables() {
return SetUtil.fromArray(
PropsValues.JOURNAL_TEMPLATE_FREEMARKER_RESTRICTED_VARIABLES);
}
@Override
public void prepare(
TemplateContext templateContext, HttpServletRequest request) {
super.prepare(templateContext, request);
// Theme display
ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
WebKeys.THEME_DISPLAY);
if (themeDisplay != null) {
Theme theme = themeDisplay.getTheme();
// Full css and templates path
String servletContextName = GetterUtil.getString(
theme.getServletContextName());
templateContext.put(
"fullCssPath",
StringPool.SLASH + servletContextName +
theme.getFreeMarkerTemplateLoader() + theme.getCssPath());
templateContext.put(
"fullTemplatesPath",
StringPool.SLASH + servletContextName +
theme.getFreeMarkerTemplateLoader() +
theme.getTemplatesPath());
// Init
templateContext.put(
"init",
StringPool.SLASH + themeDisplay.getPathContext() +
FreeMarkerTemplateLoader.SERVLET_SEPARATOR +
"/html/themes/_unstyled/templates/init.ftl");
}
// Insert custom ftl variables
Map<String, Object> ftlVariables =
(Map<String, Object>)request.getAttribute(WebKeys.FTL_VARIABLES);
if (ftlVariables != null) {
for (Map.Entry<String, Object> entry : ftlVariables.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (Validator.isNotNull(key)) {
templateContext.put(key, value);
}
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_2
|
crossvul-java_data_bad_3820_4
|
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.sync;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.candlepin.config.CandlepinCommonTestConfig;
import org.candlepin.config.Config;
import org.candlepin.config.ConfigProperties;
import org.candlepin.model.ExporterMetadata;
import org.candlepin.model.ExporterMetadataCurator;
import org.candlepin.model.Owner;
import org.candlepin.sync.Importer.ImportFile;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* ImporterTest
*/
public class ImporterTest {
private ObjectMapper mapper;
private I18n i18n;
private static final String MOCK_JS_PATH = "/tmp/empty.js";
private CandlepinCommonTestConfig config;
@Before
public void init() throws FileNotFoundException, URISyntaxException {
mapper = SyncUtils.getObjectMapper(new Config(new HashMap<String, String>()));
i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
config = new CandlepinCommonTestConfig();
config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp");
PrintStream ps = new PrintStream(new File(this.getClass()
.getClassLoader().getResource("candlepin_info.properties").toURI()));
ps.println("version=0.0.3");
ps.println("release=1");
ps.close();
}
@Test
public void validateMetaJson() throws Exception {
/* read file
* read in version
* read in created date
* make sure created date is XYZ
* make sure version is > ABC
*/
Date now = new Date();
File file = createFile("/tmp/meta", "0.0.3", now,
"test_user", "prefix");
File actual = createFile("/tmp/meta.json", "0.0.3", now,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
ExporterMetadata em = new ExporterMetadata();
Date daybefore = getDateBeforeDays(1);
em.setExported(daybefore);
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actual,
new ConflictOverrides());
Meta fileMeta = mapper.readValue(file, Meta.class);
Meta actualMeta = mapper.readValue(actual, Meta.class);
assertEquals(fileMeta.getPrincipalName(), actualMeta.getPrincipalName());
assertEquals(fileMeta.getCreated().getTime(), actualMeta.getCreated().getTime());
assertEquals(fileMeta.getWebAppPrefix(), actualMeta.getWebAppPrefix());
assertTrue(file.delete());
assertTrue(actual.delete());
assertTrue(daybefore.compareTo(em.getExported()) < 0);
}
@Test
public void firstRun() throws Exception {
File f = createFile("/tmp/meta", "0.0.3", new Date(),
"test_user", "prefix");
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
assertTrue(f.delete());
assertTrue(actualmeta.delete());
verify(emc).create(any(ExporterMetadata.class));
}
@Test
public void oldImport() throws Exception {
// actualmeta is the mock for the import itself
File actualmeta = createFile("/tmp/meta.json", "0.0.3", getDateBeforeDays(10),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// emc is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(getDateBeforeDays(3));
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
try {
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
fail();
}
catch (ImportConflictException e) {
assertFalse(e.message().getConflicts().isEmpty());
assertEquals(1, e.message().getConflicts().size());
assertTrue(e.message().getConflicts().contains(
Importer.Conflict.MANIFEST_OLD));
}
}
@Test
public void sameImport() throws Exception {
// actualmeta is the mock for the import itself
Date date = getDateBeforeDays(10);
File actualmeta = createFile("/tmp/meta.json", "0.0.3", date,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// emc is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(date); // exact same date = assumed same manifest
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
try {
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
fail();
}
catch (ImportConflictException e) {
assertFalse(e.message().getConflicts().isEmpty());
assertEquals(1, e.message().getConflicts().size());
assertTrue(e.message().getConflicts().contains(
Importer.Conflict.MANIFEST_SAME));
}
}
@Test
public void mergeConflicts() {
ImportConflictException e2 = new ImportConflictException("testing",
Importer.Conflict.DISTRIBUTOR_CONFLICT);
ImportConflictException e3 = new ImportConflictException("testing2",
Importer.Conflict.MANIFEST_OLD);
List<ImportConflictException> exceptions =
new LinkedList<ImportConflictException>();
exceptions.add(e2);
exceptions.add(e3);
ImportConflictException e1 = new ImportConflictException(exceptions);
assertEquals("testing\ntesting2", e1.message().getDisplayMessage());
assertEquals(2, e1.message().getConflicts().size());
assertTrue(e1.message().getConflicts().contains(
Importer.Conflict.DISTRIBUTOR_CONFLICT));
assertTrue(e1.message().getConflicts().contains(Importer.Conflict.MANIFEST_OLD));
}
@Test
public void newerImport() throws Exception {
// this tests bz #790751
Date importDate = getDateBeforeDays(10);
// actualmeta is the mock for the import itself
File actualmeta = createFile("/tmp/meta.json", "0.0.3", importDate,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// em is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(getDateBeforeDays(30));
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
assertEquals(importDate, em.getExported());
}
@Test
public void newerVersionImport() throws Exception {
// if we do are importing candlepin 0.0.10 data into candlepin 0.0.3,
// import the rules.
String version = "0.0.10";
File actualmeta = createFile("/tmp/meta.json", version, new Date(),
"test_user", "prefix");
File[] jsArray = createMockJsFile(MOCK_JS_PATH);
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
RulesImporter ri = mock(RulesImporter.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, null, emc, null, null, i18n);
i.importRules(jsArray, actualmeta);
//verify that rules were imported
verify(ri).importObject(any(Reader.class), eq(version));
}
@Test
public void olderVersionImport() throws Exception {
// if we are importing candlepin 0.0.1 data into
// candlepin 0.0.3, do not import the rules
File actualmeta = createFile("/tmp/meta.json", "0.0.1", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
RulesImporter ri = mock(RulesImporter.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
//verify that rules were not imported
verify(ri, never()).importObject(any(Reader.class), any(String.class));
}
@Test(expected = ImporterException.class)
public void nullType() throws ImporterException, IOException {
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
try {
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, null, null, null, i18n);
// null Type should cause exception
i.validateMetadata(null, null, actualmeta, new ConflictOverrides());
}
finally {
assertTrue(actualmeta.delete());
}
}
@Test(expected = ImporterException.class)
public void expectOwner() throws ImporterException, IOException {
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
when(emc.lookupByTypeAndOwner(ExporterMetadata.TYPE_PER_USER, null))
.thenReturn(null);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
// null Type should cause exception
i.validateMetadata(ExporterMetadata.TYPE_PER_USER, null, actualmeta,
new ConflictOverrides());
verify(emc, never()).create(any(ExporterMetadata.class));
}
@Test
public void testImportWithNonZipArchive()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/non_zip_file.zip");
FileWriter fw = new FileWriter(archive);
fw.write("Just a flat file");
fw.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The archive {0} is " +
"not a properly compressed file or is empty", "non_zip_file.zip"));
return;
}
assertTrue(false);
}
@Test
public void testImportZipArchiveNoContent()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("This is just a zip file with no content"));
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not " +
"contain the required signature file"));
return;
}
assertTrue(false);
}
@Test
public void testImportZipSigConsumerNotZip()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
FileOutputStream fos = new FileOutputStream(ceArchive);
fos.write("This is just a flat file".getBytes());
fos.close();
addFileToArchive(out, ceArchive);
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The archive {0} is " +
"not a properly compressed file or is empty", "consumer_export.zip"));
return;
}
assertTrue(false);
}
@Test
public void testImportZipSigAndEmptyConsumerZip()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
ZipOutputStream cezip = new ZipOutputStream(new FileOutputStream(ceArchive));
cezip.putNextEntry(new ZipEntry("This is just a zip file with no content"));
cezip.close();
addFileToArchive(out, ceArchive);
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The consumer_export " +
"archive has no contents"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoMeta()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), null);
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required meta.json file"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoRulesDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), null);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required rules directory"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoRulesFile()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
when(ruleDir.listFiles()).thenReturn(new File[0]);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required rules file(s)"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoConsumerTypesDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), null);
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required consumer_types directory"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoConsumer()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), null);
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required consumer.json file"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoProductDir()
throws IOException, ImporterException {
RulesImporter ri = mock(RulesImporter.class);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = createMockJsFile(MOCK_JS_PATH);
when(ruleDir.listFiles()).thenReturn(rulesFiles);
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
// this is the hook to stop testing. we confirm that the archive component tests
// are passed and then jump out instead of trying to fake the actual file
// processing.
when(ri.importObject(any(Reader.class), any(String.class))).thenThrow(
new RuntimeException("Done with the test"));
importFiles.put(ImportFile.META.fileName(), actualmeta);
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), null);
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), null);
try {
i.importObjects(owner, importFiles, co);
}
catch (RuntimeException e) {
assertEquals(e.getMessage(), "Done with the test");
return;
}
assertTrue(false);
}
@Test
public void testImportProductNoEntitlementDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), null);
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required entitlements directory"));
return;
}
assertTrue(false);
}
@After
public void tearDown() throws Exception {
PrintStream ps = new PrintStream(new File(this.getClass()
.getClassLoader().getResource("candlepin_info.properties").toURI()));
ps.println("version=${version}");
ps.println("release=${release}");
ps.close();
File mockJs = new File(MOCK_JS_PATH);
mockJs.delete();
}
private File createFile(String filename, String version, Date date,
String username, String prefix)
throws JsonGenerationException, JsonMappingException, IOException {
File f = new File(filename);
Meta meta = new Meta(version, date, username, prefix);
mapper.writeValue(f, meta);
return f;
}
private File[] createMockJsFile(String filename)
throws IOException {
FileWriter f = new FileWriter(filename);
f.write("// nothing to see here");
f.close();
File[] fileArray = new File[1];
fileArray[0] = new File(filename);
return fileArray;
}
private Date getDateBeforeDays(int days) {
long daysinmillis = 24 * 60 * 60 * 1000;
long ms = System.currentTimeMillis() - (days * daysinmillis);
Date backDate = new Date();
backDate.setTime(ms);
return backDate;
}
private void addFileToArchive(ZipOutputStream out, File file)
throws IOException, FileNotFoundException {
out.putNextEntry(new ZipEntry(file.getName()));
FileInputStream in = new FileInputStream(file);
byte [] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_3820_4
|
crossvul-java_data_bad_2293_2
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2293_2
|
crossvul-java_data_bad_2153_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.activemq.broker;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.transaction.xa.XAResource;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.region.ConnectionStatistics;
import org.apache.activemq.broker.region.RegionBroker;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.CommandTypes;
import org.apache.activemq.command.ConnectionControl;
import org.apache.activemq.command.ConnectionError;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerControl;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.ControlCommand;
import org.apache.activemq.command.DataArrayResponse;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.ExceptionResponse;
import org.apache.activemq.command.FlushCommand;
import org.apache.activemq.command.IntegerResponse;
import org.apache.activemq.command.KeepAliveInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageDispatch;
import org.apache.activemq.command.MessageDispatchNotification;
import org.apache.activemq.command.MessagePull;
import org.apache.activemq.command.ProducerAck;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.RemoveSubscriptionInfo;
import org.apache.activemq.command.Response;
import org.apache.activemq.command.SessionId;
import org.apache.activemq.command.SessionInfo;
import org.apache.activemq.command.ShutdownInfo;
import org.apache.activemq.command.TransactionId;
import org.apache.activemq.command.TransactionInfo;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.network.MBeanNetworkListener;
import org.apache.activemq.network.NetworkBridgeConfiguration;
import org.apache.activemq.network.NetworkBridgeFactory;
import org.apache.activemq.security.MessageAuthorizationPolicy;
import org.apache.activemq.state.CommandVisitor;
import org.apache.activemq.state.ConnectionState;
import org.apache.activemq.state.ConsumerState;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.state.SessionState;
import org.apache.activemq.state.TransactionState;
import org.apache.activemq.thread.Task;
import org.apache.activemq.thread.TaskRunner;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.transaction.Transaction;
import org.apache.activemq.transport.DefaultTransportListener;
import org.apache.activemq.transport.ResponseCorrelator;
import org.apache.activemq.transport.TransmitCallback;
import org.apache.activemq.transport.Transport;
import org.apache.activemq.transport.TransportDisposedIOException;
import org.apache.activemq.util.IntrospectionSupport;
import org.apache.activemq.util.MarshallingSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class TransportConnection implements Connection, Task, CommandVisitor {
private static final Logger LOG = LoggerFactory.getLogger(TransportConnection.class);
private static final Logger TRANSPORTLOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Transport");
private static final Logger SERVICELOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Service");
// Keeps track of the broker and connector that created this connection.
protected final Broker broker;
protected final TransportConnector connector;
// Keeps track of the state of the connections.
// protected final ConcurrentHashMap localConnectionStates=new
// ConcurrentHashMap();
protected final Map<ConnectionId, ConnectionState> brokerConnectionStates;
// The broker and wireformat info that was exchanged.
protected BrokerInfo brokerInfo;
protected final List<Command> dispatchQueue = new LinkedList<Command>();
protected TaskRunner taskRunner;
protected final AtomicReference<IOException> transportException = new AtomicReference<IOException>();
protected AtomicBoolean dispatchStopped = new AtomicBoolean(false);
private final Transport transport;
private MessageAuthorizationPolicy messageAuthorizationPolicy;
private WireFormatInfo wireFormatInfo;
// Used to do async dispatch.. this should perhaps be pushed down into the
// transport layer..
private boolean inServiceException;
private final ConnectionStatistics statistics = new ConnectionStatistics();
private boolean manageable;
private boolean slow;
private boolean markedCandidate;
private boolean blockedCandidate;
private boolean blocked;
private boolean connected;
private boolean active;
private boolean starting;
private boolean pendingStop;
private long timeStamp;
private final AtomicBoolean stopping = new AtomicBoolean(false);
private final CountDownLatch stopped = new CountDownLatch(1);
private final AtomicBoolean asyncException = new AtomicBoolean(false);
private final Map<ProducerId, ProducerBrokerExchange> producerExchanges = new HashMap<ProducerId, ProducerBrokerExchange>();
private final Map<ConsumerId, ConsumerBrokerExchange> consumerExchanges = new HashMap<ConsumerId, ConsumerBrokerExchange>();
private final CountDownLatch dispatchStoppedLatch = new CountDownLatch(1);
private ConnectionContext context;
private boolean networkConnection;
private boolean faultTolerantConnection;
private final AtomicInteger protocolVersion = new AtomicInteger(CommandTypes.PROTOCOL_VERSION);
private DemandForwardingBridge duplexBridge;
private final TaskRunnerFactory taskRunnerFactory;
private final TaskRunnerFactory stopTaskRunnerFactory;
private TransportConnectionStateRegister connectionStateRegister = new SingleTransportConnectionStateRegister();
private final ReentrantReadWriteLock serviceLock = new ReentrantReadWriteLock();
private String duplexNetworkConnectorId;
private Throwable stopError = null;
/**
* @param taskRunnerFactory - can be null if you want direct dispatch to the transport
* else commands are sent async.
* @param stopTaskRunnerFactory - can <b>not</b> be null, used for stopping this connection.
*/
public TransportConnection(TransportConnector connector, final Transport transport, Broker broker,
TaskRunnerFactory taskRunnerFactory, TaskRunnerFactory stopTaskRunnerFactory) {
this.connector = connector;
this.broker = broker;
RegionBroker rb = (RegionBroker) broker.getAdaptor(RegionBroker.class);
brokerConnectionStates = rb.getConnectionStates();
if (connector != null) {
this.statistics.setParent(connector.getStatistics());
this.messageAuthorizationPolicy = connector.getMessageAuthorizationPolicy();
}
this.taskRunnerFactory = taskRunnerFactory;
this.stopTaskRunnerFactory = stopTaskRunnerFactory;
this.transport = transport;
final BrokerService brokerService = this.broker.getBrokerService();
if( this.transport instanceof BrokerServiceAware ) {
((BrokerServiceAware)this.transport).setBrokerService(brokerService);
}
this.transport.setTransportListener(new DefaultTransportListener() {
@Override
public void onCommand(Object o) {
serviceLock.readLock().lock();
try {
if (!(o instanceof Command)) {
throw new RuntimeException("Protocol violation - Command corrupted: " + o.toString());
}
Command command = (Command) o;
if (!brokerService.isStopping()) {
Response response = service(command);
if (response != null && !brokerService.isStopping()) {
dispatchSync(response);
}
} else {
throw new BrokerStoppedException("Broker " + brokerService + " is being stopped");
}
} finally {
serviceLock.readLock().unlock();
}
}
@Override
public void onException(IOException exception) {
serviceLock.readLock().lock();
try {
serviceTransportException(exception);
} finally {
serviceLock.readLock().unlock();
}
}
});
connected = true;
}
/**
* Returns the number of messages to be dispatched to this connection
*
* @return size of dispatch queue
*/
@Override
public int getDispatchQueueSize() {
synchronized (dispatchQueue) {
return dispatchQueue.size();
}
}
public void serviceTransportException(IOException e) {
BrokerService bService = connector.getBrokerService();
if (bService.isShutdownOnSlaveFailure()) {
if (brokerInfo != null) {
if (brokerInfo.isSlaveBroker()) {
LOG.error("Slave has exception: {} shutting down master now.", e.getMessage(), e);
try {
doStop();
bService.stop();
} catch (Exception ex) {
LOG.warn("Failed to stop the master", ex);
}
}
}
}
if (!stopping.get() && !pendingStop) {
transportException.set(e);
if (TRANSPORTLOG.isDebugEnabled()) {
TRANSPORTLOG.debug(this + " failed: " + e, e);
} else if (TRANSPORTLOG.isWarnEnabled() && !expected(e)) {
TRANSPORTLOG.warn(this + " failed: " + e);
}
stopAsync();
}
}
private boolean expected(IOException e) {
return isStomp() && ((e instanceof SocketException && e.getMessage().indexOf("reset") != -1) || e instanceof EOFException);
}
private boolean isStomp() {
URI uri = connector.getUri();
return uri != null && uri.getScheme() != null && uri.getScheme().indexOf("stomp") != -1;
}
/**
* Calls the serviceException method in an async thread. Since handling a
* service exception closes a socket, we should not tie up broker threads
* since client sockets may hang or cause deadlocks.
*/
@Override
public void serviceExceptionAsync(final IOException e) {
if (asyncException.compareAndSet(false, true)) {
new Thread("Async Exception Handler") {
@Override
public void run() {
serviceException(e);
}
}.start();
}
}
/**
* Closes a clients connection due to a detected error. Errors are ignored
* if: the client is closing or broker is closing. Otherwise, the connection
* error transmitted to the client before stopping it's transport.
*/
@Override
public void serviceException(Throwable e) {
// are we a transport exception such as not being able to dispatch
// synchronously to a transport
if (e instanceof IOException) {
serviceTransportException((IOException) e);
} else if (e.getClass() == BrokerStoppedException.class) {
// Handle the case where the broker is stopped
// But the client is still connected.
if (!stopping.get()) {
SERVICELOG.debug("Broker has been stopped. Notifying client and closing his connection.");
ConnectionError ce = new ConnectionError();
ce.setException(e);
dispatchSync(ce);
// Record the error that caused the transport to stop
this.stopError = e;
// Wait a little bit to try to get the output buffer to flush
// the exception notification to the client.
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
// Worst case is we just kill the connection before the
// notification gets to him.
stopAsync();
}
} else if (!stopping.get() && !inServiceException) {
inServiceException = true;
try {
SERVICELOG.warn("Async error occurred: ", e);
ConnectionError ce = new ConnectionError();
ce.setException(e);
if (pendingStop) {
dispatchSync(ce);
} else {
dispatchAsync(ce);
}
} finally {
inServiceException = false;
}
}
}
@Override
public Response service(Command command) {
MDC.put("activemq.connector", connector.getUri().toString());
Response response = null;
boolean responseRequired = command.isResponseRequired();
int commandId = command.getCommandId();
try {
if (!pendingStop) {
response = command.visit(this);
} else {
response = new ExceptionResponse(this.stopError);
}
} catch (Throwable e) {
if (SERVICELOG.isDebugEnabled() && e.getClass() != BrokerStoppedException.class) {
SERVICELOG.debug("Error occured while processing " + (responseRequired ? "sync" : "async")
+ " command: " + command + ", exception: " + e, e);
}
if (e instanceof SuppressReplyException || (e.getCause() instanceof SuppressReplyException)) {
LOG.info("Suppressing reply to: " + command + " on: " + e + ", cause: " + e.getCause());
responseRequired = false;
}
if (responseRequired) {
if (e instanceof SecurityException || e.getCause() instanceof SecurityException) {
SERVICELOG.warn("Security Error occurred: {}", e.getMessage());
}
response = new ExceptionResponse(e);
} else {
serviceException(e);
}
}
if (responseRequired) {
if (response == null) {
response = new Response();
}
response.setCorrelationId(commandId);
}
// The context may have been flagged so that the response is not
// sent.
if (context != null) {
if (context.isDontSendReponse()) {
context.setDontSendReponse(false);
response = null;
}
context = null;
}
MDC.remove("activemq.connector");
return response;
}
@Override
public Response processKeepAlive(KeepAliveInfo info) throws Exception {
return null;
}
@Override
public Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception {
broker.removeSubscription(lookupConnectionState(info.getConnectionId()).getContext(), info);
return null;
}
@Override
public Response processWireFormat(WireFormatInfo info) throws Exception {
wireFormatInfo = info;
protocolVersion.set(info.getVersion());
return null;
}
@Override
public Response processShutdown(ShutdownInfo info) throws Exception {
stopAsync();
return null;
}
@Override
public Response processFlush(FlushCommand command) throws Exception {
return null;
}
@Override
public Response processBeginTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = null;
if (cs != null) {
context = cs.getContext();
}
if (cs == null) {
throw new NullPointerException("Context is null");
}
// Avoid replaying dup commands
if (cs.getTransactionState(info.getTransactionId()) == null) {
cs.addTransactionState(info.getTransactionId());
broker.beginTransaction(context, info.getTransactionId());
}
return null;
}
@Override
public int getActiveTransactionCount() {
int rc = 0;
for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
Collection<TransactionState> transactions = cs.getTransactionStates();
for (TransactionState transaction : transactions) {
rc++;
}
}
return rc;
}
@Override
public Long getOldestActiveTransactionDuration() {
TransactionState oldestTX = null;
for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
Collection<TransactionState> transactions = cs.getTransactionStates();
for (TransactionState transaction : transactions) {
if( oldestTX ==null || oldestTX.getCreatedAt() < transaction.getCreatedAt() ) {
oldestTX = transaction;
}
}
}
if( oldestTX == null ) {
return null;
}
return System.currentTimeMillis() - oldestTX.getCreatedAt();
}
@Override
public Response processEndTransaction(TransactionInfo info) throws Exception {
// No need to do anything. This packet is just sent by the client
// make sure he is synced with the server as commit command could
// come from a different connection.
return null;
}
@Override
public Response processPrepareTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = null;
if (cs != null) {
context = cs.getContext();
}
if (cs == null) {
throw new NullPointerException("Context is null");
}
TransactionState transactionState = cs.getTransactionState(info.getTransactionId());
if (transactionState == null) {
throw new IllegalStateException("Cannot prepare a transaction that had not been started or previously returned XA_RDONLY: "
+ info.getTransactionId());
}
// Avoid dups.
if (!transactionState.isPrepared()) {
transactionState.setPrepared(true);
int result = broker.prepareTransaction(context, info.getTransactionId());
transactionState.setPreparedResult(result);
if (result == XAResource.XA_RDONLY) {
// we are done, no further rollback or commit from TM
cs.removeTransactionState(info.getTransactionId());
}
IntegerResponse response = new IntegerResponse(result);
return response;
} else {
IntegerResponse response = new IntegerResponse(transactionState.getPreparedResult());
return response;
}
}
@Override
public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.commitTransaction(context, info.getTransactionId(), true);
return null;
}
@Override
public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.commitTransaction(context, info.getTransactionId(), false);
return null;
}
@Override
public Response processRollbackTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.rollbackTransaction(context, info.getTransactionId());
return null;
}
@Override
public Response processForgetTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
broker.forgetTransaction(context, info.getTransactionId());
return null;
}
@Override
public Response processRecoverTransactions(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
TransactionId[] preparedTransactions = broker.getPreparedTransactions(context);
return new DataArrayResponse(preparedTransactions);
}
@Override
public Response processMessage(Message messageSend) throws Exception {
ProducerId producerId = messageSend.getProducerId();
ProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId);
if (producerExchange.canDispatch(messageSend)) {
broker.send(producerExchange, messageSend);
}
return null;
}
@Override
public Response processMessageAck(MessageAck ack) throws Exception {
ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(ack.getConsumerId());
if (consumerExchange != null) {
broker.acknowledge(consumerExchange, ack);
} else if (ack.isInTransaction()) {
LOG.warn("no matching consumer, ignoring ack {}", consumerExchange, ack);
}
return null;
}
@Override
public Response processMessagePull(MessagePull pull) throws Exception {
return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull);
}
@Override
public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception {
broker.processDispatchNotification(notification);
return null;
}
@Override
public Response processAddDestination(DestinationInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
broker.addDestinationInfo(cs.getContext(), info);
if (info.getDestination().isTemporary()) {
cs.addTempDestination(info);
}
return null;
}
@Override
public Response processRemoveDestination(DestinationInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
broker.removeDestinationInfo(cs.getContext(), info);
if (info.getDestination().isTemporary()) {
cs.removeTempDestination(info.getDestination());
}
return null;
}
@Override
public Response processAddProducer(ProducerInfo info) throws Exception {
SessionId sessionId = info.getProducerId().getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot add a producer to a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot add a producer to a session that had not been registered: "
+ sessionId);
}
// Avoid replaying dup commands
if (!ss.getProducerIds().contains(info.getProducerId())) {
ActiveMQDestination destination = info.getDestination();
if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) {
if (getProducerCount(connectionId) >= connector.getMaximumProducersAllowedPerConnection()){
throw new IllegalStateException("Can't add producer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumProducersAllowedPerConnection());
}
}
broker.addProducer(cs.getContext(), info);
try {
ss.addProducer(info);
} catch (IllegalStateException e) {
broker.removeProducer(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveProducer(ProducerId id) throws Exception {
SessionId sessionId = id.getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: "
+ sessionId);
}
ProducerState ps = ss.removeProducer(id);
if (ps == null) {
throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id);
}
removeProducerBrokerExchange(id);
broker.removeProducer(cs.getContext(), ps.getInfo());
return null;
}
@Override
public Response processAddConsumer(ConsumerInfo info) throws Exception {
SessionId sessionId = info.getConsumerId().getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot add a consumer to a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException(broker.getBrokerName()
+ " Cannot add a consumer to a session that had not been registered: " + sessionId);
}
// Avoid replaying dup commands
if (!ss.getConsumerIds().contains(info.getConsumerId())) {
ActiveMQDestination destination = info.getDestination();
if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) {
if (getConsumerCount(connectionId) >= connector.getMaximumConsumersAllowedPerConnection()){
throw new IllegalStateException("Can't add consumer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumConsumersAllowedPerConnection());
}
}
broker.addConsumer(cs.getContext(), info);
try {
ss.addConsumer(info);
addConsumerBrokerExchange(info.getConsumerId());
} catch (IllegalStateException e) {
broker.removeConsumer(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveConsumer(ConsumerId id, long lastDeliveredSequenceId) throws Exception {
SessionId sessionId = id.getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot remove a consumer from a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: "
+ sessionId);
}
ConsumerState consumerState = ss.removeConsumer(id);
if (consumerState == null) {
throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id);
}
ConsumerInfo info = consumerState.getInfo();
info.setLastDeliveredSequenceId(lastDeliveredSequenceId);
broker.removeConsumer(cs.getContext(), consumerState.getInfo());
removeConsumerBrokerExchange(id);
return null;
}
@Override
public Response processAddSession(SessionInfo info) throws Exception {
ConnectionId connectionId = info.getSessionId().getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
// Avoid replaying dup commands
if (cs != null && !cs.getSessionIds().contains(info.getSessionId())) {
broker.addSession(cs.getContext(), info);
try {
cs.addSession(info);
} catch (IllegalStateException e) {
e.printStackTrace();
broker.removeSession(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveSession(SessionId id, long lastDeliveredSequenceId) throws Exception {
ConnectionId connectionId = id.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot remove session from connection that had not been registered: " + connectionId);
}
SessionState session = cs.getSessionState(id);
if (session == null) {
throw new IllegalStateException("Cannot remove session that had not been registered: " + id);
}
// Don't let new consumers or producers get added while we are closing
// this down.
session.shutdown();
// Cascade the connection stop to the consumers and producers.
for (ConsumerId consumerId : session.getConsumerIds()) {
try {
processRemoveConsumer(consumerId, lastDeliveredSequenceId);
} catch (Throwable e) {
LOG.warn("Failed to remove consumer: {}", consumerId, e);
}
}
for (ProducerId producerId : session.getProducerIds()) {
try {
processRemoveProducer(producerId);
} catch (Throwable e) {
LOG.warn("Failed to remove producer: {}", producerId, e);
}
}
cs.removeSession(id);
broker.removeSession(cs.getContext(), session.getInfo());
return null;
}
@Override
public Response processAddConnection(ConnectionInfo info) throws Exception {
// Older clients should have been defaulting this field to true.. but
// they were not.
if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) {
info.setClientMaster(true);
}
TransportConnectionState state;
// Make sure 2 concurrent connections by the same ID only generate 1
// TransportConnectionState object.
synchronized (brokerConnectionStates) {
state = (TransportConnectionState) brokerConnectionStates.get(info.getConnectionId());
if (state == null) {
state = new TransportConnectionState(info, this);
brokerConnectionStates.put(info.getConnectionId(), state);
}
state.incrementReference();
}
// If there are 2 concurrent connections for the same connection id,
// then last one in wins, we need to sync here
// to figure out the winner.
synchronized (state.getConnectionMutex()) {
if (state.getConnection() != this) {
LOG.debug("Killing previous stale connection: {}", state.getConnection().getRemoteAddress());
state.getConnection().stop();
LOG.debug("Connection {} taking over previous connection: {}", getRemoteAddress(), state.getConnection().getRemoteAddress());
state.setConnection(this);
state.reset(info);
}
}
registerConnectionState(info.getConnectionId(), state);
LOG.debug("Setting up new connection id: {}, address: {}, info: {}", new Object[]{ info.getConnectionId(), getRemoteAddress(), info });
this.faultTolerantConnection = info.isFaultTolerant();
// Setup the context.
String clientId = info.getClientId();
context = new ConnectionContext();
context.setBroker(broker);
context.setClientId(clientId);
context.setClientMaster(info.isClientMaster());
context.setConnection(this);
context.setConnectionId(info.getConnectionId());
context.setConnector(connector);
context.setMessageAuthorizationPolicy(getMessageAuthorizationPolicy());
context.setNetworkConnection(networkConnection);
context.setFaultTolerant(faultTolerantConnection);
context.setTransactions(new ConcurrentHashMap<TransactionId, Transaction>());
context.setUserName(info.getUserName());
context.setWireFormatInfo(wireFormatInfo);
context.setReconnect(info.isFailoverReconnect());
this.manageable = info.isManageable();
context.setConnectionState(state);
state.setContext(context);
state.setConnection(this);
if (info.getClientIp() == null) {
info.setClientIp(getRemoteAddress());
}
try {
broker.addConnection(context, info);
} catch (Exception e) {
synchronized (brokerConnectionStates) {
brokerConnectionStates.remove(info.getConnectionId());
}
unregisterConnectionState(info.getConnectionId());
LOG.warn("Failed to add Connection {}", info.getConnectionId(), e);
if (e instanceof SecurityException) {
// close this down - in case the peer of this transport doesn't play nice
delayedStop(2000, "Failed with SecurityException: " + e.getLocalizedMessage(), e);
}
throw e;
}
if (info.isManageable()) {
// send ConnectionCommand
ConnectionControl command = this.connector.getConnectionControl();
command.setFaultTolerant(broker.isFaultTolerantConfiguration());
if (info.isFailoverReconnect()) {
command.setRebalanceConnection(false);
}
dispatchAsync(command);
}
return null;
}
@Override
public synchronized Response processRemoveConnection(ConnectionId id, long lastDeliveredSequenceId)
throws InterruptedException {
LOG.debug("remove connection id: {}", id);
TransportConnectionState cs = lookupConnectionState(id);
if (cs != null) {
// Don't allow things to be added to the connection state while we
// are shutting down.
cs.shutdown();
// Cascade the connection stop to the sessions.
for (SessionId sessionId : cs.getSessionIds()) {
try {
processRemoveSession(sessionId, lastDeliveredSequenceId);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove session {}", sessionId, e);
}
}
// Cascade the connection stop to temp destinations.
for (Iterator<DestinationInfo> iter = cs.getTempDestinations().iterator(); iter.hasNext(); ) {
DestinationInfo di = iter.next();
try {
broker.removeDestination(cs.getContext(), di.getDestination(), 0);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove tmp destination {}", di.getDestination(), e);
}
iter.remove();
}
try {
broker.removeConnection(cs.getContext(), cs.getInfo(), null);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove connection {}", cs.getInfo(), e);
}
TransportConnectionState state = unregisterConnectionState(id);
if (state != null) {
synchronized (brokerConnectionStates) {
// If we are the last reference, we should remove the state
// from the broker.
if (state.decrementReference() == 0) {
brokerConnectionStates.remove(id);
}
}
}
}
return null;
}
@Override
public Response processProducerAck(ProducerAck ack) throws Exception {
// A broker should not get ProducerAck messages.
return null;
}
@Override
public Connector getConnector() {
return connector;
}
@Override
public void dispatchSync(Command message) {
try {
processDispatch(message);
} catch (IOException e) {
serviceExceptionAsync(e);
}
}
@Override
public void dispatchAsync(Command message) {
if (!stopping.get()) {
if (taskRunner == null) {
dispatchSync(message);
} else {
synchronized (dispatchQueue) {
dispatchQueue.add(message);
}
try {
taskRunner.wakeup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} else {
if (message.isMessageDispatch()) {
MessageDispatch md = (MessageDispatch) message;
TransmitCallback sub = md.getTransmitCallback();
broker.postProcessDispatch(md);
if (sub != null) {
sub.onFailure();
}
}
}
}
protected void processDispatch(Command command) throws IOException {
MessageDispatch messageDispatch = (MessageDispatch) (command.isMessageDispatch() ? command : null);
try {
if (!stopping.get()) {
if (messageDispatch != null) {
broker.preProcessDispatch(messageDispatch);
}
dispatch(command);
}
} catch (IOException e) {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
broker.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onFailure();
}
messageDispatch = null;
throw e;
}
} finally {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
broker.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onSuccess();
}
}
}
}
@Override
public boolean iterate() {
try {
if (pendingStop || stopping.get()) {
if (dispatchStopped.compareAndSet(false, true)) {
if (transportException.get() == null) {
try {
dispatch(new ShutdownInfo());
} catch (Throwable ignore) {
}
}
dispatchStoppedLatch.countDown();
}
return false;
}
if (!dispatchStopped.get()) {
Command command = null;
synchronized (dispatchQueue) {
if (dispatchQueue.isEmpty()) {
return false;
}
command = dispatchQueue.remove(0);
}
processDispatch(command);
return true;
}
return false;
} catch (IOException e) {
if (dispatchStopped.compareAndSet(false, true)) {
dispatchStoppedLatch.countDown();
}
serviceExceptionAsync(e);
return false;
}
}
/**
* Returns the statistics for this connection
*/
@Override
public ConnectionStatistics getStatistics() {
return statistics;
}
public MessageAuthorizationPolicy getMessageAuthorizationPolicy() {
return messageAuthorizationPolicy;
}
public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) {
this.messageAuthorizationPolicy = messageAuthorizationPolicy;
}
@Override
public boolean isManageable() {
return manageable;
}
@Override
public void start() throws Exception {
try {
synchronized (this) {
starting = true;
if (taskRunnerFactory != null) {
taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: "
+ getRemoteAddress());
} else {
taskRunner = null;
}
transport.start();
active = true;
BrokerInfo info = connector.getBrokerInfo().copy();
if (connector.isUpdateClusterClients()) {
info.setPeerBrokerInfos(this.broker.getPeerBrokerInfos());
} else {
info.setPeerBrokerInfos(null);
}
dispatchAsync(info);
connector.onStarted(this);
}
} catch (Exception e) {
// Force clean up on an error starting up.
pendingStop = true;
throw e;
} finally {
// stop() can be called from within the above block,
// but we want to be sure start() completes before
// stop() runs, so queue the stop until right now:
setStarting(false);
if (isPendingStop()) {
LOG.debug("Calling the delayed stop() after start() {}", this);
stop();
}
}
}
@Override
public void stop() throws Exception {
// do not stop task the task runner factories (taskRunnerFactory, stopTaskRunnerFactory)
// as their lifecycle is handled elsewhere
stopAsync();
while (!stopped.await(5, TimeUnit.SECONDS)) {
LOG.info("The connection to '{}' is taking a long time to shutdown.", transport.getRemoteAddress());
}
}
public void delayedStop(final int waitTime, final String reason, Throwable cause) {
if (waitTime > 0) {
synchronized (this) {
pendingStop = true;
stopError = cause;
}
try {
stopTaskRunnerFactory.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(waitTime);
stopAsync();
LOG.info("Stopping {} because {}", transport.getRemoteAddress(), reason);
} catch (InterruptedException e) {
}
}
});
} catch (Throwable t) {
LOG.warn("Cannot create stopAsync. This exception will be ignored.", t);
}
}
}
public void stopAsync() {
// If we're in the middle of starting then go no further... for now.
synchronized (this) {
pendingStop = true;
if (starting) {
LOG.debug("stopAsync() called in the middle of start(). Delaying till start completes..");
return;
}
}
if (stopping.compareAndSet(false, true)) {
// Let all the connection contexts know we are shutting down
// so that in progress operations can notice and unblock.
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
ConnectionContext connectionContext = cs.getContext();
if (connectionContext != null) {
connectionContext.getStopping().set(true);
}
}
try {
stopTaskRunnerFactory.execute(new Runnable() {
@Override
public void run() {
serviceLock.writeLock().lock();
try {
doStop();
} catch (Throwable e) {
LOG.debug("Error occurred while shutting down a connection {}", this, e);
} finally {
stopped.countDown();
serviceLock.writeLock().unlock();
}
}
});
} catch (Throwable t) {
LOG.warn("Cannot create async transport stopper thread. This exception is ignored. Not waiting for stop to complete", t);
stopped.countDown();
}
}
}
@Override
public String toString() {
return "Transport Connection to: " + transport.getRemoteAddress();
}
protected void doStop() throws Exception {
LOG.debug("Stopping connection: {}", transport.getRemoteAddress());
connector.onStopped(this);
try {
synchronized (this) {
if (duplexBridge != null) {
duplexBridge.stop();
}
}
} catch (Exception ignore) {
LOG.trace("Exception caught stopping. This exception is ignored.", ignore);
}
try {
transport.stop();
LOG.debug("Stopped transport: {}", transport.getRemoteAddress());
} catch (Exception e) {
LOG.debug("Could not stop transport to {}. This exception is ignored.", transport.getRemoteAddress(), e);
}
if (taskRunner != null) {
taskRunner.shutdown(1);
taskRunner = null;
}
active = false;
// Run the MessageDispatch callbacks so that message references get
// cleaned up.
synchronized (dispatchQueue) {
for (Iterator<Command> iter = dispatchQueue.iterator(); iter.hasNext(); ) {
Command command = iter.next();
if (command.isMessageDispatch()) {
MessageDispatch md = (MessageDispatch) command;
TransmitCallback sub = md.getTransmitCallback();
broker.postProcessDispatch(md);
if (sub != null) {
sub.onFailure();
}
}
}
dispatchQueue.clear();
}
//
// Remove all logical connection associated with this connection
// from the broker.
if (!broker.isStopped()) {
List<TransportConnectionState> connectionStates = listConnectionStates();
connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
cs.getContext().getStopping().set(true);
try {
LOG.debug("Cleaning up connection resources: {}", getRemoteAddress());
processRemoveConnection(cs.getInfo().getConnectionId(), 0l);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}
LOG.debug("Connection Stopped: {}", getRemoteAddress());
}
/**
* @return Returns the blockedCandidate.
*/
public boolean isBlockedCandidate() {
return blockedCandidate;
}
/**
* @param blockedCandidate The blockedCandidate to set.
*/
public void setBlockedCandidate(boolean blockedCandidate) {
this.blockedCandidate = blockedCandidate;
}
/**
* @return Returns the markedCandidate.
*/
public boolean isMarkedCandidate() {
return markedCandidate;
}
/**
* @param markedCandidate The markedCandidate to set.
*/
public void setMarkedCandidate(boolean markedCandidate) {
this.markedCandidate = markedCandidate;
if (!markedCandidate) {
timeStamp = 0;
blockedCandidate = false;
}
}
/**
* @param slow The slow to set.
*/
public void setSlow(boolean slow) {
this.slow = slow;
}
/**
* @return true if the Connection is slow
*/
@Override
public boolean isSlow() {
return slow;
}
/**
* @return true if the Connection is potentially blocked
*/
public boolean isMarkedBlockedCandidate() {
return markedCandidate;
}
/**
* Mark the Connection, so we can deem if it's collectable on the next sweep
*/
public void doMark() {
if (timeStamp == 0) {
timeStamp = System.currentTimeMillis();
}
}
/**
* @return if after being marked, the Connection is still writing
*/
@Override
public boolean isBlocked() {
return blocked;
}
/**
* @return true if the Connection is connected
*/
@Override
public boolean isConnected() {
return connected;
}
/**
* @param blocked The blocked to set.
*/
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
/**
* @param connected The connected to set.
*/
public void setConnected(boolean connected) {
this.connected = connected;
}
/**
* @return true if the Connection is active
*/
@Override
public boolean isActive() {
return active;
}
/**
* @param active The active to set.
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* @return true if the Connection is starting
*/
public synchronized boolean isStarting() {
return starting;
}
@Override
public synchronized boolean isNetworkConnection() {
return networkConnection;
}
@Override
public boolean isFaultTolerantConnection() {
return this.faultTolerantConnection;
}
protected synchronized void setStarting(boolean starting) {
this.starting = starting;
}
/**
* @return true if the Connection needs to stop
*/
public synchronized boolean isPendingStop() {
return pendingStop;
}
protected synchronized void setPendingStop(boolean pendingStop) {
this.pendingStop = pendingStop;
}
@Override
public Response processBrokerInfo(BrokerInfo info) {
if (info.isSlaveBroker()) {
LOG.error(" Slave Brokers are no longer supported - slave trying to attach is: {}", info.getBrokerName());
} else if (info.isNetworkConnection() && info.isDuplexConnection()) {
// so this TransportConnection is the rear end of a network bridge
// We have been requested to create a two way pipe ...
try {
Properties properties = MarshallingSupport.stringToProperties(info.getNetworkProperties());
Map<String, String> props = createMap(properties);
NetworkBridgeConfiguration config = new NetworkBridgeConfiguration();
IntrospectionSupport.setProperties(config, props, "");
config.setBrokerName(broker.getBrokerName());
// check for existing duplex connection hanging about
// We first look if existing network connection already exists for the same broker Id and network connector name
// It's possible in case of brief network fault to have this transport connector side of the connection always active
// and the duplex network connector side wanting to open a new one
// In this case, the old connection must be broken
String duplexNetworkConnectorId = config.getName() + "@" + info.getBrokerId();
CopyOnWriteArrayList<TransportConnection> connections = this.connector.getConnections();
synchronized (connections) {
for (Iterator<TransportConnection> iter = connections.iterator(); iter.hasNext(); ) {
TransportConnection c = iter.next();
if ((c != this) && (duplexNetworkConnectorId.equals(c.getDuplexNetworkConnectorId()))) {
LOG.warn("Stopping an existing active duplex connection [{}] for network connector ({}).", c, duplexNetworkConnectorId);
c.stopAsync();
// better to wait for a bit rather than get connection id already in use and failure to start new bridge
c.getStopped().await(1, TimeUnit.SECONDS);
}
}
setDuplexNetworkConnectorId(duplexNetworkConnectorId);
}
Transport localTransport = NetworkBridgeFactory.createLocalTransport(broker);
Transport remoteBridgeTransport = transport;
if (! (remoteBridgeTransport instanceof ResponseCorrelator)) {
// the vm transport case is already wrapped
remoteBridgeTransport = new ResponseCorrelator(remoteBridgeTransport);
}
String duplexName = localTransport.toString();
if (duplexName.contains("#")) {
duplexName = duplexName.substring(duplexName.lastIndexOf("#"));
}
MBeanNetworkListener listener = new MBeanNetworkListener(broker.getBrokerService(), config, broker.getBrokerService().createDuplexNetworkConnectorObjectName(duplexName));
listener.setCreatedByDuplex(true);
duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, remoteBridgeTransport, listener);
duplexBridge.setBrokerService(broker.getBrokerService());
// now turn duplex off this side
info.setDuplexConnection(false);
duplexBridge.setCreatedByDuplex(true);
duplexBridge.duplexStart(this, brokerInfo, info);
LOG.info("Started responder end of duplex bridge {}", duplexNetworkConnectorId);
return null;
} catch (TransportDisposedIOException e) {
LOG.warn("Duplex bridge {} was stopped before it was correctly started.", duplexNetworkConnectorId);
return null;
} catch (Exception e) {
LOG.error("Failed to create responder end of duplex network bridge {}", duplexNetworkConnectorId, e);
return null;
}
}
// We only expect to get one broker info command per connection
if (this.brokerInfo != null) {
LOG.warn("Unexpected extra broker info command received: {}", info);
}
this.brokerInfo = info;
networkConnection = true;
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
cs.getContext().setNetworkConnection(true);
}
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private HashMap<String, String> createMap(Properties properties) {
return new HashMap(properties);
}
protected void dispatch(Command command) throws IOException {
try {
setMarkedCandidate(true);
transport.oneway(command);
} finally {
setMarkedCandidate(false);
}
}
@Override
public String getRemoteAddress() {
return transport.getRemoteAddress();
}
public Transport getTransport() {
return transport;
}
@Override
public String getConnectionId() {
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
if (cs.getInfo().getClientId() != null) {
return cs.getInfo().getClientId();
}
return cs.getInfo().getConnectionId().toString();
}
return null;
}
@Override
public void updateClient(ConnectionControl control) {
if (isActive() && isBlocked() == false && isFaultTolerantConnection() && this.wireFormatInfo != null
&& this.wireFormatInfo.getVersion() >= 6) {
dispatchAsync(control);
}
}
public ProducerBrokerExchange getProducerBrokerExchangeIfExists(ProducerInfo producerInfo){
ProducerBrokerExchange result = null;
if (producerInfo != null && producerInfo.getProducerId() != null){
synchronized (producerExchanges){
result = producerExchanges.get(producerInfo.getProducerId());
}
}
return result;
}
private ProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
ProducerBrokerExchange result = producerExchanges.get(id);
if (result == null) {
synchronized (producerExchanges) {
result = new ProducerBrokerExchange();
TransportConnectionState state = lookupConnectionState(id);
context = state.getContext();
result.setConnectionContext(context);
if (context.isReconnect() || (context.isNetworkConnection() && connector.isAuditNetworkProducers())) {
result.setLastStoredSequenceId(broker.getBrokerService().getPersistenceAdapter().getLastProducerSequenceId(id));
}
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
result.setProducerState(ss.getProducerState(id));
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
}
}
producerExchanges.put(id, result);
}
} else {
context = result.getConnectionContext();
}
return result;
}
private void removeProducerBrokerExchange(ProducerId id) {
synchronized (producerExchanges) {
producerExchanges.remove(id);
}
}
private ConsumerBrokerExchange getConsumerBrokerExchange(ConsumerId id) {
ConsumerBrokerExchange result = consumerExchanges.get(id);
return result;
}
private ConsumerBrokerExchange addConsumerBrokerExchange(ConsumerId id) {
ConsumerBrokerExchange result = consumerExchanges.get(id);
if (result == null) {
synchronized (consumerExchanges) {
result = new ConsumerBrokerExchange();
TransportConnectionState state = lookupConnectionState(id);
context = state.getContext();
result.setConnectionContext(context);
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
ConsumerState cs = ss.getConsumerState(id);
if (cs != null) {
ConsumerInfo info = cs.getInfo();
if (info != null) {
if (info.getDestination() != null && info.getDestination().isPattern()) {
result.setWildcard(true);
}
}
}
}
consumerExchanges.put(id, result);
}
}
return result;
}
private void removeConsumerBrokerExchange(ConsumerId id) {
synchronized (consumerExchanges) {
consumerExchanges.remove(id);
}
}
public int getProtocolVersion() {
return protocolVersion.get();
}
@Override
public Response processControlCommand(ControlCommand command) throws Exception {
String control = command.getCommand();
if (control != null && control.equals("shutdown")) {
System.exit(0);
}
return null;
}
@Override
public Response processMessageDispatch(MessageDispatch dispatch) throws Exception {
return null;
}
@Override
public Response processConnectionControl(ConnectionControl control) throws Exception {
if (control != null) {
faultTolerantConnection = control.isFaultTolerant();
}
return null;
}
@Override
public Response processConnectionError(ConnectionError error) throws Exception {
return null;
}
@Override
public Response processConsumerControl(ConsumerControl control) throws Exception {
ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(control.getConsumerId());
broker.processConsumerControl(consumerExchange, control);
return null;
}
protected synchronized TransportConnectionState registerConnectionState(ConnectionId connectionId,
TransportConnectionState state) {
TransportConnectionState cs = null;
if (!connectionStateRegister.isEmpty() && !connectionStateRegister.doesHandleMultipleConnectionStates()) {
// swap implementations
TransportConnectionStateRegister newRegister = new MapTransportConnectionStateRegister();
newRegister.intialize(connectionStateRegister);
connectionStateRegister = newRegister;
}
cs = connectionStateRegister.registerConnectionState(connectionId, state);
return cs;
}
protected synchronized TransportConnectionState unregisterConnectionState(ConnectionId connectionId) {
return connectionStateRegister.unregisterConnectionState(connectionId);
}
protected synchronized List<TransportConnectionState> listConnectionStates() {
return connectionStateRegister.listConnectionStates();
}
protected synchronized TransportConnectionState lookupConnectionState(String connectionId) {
return connectionStateRegister.lookupConnectionState(connectionId);
}
protected synchronized TransportConnectionState lookupConnectionState(ConsumerId id) {
return connectionStateRegister.lookupConnectionState(id);
}
protected synchronized TransportConnectionState lookupConnectionState(ProducerId id) {
return connectionStateRegister.lookupConnectionState(id);
}
protected synchronized TransportConnectionState lookupConnectionState(SessionId id) {
return connectionStateRegister.lookupConnectionState(id);
}
// public only for testing
public synchronized TransportConnectionState lookupConnectionState(ConnectionId connectionId) {
return connectionStateRegister.lookupConnectionState(connectionId);
}
protected synchronized void setDuplexNetworkConnectorId(String duplexNetworkConnectorId) {
this.duplexNetworkConnectorId = duplexNetworkConnectorId;
}
protected synchronized String getDuplexNetworkConnectorId() {
return this.duplexNetworkConnectorId;
}
public boolean isStopping() {
return stopping.get();
}
protected CountDownLatch getStopped() {
return stopped;
}
private int getProducerCount(ConnectionId connectionId) {
int result = 0;
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs != null) {
for (SessionId sessionId : cs.getSessionIds()) {
SessionState sessionState = cs.getSessionState(sessionId);
if (sessionState != null) {
result += sessionState.getProducerIds().size();
}
}
}
return result;
}
private int getConsumerCount(ConnectionId connectionId) {
int result = 0;
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs != null) {
for (SessionId sessionId : cs.getSessionIds()) {
SessionState sessionState = cs.getSessionState(sessionId);
if (sessionState != null) {
result += sessionState.getConsumerIds().size();
}
}
}
return result;
}
public WireFormatInfo getRemoteWireFormatInfo() {
return wireFormatInfo;
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2153_0
|
crossvul-java_data_bad_2091_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Alan Harder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.model.Run;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.MockBuilder;
/**
* Tests for hudson.tasks.BuildTrigger
* @author Alan.Harder@sun.com
*/
public class BuildTriggerTest extends HudsonTestCase {
private FreeStyleProject createDownstreamProject() throws Exception {
FreeStyleProject dp = createFreeStyleProject("downstream");
// Hm, no setQuietPeriod, have to submit form..
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(dp,"configure");
HtmlForm form = page.getFormByName("config");
form.getInputByName("hasCustomQuietPeriod").click();
form.getInputByName("quiet_period").setValueAttribute("0");
submit(form);
assertEquals("set quiet period", 0, dp.getQuietPeriod());
return dp;
}
private void doTriggerTest(boolean evenWhenUnstable, Result triggerResult,
Result dontTriggerResult) throws Exception {
FreeStyleProject p = createFreeStyleProject(),
dp = createDownstreamProject();
p.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
p.getBuildersList().add(new MockBuilder(dontTriggerResult));
jenkins.rebuildDependencyGraph();
// First build should not trigger downstream job
FreeStyleBuild b = p.scheduleBuild2(0).get();
assertNoDownstreamBuild(dp, b);
// Next build should trigger downstream job
p.getBuildersList().replace(new MockBuilder(triggerResult));
b = p.scheduleBuild2(0).get();
assertDownstreamBuild(dp, b);
}
private void assertNoDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
for (int i = 0; i < 3; i++) {
Thread.sleep(200);
assertTrue("downstream build should not run! upstream log: " + getLog(b),
!dp.isInQueue() && !dp.isBuilding() && dp.getLastBuild()==null);
}
}
private void assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
// Wait for downstream build
for (int i = 0; dp.getLastBuild()==null && i < 20; i++) Thread.sleep(100);
assertNotNull("downstream build didn't run.. upstream log: " + getLog(b), dp.getLastBuild());
}
public void testBuildTrigger() throws Exception {
doTriggerTest(false, Result.SUCCESS, Result.UNSTABLE);
}
public void testTriggerEvenWhenUnstable() throws Exception {
doTriggerTest(true, Result.UNSTABLE, Result.FAILURE);
}
private void doMavenTriggerTest(boolean evenWhenUnstable) throws Exception {
FreeStyleProject dp = createDownstreamProject();
configureDefaultMaven();
MavenModuleSet m = createMavenProject();
m.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
if (!evenWhenUnstable) {
// Configure for UNSTABLE
m.setGoals("clean test");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-test-failure.zip")));
} // otherwise do nothing which gets FAILURE
// First build should not trigger downstream project
MavenModuleSetBuild b = m.scheduleBuild2(0).get();
assertNoDownstreamBuild(dp, b);
if (evenWhenUnstable) {
// Configure for UNSTABLE
m.setGoals("clean test");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-test-failure.zip")));
} else {
// Configure for SUCCESS
m.setGoals("clean");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-empty.zip")));
}
// Next build should trigger downstream project
b = m.scheduleBuild2(0).get();
assertDownstreamBuild(dp, b);
}
public void testMavenBuildTrigger() throws Exception {
doMavenTriggerTest(false);
}
public void testMavenTriggerEvenWhenUnstable() throws Exception {
doMavenTriggerTest(true);
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2091_1
|
crossvul-java_data_good_2293_1
|
package org.uberfire.io.regex;
import java.net.URI;
import java.util.Collection;
import org.uberfire.java.nio.file.Path;
import static org.uberfire.commons.validation.Preconditions.*;
public final class AntPathMatcher {
private static org.uberfire.commons.regex.util.AntPathMatcher matcher = new org.uberfire.commons.regex.util.AntPathMatcher();
public static boolean filter( final Collection<String> includes,
final Collection<String> excludes,
final Path path ) {
checkNotNull( "includes", includes );
checkNotNull( "excludes", excludes );
checkNotNull( "path", path );
if ( includes.isEmpty() && excludes.isEmpty() ) {
return true;
} else if ( includes.isEmpty() ) {
return !( excludes( excludes, path ) );
} else if ( excludes.isEmpty() ) {
return includes( includes, path );
}
return includes( includes, path ) && !( excludes( excludes, path ) );
}
public static boolean filter( final Collection<String> includes,
final Collection<String> excludes,
final URI uri ) {
checkNotNull( "includes", includes );
checkNotNull( "excludes", excludes );
checkNotNull( "uri", uri );
if ( includes.isEmpty() && excludes.isEmpty() ) {
return true;
} else if ( includes.isEmpty() ) {
return !( excludes( excludes, uri ) );
} else if ( excludes.isEmpty() ) {
return includes( includes, uri );
}
return includes( includes, uri ) && !( excludes( excludes, uri ) );
}
public static boolean includes( final Collection<String> patterns,
final Path path ) {
checkNotNull( "patterns", patterns );
checkNotNull( "path", path );
return matches( patterns, path );
}
public static boolean includes( final Collection<String> patterns,
final URI uri ) {
checkNotNull( "patterns", patterns );
checkNotNull( "uri", uri );
return matches( patterns, uri );
}
public static boolean excludes( final Collection<String> patterns,
final URI uri ) {
checkNotNull( "patterns", patterns );
checkNotNull( "uri", uri );
return matches( patterns, uri );
}
public static boolean excludes( final Collection<String> patterns,
final Path path ) {
checkNotNull( "patterns", patterns );
checkNotNull( "path", path );
return matches( patterns, path );
}
private static boolean matches( final Collection<String> patterns,
final Path path ) {
return matches( patterns, path.toUri() );
}
private static boolean matches( final Collection<String> patterns,
final URI uri ) {
for ( final String pattern : patterns ) {
if ( matcher.match( pattern, uri.toString() ) ) {
return true;
}
}
return false;
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2293_1
|
crossvul-java_data_good_4708_0
|
package org.orbeon.oxf.xml.xerces;
import org.orbeon.oxf.common.OXFException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.*;
/**
* Boasts a couple of improvements over the 'stock' xerces parser factory.
*
* o Doesn't create a new parser every time one calls setFeature or getFeature. Stock one
* has to do this because valid feature set is encapsulated in the parser code.
*
* o Creates a XercesJAXPSAXParser instead of SaxParserImpl. See XercesJAXPSAXParser for
* why this is an improvement.
*
* o The improvements cut the time it takes to a SAX parser via JAXP in
* half and reduce the amount of garbage created when accessing '/' in
* the examples app from 9019216 bytes to 8402880 bytes.
*/
public class XercesSAXParserFactoryImpl extends SAXParserFactory {
private static final Collection recognizedFeaturesNonValidatingXInclude;
private static final Map defaultFeaturesNonValidatingXInclude;
private static final Collection recognizedFeaturesNonValidatingNoXInclude;
private static final Map defaultFeaturesNonValidatingNoXInclude;
private static final Collection recognizedFeaturesValidatingXInclude;
private static final Map defaultFeaturesValidatingXInclude;
private static final Collection recognizedFeaturesValidatingNoXInclude;
private static final Map defaultFeaturesValidatingNoXInclude;
static {
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(false, true);
final Collection recognizedFeatures = configuration.getRecognizedFeatures();
recognizedFeaturesNonValidatingXInclude = Collections.unmodifiableCollection(recognizedFeatures);
defaultFeaturesNonValidatingXInclude = configuration.getFeatures();
addDefaultFeatures(defaultFeaturesNonValidatingXInclude);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(false, false);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesNonValidatingNoXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesNonValidatingNoXInclude = configuration.getFeatures();
addDefaultFeatures(defaultFeaturesNonValidatingNoXInclude);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(true, true);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesValidatingXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesValidatingXInclude = configuration.getFeatures();
addDefaultFeatures(defaultFeaturesValidatingXInclude);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(true, false);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesValidatingNoXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesValidatingNoXInclude = configuration.getFeatures();
addDefaultFeatures(defaultFeaturesValidatingNoXInclude);
}
}
private static void addDefaultFeatures(Map features) {
features.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
features.put("http://xml.org/sax/features/namespace-prefixes", Boolean.FALSE);
// For security purposes, disable external entities
features.put("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
features.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
}
private final Hashtable features;
private final boolean validating;
private final boolean handleXInclude;
public XercesSAXParserFactoryImpl() {
this(false, false);
}
public XercesSAXParserFactoryImpl(boolean validating, boolean handleXInclude) {
this.validating = validating;
this.handleXInclude = handleXInclude;
if (!validating) {
features = new Hashtable(handleXInclude ? defaultFeaturesNonValidatingXInclude : defaultFeaturesNonValidatingNoXInclude);
} else {
features = new Hashtable(handleXInclude ? defaultFeaturesValidatingXInclude : defaultFeaturesValidatingNoXInclude);
}
setNamespaceAware(true); // this is needed by some tools in addition to the feature
}
public boolean getFeature(final String key) throws SAXNotRecognizedException {
if (!getRecognizedFeatures().contains(key)) throw new SAXNotRecognizedException(key);
return features.get(key) == Boolean.TRUE;
}
public void setFeature(final String key, final boolean val) throws SAXNotRecognizedException {
if (!getRecognizedFeatures().contains(key)) throw new SAXNotRecognizedException(key);
features.put(key, val ? Boolean.TRUE : Boolean.FALSE);
}
public SAXParser newSAXParser() {
final SAXParser ret;
try {
ret = new XercesJAXPSAXParser(this, features, validating, handleXInclude);
} catch (final SAXException se) {
// Translate to ParserConfigurationException
throw new OXFException(se); // so we see a decent stack trace!
}
return ret;
}
private Collection getRecognizedFeatures() {
if (!validating) {
return handleXInclude ? recognizedFeaturesNonValidatingXInclude : recognizedFeaturesNonValidatingNoXInclude;
} else {
return handleXInclude ? recognizedFeaturesValidatingXInclude : recognizedFeaturesValidatingNoXInclude;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4708_0
|
crossvul-java_data_bad_2091_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
* Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
* id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques
* Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.EnvVars;
import hudson.Functions;
import antlr.ANTLRException;
import hudson.AbortException;
import hudson.CopyOnWrite;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.SubTask;
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTaskContributor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.slaves.WorkspaceList;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import jenkins.util.TimeDuration;
import net.sf.json.JSONObject;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
*/
private volatile SCM scm = new NullSCM();
/**
* Controls how the checkout is done.
*/
private volatile SCMCheckoutStrategy scmCheckoutStrategy;
/**
* State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
*/
private volatile transient SCMRevisionState pollingBaseline = null;
/**
* All the builds keyed by their build number.
*
* External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
* {@link Run#getPreviousBuild()}
*/
@Restricted(NoExternalUse.class)
@SuppressWarnings("deprecation") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
protected transient RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
*/
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
*/
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when downstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenDownstreamBuilding = false;
/**
* True to keep builds of this project in queue when upstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenUpstreamBuilding = false;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
* are saved independently.
*
* @see Jenkins#getJDK(String)
*/
private volatile String jdk;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
private boolean concurrentBuild;
/**
* See {@link #setCustomWorkspace(String)}.
*
* @since 1.410
*/
private String customWorkspace;
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
if(!Jenkins.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public synchronized void save() throws IOException {
super.save();
updateTransientActions();
}
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
builds = createBuildRunMap();
// solicit initial contributions, especially from TransientProjectActionFactory
updateTransientActions();
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
RunMap<R> builds = createBuildRunMap();
RunMap<R> currentBuilds = this.builds;
if (currentBuilds==null) {
// are we overwriting what currently exist?
// this is primarily when Jenkins is getting reloaded
Item current = parent.getItem(name);
if (current!=null && current.getClass()==getClass()) {
currentBuilds = ((AbstractProject)current).builds;
}
}
if (currentBuilds !=null) {
// if we are reloading, keep all those that are still building intact
for (R r : currentBuilds.getLoadedBuilds().values()) {
if (r.isBuilding())
builds.put(r);
}
}
this.builds = builds;
for (Trigger t : triggers())
t.start(this, Items.updatingByXml.get());
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
}
private RunMap<R> createBuildRunMap() {
return new RunMap<R>(getBuildDir(), new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
}
private synchronized List<Trigger<?>> triggers() {
if (triggers == null) {
triggers = new Vector<Trigger<?>>();
}
return triggers;
}
@Override
public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(node, listener);
JDK jdk = getJDK();
if (jdk != null) {
if (node != null) { // just in case were not in a build
jdk = jdk.forNode(node, listener);
}
jdk.buildEnvVars(env);
}
return env;
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
@Exported
public boolean isConcurrentBuild() {
return concurrentBuild;
}
public void setConcurrentBuild(boolean b) throws IOException {
concurrentBuild = b;
save();
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Jenkins.getInstance().getSelfLabel();
return Jenkins.getInstance().getLabel(assignedNode);
}
/**
* Set of labels relevant to this job.
*
* This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.
* It does not affect the scheduling. This information is informational and the best-effort basis.
*
* @since 1.456
* @return
* Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element
* to correspond to the null return value from {@link #getAssignedLabel()}.
*/
public Set<Label> getRelevantLabels() {
return Collections.singleton(getAssignedLabel());
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (canRoam || assignedNode==null) return null;
try {
LabelExpression.parseExpression(assignedNode);
return assignedNode;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(assignedNode);
}
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getExpression();
}
save();
}
/**
* Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
*/
public void setAssignedNode(Node l) throws IOException {
setAssignedLabel(l.getSelfLabel());
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
}
/**
* Gets the human readable display name to be rendered in the "Build Now" link.
*
* @since 1.401
*/
public String getBuildNowText() {
return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
}
/**
* Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
*
* <p>
* Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs
* that acts as a single unit. This method can be used to find the top most dominating job that
* covers such a tree.
*
* @return never null.
* @see AbstractBuild#getRootBuild()
*/
public AbstractProject<?,?> getRootProject() {
if (this instanceof TopLevelItem) {
return this;
} else {
ItemGroup p = this.getParent();
if (p instanceof AbstractProject)
return ((AbstractProject) p).getRootProject();
return this;
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
}
/**
* Various deprecated methods in this class all need the 'current' build. This method returns
* the build suitable for that purpose.
*
* @return An AbstractBuild for deprecated methods to use.
*/
private AbstractBuild getBuildForDeprecatedMethods() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b;
}
}
R lb = getLastBuild();
if(lb!=null) return lb;
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
if (b!=null) return b.getWorkspace();
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
FilePath f = browser.getWorkspace(this);
if (f != null) return f;
}
return null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
}
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
}
public SCMCheckoutStrategy getScmCheckoutStrategy() {
return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
}
public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
this.scmCheckoutStrategy = scmCheckoutStrategy;
save();
}
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
}
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return quietPeriod!=null;
}
/**
* Sets the custom quiet period of this project, or revert to the global default if null is given.
*/
public void setQuietPeriod(Integer seconds) throws IOException {
this.quietPeriod = seconds;
save();
}
public boolean hasCustomScmCheckoutRetryCount(){
return scmCheckoutRetryCount != null;
}
@Override
public boolean isBuildable() {
return !isDisabled() && !isHoldOffBuildUntilSave();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenDownstreamBuilding() {
return blockBuildWhenDownstreamBuilding;
}
public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
blockBuildWhenDownstreamBuilding = b;
save();
}
public boolean blockBuildWhenUpstreamBuilding() {
return blockBuildWhenUpstreamBuilding;
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
blockBuildWhenUpstreamBuilding = b;
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Jenkins.getInstance().getQueue().cancel(this);
save();
}
/**
* Specifies whether this project may be disabled by the user.
* By default, it can be only if this is a {@link TopLevelItem};
* would be false for matrix configurations, etc.
* @return true if the GUI should allow {@link #doDisable} and the like
* @since 1.475
*/
public boolean supportsMakeDisabled() {
return this instanceof TopLevelItem;
}
public void disable() throws IOException {
makeDisabled(true);
}
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
/**
* effectively deprecated. Since using updateTransientActions correctly
* under concurrent environment requires a lock that can too easily cause deadlocks.
*
* <p>
* Override {@link #createTransientActions()} instead.
*/
protected void updateTransientActions() {
transientActions = createTransientActions();
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
for (JobProperty<? super P> p : Util.fixNull(properties))
ta.addAll(p.getJobActions((P)this));
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
return ta;
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
updateTransientActions();
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Jenkins.getInstance().rebuildDependencyGraph();
convertUpstreamBuildTrigger(upstream);
// notify the queue as the project might be now tied to different node
Jenkins.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Jenkins.getInstance().rebuildDependencyGraph();
}
/**
* Reflect the submission of the pseudo 'upstream build trigger'.
*/
/* package */ void convertUpstreamBuildTrigger(Set<AbstractProject> upstream) throws IOException {
SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
try {
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list. For us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects(p));
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(p,newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null? Result.SUCCESS:existing.getThreshold()));
}
}
}
} finally {
SecurityContextHolder.setContext(saveCtx);
}
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this array can contain null, and those will be silently ignored.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this collection can contain null, and those will be silently ignored.
* @since 1.383
*/
@SuppressWarnings("unchecked")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
if (!isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (QueueTaskFuture)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
@SuppressWarnings("deprecation")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Jenkins.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Jenkins.getInstance().getQueue().getItem(this);
}
/**
* Gets the JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Jenkins.getInstance().getJDK(jdk);
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
this.jdk = jdk.getName();
save();
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
@Override
public RunMap<R> _getRuns() {
assert builds.baseDirInitialized() : "neither onCreatedFromScratch nor onLoad called on " + this + " yet";
return builds;
}
@Override
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuild(String id) {
return builds.getById(id);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuildByNumber(int n) {
return builds.getByNumber(n);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getFirstBuild() {
return builds.oldestBuild();
}
@Override
public R getLastBuild() {
return builds.newestBuild();
}
@Override
public R getNearestBuild(int n) {
return builds.search(n, Direction.ASC);
}
@Override
public R getNearestOldBuild(int n) {
return builds.search(n, Direction.DESC);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
public Object getSameNodeConstraint() {
return this; // in this way, any member that wants to run with the main guy can nominate the project itself
}
public final Task getOwnerTask() {
return this;
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the downstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
// Block builds until they are done with post-production
if (isLogUpdated() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenDownstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingDownstream();
if (bup!=null)
return new BecauseOfDownstreamBuildInProgress(bup);
}
if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the downstream project is either
* building, waiting, pending or buildable.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingDownstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveDownstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
/**
* Returns the project if any of the upstream project is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingUpstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveUpstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
for (JobProperty<? super P> p : properties)
r.addAll(p.getSubTasks());
return r;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
if (r) {
// Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations
// won't reach this line anyway, as they throw AbortExceptions on checkout failure.
calcPollingBaseline(build, launcher, listener);
}
return r;
}
/**
* Pushes the baseline up to the newly checked out revision.
*/
private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
if (baseline==null) {
try {
baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
} catch (AbstractMethodError e) {
baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
}
if (baseline!=null)
build.addAction(baseline);
}
pollingBaseline = baseline;
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The implementation is responsible for ensuring mutual exclusion between polling and builds
* if necessary.
*
* @since 1.345
*/
public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (!isBuildable()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
SCMPollListener.fireBeforePolling(this, listener);
PollingResult r = _poll(listener, scm, lb);
SCMPollListener.firePollingSuccess(this,listener, r);
return r;
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (RuntimeException e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
} catch (Error e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
}
}
/**
* {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
*/
private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
if ( workspaceOfflineReason != null ) {
// workspace offline
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
ws = browser.getWorkspace(this);
if (ws != null) {
return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
}
}
// build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().print(Messages.AbstractProject_NoWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return BUILD_NOW;
}
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
return pollWithWorkspace(listener, scm, lb, ws, l);
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
}
private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
enum WorkspaceOfflineReason {
nonexisting_workspace,
builton_node_gone,
builton_node_no_executors
}
private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {
FilePath ws = build.getWorkspace();
if (ws==null || !ws.exists()) {
return WorkspaceOfflineReason.nonexisting_workspace;
}
Node builtOn = build.getBuiltOn();
if (builtOn == null) { // node built-on doesn't exist anymore
return WorkspaceOfflineReason.builton_node_gone;
}
if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
return WorkspaceOfflineReason.builton_node_no_executors;
}
return null;
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
@Exported
public SCM getScm() {
return scm;
}
public void setScm(SCM scm) throws IOException {
this.scm = scm;
save();
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
public void addTrigger(Trigger<?> trigger) throws IOException {
addToList(trigger,triggers());
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
removeFromList(trigger,triggers());
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i,item);
save();
return;
}
}
// add
collection.add(item);
save();
updateTransientActions();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
updateTransientActions();
return;
}
}
}
@SuppressWarnings("unchecked")
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(triggers());
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : triggers()) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects(ap).contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {
if (delay==null) delay=new TimeDuration(getQuietPeriod());
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
if (pp != null) {
pp._doBuild(req,rsp,delay);
return;
}
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));
rsp.sendRedirect(".");
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
/*package*/ CauseAction getBuildCause(StaplerRequest req) {
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserIdCause();
}
return new CauseAction(cause);
}
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*
* @deprecated as of 1.488
* Inject {@link TimeDuration}.
*/
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
return Integer.parseInt(delay);
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp,delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.sendRedirect(".");
}
/**
* Cancels a scheduled build.
*/
@RequirePOST
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ABORT);
Jenkins.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
/**
* Deletes this project.
*/
@Override
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
delete();
if (req == null || rsp == null)
return;
View view = req.findAncestorObject(View.class);
if (view == null)
rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());
else
rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
makeDisabled(req.getParameter("disable")!=null);
jdk = req.getParameter("jdk");
if(req.getParameter("hasCustomQuietPeriod")!=null) {
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
} else {
quietPeriod = null;
}
if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
} else {
scmCheckoutRetryCount = null;
}
blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;
if(req.hasParameter("customWorkspace")) {
customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
} else {
customWorkspace = null;
}
if (json.has("scmCheckoutStrategy"))
scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,
json.getJSONObject("scmCheckoutStrategy"));
else
scmCheckoutStrategy = null;
if(req.getParameter("hasSlaveAffinity")!=null) {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
} else {
assignedNode = null;
}
canRoam = assignedNode==null;
concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
for (Trigger t : triggers())
t.stop();
triggers = buildDescribable(req, Trigger.for_(this));
for (Trigger t : triggers)
t.start(this,true);
for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
BuildTrigger t = (BuildTrigger) _t;
for (AbstractProject downstream : t.getChildProjects(this)) {
downstream.checkPermission(BUILD);
}
}
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
T instance = d.newInstance(req, data.getJSONObject(safeName));
r.add(instance);
}
}
return r;
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
// Would be good if when asked for *plain*, do something else!
// (E.g. return 404, or send empty doc.)
// Not critical; client can just check if content type is not text/plain,
// which also serves to detect old versions of Hudson.
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b!=null ? b.getWorkspace() : null;
if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
for (WorkspaceListener wl : WorkspaceListener.all()) {
wl.afterDelete(this);
}
return new HttpRedirect(".");
} else {
// If we get here, that means the SCM blocked the workspace deletion.
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
@CLIMethod(name="disable-job")
@RequirePOST
public HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
@RequirePOST
public HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return JenkinsLocationConfiguration.get().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
if (Util.fixEmpty(value)==null)
return FormValidation.ok(); // nothing typed yet
try {
Label.parseExpression(value);
} catch (ANTLRException e) {
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
Label l = Jenkins.getInstance().getLabel(value);
if (l.isEmpty()) {
for (LabelAtom a : l.listAtoms()) {
if (a.isEmpty()) {
LabelAtom nearest = LabelAtom.findNearest(a.getName());
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));
}
}
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
}
return FormValidation.ok();
}
public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
if(Util.fixEmptyAndTrim(customWorkspace)==null)
return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
else
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
AutoCompletionCandidates candidates = new AutoCompletionCandidates();
List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
for (Job job: jobs) {
if (job.getFullName().startsWith(value)) {
if (job.hasPermission(Item.READ)) {
candidates.add(job.getFullName());
}
}
}
return candidates;
}
public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
AutoCompletionCandidates c = new AutoCompletionCandidates();
Set<Label> labels = Jenkins.getInstance().getLabels();
List<String> queries = new AutoCompleteSeeder(value).getSeeds();
for (String term : queries) {
for (Label l : labels) {
if (l.getName().startsWith(term)) {
c.add(l.getName());
}
}
}
return c;
}
public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
return SCMCheckoutStrategyDescriptor._for(p);
}
/**
* Utility class for taking the current input value and computing a list
* of potential terms to match against the list of defined labels.
*/
static class AutoCompleteSeeder {
private String source;
AutoCompleteSeeder(String source) {
this.source = source;
}
List<String> getSeeds() {
ArrayList<String> terms = new ArrayList<String>();
boolean trailingQuote = source.endsWith("\"");
boolean leadingQuote = source.startsWith("\"");
boolean trailingSpace = source.endsWith(" ");
if (trailingQuote || (trailingSpace && !leadingQuote)) {
terms.add("");
} else {
if (leadingQuote) {
int quote = source.lastIndexOf('"');
if (quote == 0) {
terms.add(source.substring(1));
} else {
terms.add("");
}
} else {
int space = source.lastIndexOf(' ');
if (space > -1) {
terms.add(source.substring(space+1));
} else {
terms.add(source);
}
}
}
return terms;
}
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
return findNearest(name,Hudson.getInstance());
}
/**
* Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
*
* @since 1.419
*/
public static AbstractProject findNearest(String name, ItemGroup context) {
List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getRelativeNameFrom(context);
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build
*/
public static final Permission ABORT = CANCEL;
/**
* Replaceable "Build Now" text.
*/
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();
/**
* Used for CLI binding.
*/
@CLIResolver
public static AbstractProject resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
if (item==null)
throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
return item;
}
public String getCustomWorkspace() {
return customWorkspace;
}
/**
* User-specified workspace directory, or null if it's up to Jenkins.
*
* <p>
* Normally a project uses the workspace location assigned by its parent container,
* but sometimes people have builds that have hard-coded paths.
*
* <p>
* This is not {@link File} because it may have to hold a path representation on another OS.
*
* <p>
* If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace
* is prepared.
*
* @since 1.410
*/
public void setCustomWorkspace(String customWorkspace) throws IOException {
this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
save();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2091_0
|
crossvul-java_data_bad_2293_3
|
/*
* Copyright 2012 JBoss Inc
*
* Licensed 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.uberfire.security.server;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.uberfire.security.Resource;
import org.uberfire.security.ResourceManager;
import org.uberfire.security.Role;
import org.uberfire.security.impl.RoleImpl;
import org.uberfire.security.server.util.AntPathMatcher;
import org.yaml.snakeyaml.Yaml;
import static java.util.Collections.*;
import static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;
import static org.uberfire.commons.validation.Preconditions.*;
import static org.uberfire.security.server.SecurityConstants.*;
public class URLResourceManager implements ResourceManager {
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
private static final Collection<Class<? extends Resource>> SUPPORTED_TYPES = new ArrayList<Class<? extends Resource>>( 1 ) {{
add( URLResource.class );
}};
private static final String DEFAULT_CONFIG = "exclude:\n" +
" - /*.ico\n" +
" - /image/**\n" +
" - /css/**";
private String configFile = URL_FILTER_CONFIG_YAML;
private final Resources resources;
private final Set<String> excludeCache = Collections.newSetFromMap( new ConcurrentHashMap<String, Boolean>() );
public URLResourceManager( final String configFile ) {
if ( configFile != null && !configFile.isEmpty() ) {
this.configFile = configFile;
}
this.resources = loadConfigData();
}
private Resources loadConfigData() {
final Yaml yaml = new Yaml();
final InputStream stream = URLResourceManager.class.getClassLoader().getResourceAsStream( this.configFile );
final Map result;
if ( stream != null ) {
result = (Map) yaml.load( stream );
} else {
result = (Map) yaml.load( DEFAULT_CONFIG );
}
return new Resources( result );
}
@Override
public boolean supports( final Resource resource ) {
if ( resource instanceof URLResource ) {
return true;
}
return false;
}
@Override
public boolean requiresAuthentication( final Resource resource ) {
final URLResource urlResource;
try {
urlResource = checkInstanceOf( "context", resource, URLResource.class );
} catch ( IllegalArgumentException e ) {
return false;
}
if ( !excludeCache.contains( urlResource.getURL() ) ) {
boolean isExcluded = false;
for ( String excluded : resources.getExcludedResources() ) {
if ( ANT_PATH_MATCHER.match( excluded, urlResource.getURL() ) ) {
isExcluded = true;
excludeCache.add( urlResource.getURL() );
break;
}
}
if ( isExcluded ) {
return false;
}
} else {
return false;
}
return true;
}
public List<Role> getMandatoryRoles( final URLResource urlResource ) {
for ( Map.Entry<String, List<Role>> activeFilteredResource : resources.getMandatoryFilteredResources().entrySet() ) {
if ( ANT_PATH_MATCHER.match( activeFilteredResource.getKey(), urlResource.getURL() ) ) {
return activeFilteredResource.getValue();
}
}
return emptyList();
}
private static class Resources {
private final Map<String, List<Role>> filteredResources;
private final Map<String, List<Role>> mandatoryFilteredResources;
private final Set<String> excludedResources;
private Resources( final Map yaml ) {
checkNotNull( "yaml", yaml );
final Object ofilter = yaml.get( "filter" );
if ( ofilter != null ) {
final List<Map<String, String>> filter = checkInstanceOf( "ofilter", ofilter, List.class );
this.filteredResources = new HashMap<String, List<Role>>( filter.size() );
this.mandatoryFilteredResources = new HashMap<String, List<Role>>( filter.size() );
for ( final Map<String, String> activeFilter : filter ) {
final String pattern = activeFilter.get( "pattern" );
final String access = activeFilter.get( "access" );
checkNotNull( "pattern", pattern );
final List<Role> roles;
if ( access != null ) {
final String[] textRoles = access.split( "," );
roles = new ArrayList<Role>( textRoles.length );
for ( final String textRole : textRoles ) {
roles.add( new RoleImpl( textRole ) );
}
mandatoryFilteredResources.put( pattern, roles );
} else {
roles = emptyList();
}
filteredResources.put( pattern, roles );
}
} else {
this.filteredResources = emptyMap();
this.mandatoryFilteredResources = emptyMap();
}
final Object oexclude = yaml.get( "exclude" );
final List exclude = checkInstanceOf( "exclude", oexclude, List.class );
this.excludedResources = new HashSet<String>( exclude );
}
public Map<String, List<Role>> getFilteredResources() {
return filteredResources;
}
public Set<String> getExcludedResources() {
return excludedResources;
}
public Map<String, List<Role>> getMandatoryFilteredResources() {
return mandatoryFilteredResources;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2293_3
|
crossvul-java_data_good_2091_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
* Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
* id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques
* Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.EnvVars;
import hudson.Functions;
import antlr.ANTLRException;
import hudson.AbortException;
import hudson.CopyOnWrite;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.SubTask;
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTaskContributor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.slaves.WorkspaceList;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import jenkins.util.TimeDuration;
import net.sf.json.JSONObject;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
*/
private volatile SCM scm = new NullSCM();
/**
* Controls how the checkout is done.
*/
private volatile SCMCheckoutStrategy scmCheckoutStrategy;
/**
* State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
*/
private volatile transient SCMRevisionState pollingBaseline = null;
/**
* All the builds keyed by their build number.
*
* External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
* {@link Run#getPreviousBuild()}
*/
@Restricted(NoExternalUse.class)
@SuppressWarnings("deprecation") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
protected transient RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
*/
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
*/
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when downstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenDownstreamBuilding = false;
/**
* True to keep builds of this project in queue when upstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenUpstreamBuilding = false;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
* are saved independently.
*
* @see Jenkins#getJDK(String)
*/
private volatile String jdk;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
private boolean concurrentBuild;
/**
* See {@link #setCustomWorkspace(String)}.
*
* @since 1.410
*/
private String customWorkspace;
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
if(!Jenkins.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public synchronized void save() throws IOException {
super.save();
updateTransientActions();
}
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
builds = createBuildRunMap();
// solicit initial contributions, especially from TransientProjectActionFactory
updateTransientActions();
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
RunMap<R> builds = createBuildRunMap();
RunMap<R> currentBuilds = this.builds;
if (currentBuilds==null) {
// are we overwriting what currently exist?
// this is primarily when Jenkins is getting reloaded
Item current = parent.getItem(name);
if (current!=null && current.getClass()==getClass()) {
currentBuilds = ((AbstractProject)current).builds;
}
}
if (currentBuilds !=null) {
// if we are reloading, keep all those that are still building intact
for (R r : currentBuilds.getLoadedBuilds().values()) {
if (r.isBuilding())
builds.put(r);
}
}
this.builds = builds;
for (Trigger t : triggers())
t.start(this, Items.updatingByXml.get());
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
}
private RunMap<R> createBuildRunMap() {
return new RunMap<R>(getBuildDir(), new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
}
private synchronized List<Trigger<?>> triggers() {
if (triggers == null) {
triggers = new Vector<Trigger<?>>();
}
return triggers;
}
@Override
public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(node, listener);
JDK jdk = getJDK();
if (jdk != null) {
if (node != null) { // just in case were not in a build
jdk = jdk.forNode(node, listener);
}
jdk.buildEnvVars(env);
}
return env;
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
@Exported
public boolean isConcurrentBuild() {
return concurrentBuild;
}
public void setConcurrentBuild(boolean b) throws IOException {
concurrentBuild = b;
save();
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Jenkins.getInstance().getSelfLabel();
return Jenkins.getInstance().getLabel(assignedNode);
}
/**
* Set of labels relevant to this job.
*
* This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.
* It does not affect the scheduling. This information is informational and the best-effort basis.
*
* @since 1.456
* @return
* Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element
* to correspond to the null return value from {@link #getAssignedLabel()}.
*/
public Set<Label> getRelevantLabels() {
return Collections.singleton(getAssignedLabel());
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (canRoam || assignedNode==null) return null;
try {
LabelExpression.parseExpression(assignedNode);
return assignedNode;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(assignedNode);
}
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getExpression();
}
save();
}
/**
* Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
*/
public void setAssignedNode(Node l) throws IOException {
setAssignedLabel(l.getSelfLabel());
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
}
/**
* Gets the human readable display name to be rendered in the "Build Now" link.
*
* @since 1.401
*/
public String getBuildNowText() {
return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
}
/**
* Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
*
* <p>
* Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs
* that acts as a single unit. This method can be used to find the top most dominating job that
* covers such a tree.
*
* @return never null.
* @see AbstractBuild#getRootBuild()
*/
public AbstractProject<?,?> getRootProject() {
if (this instanceof TopLevelItem) {
return this;
} else {
ItemGroup p = this.getParent();
if (p instanceof AbstractProject)
return ((AbstractProject) p).getRootProject();
return this;
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
}
/**
* Various deprecated methods in this class all need the 'current' build. This method returns
* the build suitable for that purpose.
*
* @return An AbstractBuild for deprecated methods to use.
*/
private AbstractBuild getBuildForDeprecatedMethods() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b;
}
}
R lb = getLastBuild();
if(lb!=null) return lb;
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
if (b!=null) return b.getWorkspace();
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
FilePath f = browser.getWorkspace(this);
if (f != null) return f;
}
return null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
}
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
}
public SCMCheckoutStrategy getScmCheckoutStrategy() {
return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
}
public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
this.scmCheckoutStrategy = scmCheckoutStrategy;
save();
}
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
}
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return quietPeriod!=null;
}
/**
* Sets the custom quiet period of this project, or revert to the global default if null is given.
*/
public void setQuietPeriod(Integer seconds) throws IOException {
this.quietPeriod = seconds;
save();
}
public boolean hasCustomScmCheckoutRetryCount(){
return scmCheckoutRetryCount != null;
}
@Override
public boolean isBuildable() {
return !isDisabled() && !isHoldOffBuildUntilSave();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenDownstreamBuilding() {
return blockBuildWhenDownstreamBuilding;
}
public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
blockBuildWhenDownstreamBuilding = b;
save();
}
public boolean blockBuildWhenUpstreamBuilding() {
return blockBuildWhenUpstreamBuilding;
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
blockBuildWhenUpstreamBuilding = b;
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Jenkins.getInstance().getQueue().cancel(this);
save();
}
/**
* Specifies whether this project may be disabled by the user.
* By default, it can be only if this is a {@link TopLevelItem};
* would be false for matrix configurations, etc.
* @return true if the GUI should allow {@link #doDisable} and the like
* @since 1.475
*/
public boolean supportsMakeDisabled() {
return this instanceof TopLevelItem;
}
public void disable() throws IOException {
makeDisabled(true);
}
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
/**
* effectively deprecated. Since using updateTransientActions correctly
* under concurrent environment requires a lock that can too easily cause deadlocks.
*
* <p>
* Override {@link #createTransientActions()} instead.
*/
protected void updateTransientActions() {
transientActions = createTransientActions();
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
for (JobProperty<? super P> p : Util.fixNull(properties))
ta.addAll(p.getJobActions((P)this));
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
return ta;
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
updateTransientActions();
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Jenkins.getInstance().rebuildDependencyGraph();
convertUpstreamBuildTrigger(upstream);
// notify the queue as the project might be now tied to different node
Jenkins.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Jenkins.getInstance().rebuildDependencyGraph();
}
/**
* Reflect the submission of the pseudo 'upstream build trigger'.
*/
/* package */ void convertUpstreamBuildTrigger(Set<AbstractProject> upstream) throws IOException {
SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
try {
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list. For us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects(p));
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(p,newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null? Result.SUCCESS:existing.getThreshold()));
}
}
}
} finally {
SecurityContextHolder.setContext(saveCtx);
}
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this array can contain null, and those will be silently ignored.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this collection can contain null, and those will be silently ignored.
* @since 1.383
*/
@SuppressWarnings("unchecked")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
if (!isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (QueueTaskFuture)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
@SuppressWarnings("deprecation")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Jenkins.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Jenkins.getInstance().getQueue().getItem(this);
}
/**
* Gets the JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Jenkins.getInstance().getJDK(jdk);
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
this.jdk = jdk.getName();
save();
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
@Override
public RunMap<R> _getRuns() {
assert builds.baseDirInitialized() : "neither onCreatedFromScratch nor onLoad called on " + this + " yet";
return builds;
}
@Override
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuild(String id) {
return builds.getById(id);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuildByNumber(int n) {
return builds.getByNumber(n);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getFirstBuild() {
return builds.oldestBuild();
}
@Override
public R getLastBuild() {
return builds.newestBuild();
}
@Override
public R getNearestBuild(int n) {
return builds.search(n, Direction.ASC);
}
@Override
public R getNearestOldBuild(int n) {
return builds.search(n, Direction.DESC);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
public Object getSameNodeConstraint() {
return this; // in this way, any member that wants to run with the main guy can nominate the project itself
}
public final Task getOwnerTask() {
return this;
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the downstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
// Block builds until they are done with post-production
if (isLogUpdated() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenDownstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingDownstream();
if (bup!=null)
return new BecauseOfDownstreamBuildInProgress(bup);
}
if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the downstream project is either
* building, waiting, pending or buildable.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingDownstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveDownstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
/**
* Returns the project if any of the upstream project is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingUpstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveUpstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
for (JobProperty<? super P> p : properties)
r.addAll(p.getSubTasks());
return r;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
if (r) {
// Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations
// won't reach this line anyway, as they throw AbortExceptions on checkout failure.
calcPollingBaseline(build, launcher, listener);
}
return r;
}
/**
* Pushes the baseline up to the newly checked out revision.
*/
private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
if (baseline==null) {
try {
baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
} catch (AbstractMethodError e) {
baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
}
if (baseline!=null)
build.addAction(baseline);
}
pollingBaseline = baseline;
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The implementation is responsible for ensuring mutual exclusion between polling and builds
* if necessary.
*
* @since 1.345
*/
public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (!isBuildable()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
SCMPollListener.fireBeforePolling(this, listener);
PollingResult r = _poll(listener, scm, lb);
SCMPollListener.firePollingSuccess(this,listener, r);
return r;
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (RuntimeException e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
} catch (Error e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
}
}
/**
* {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
*/
private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
if ( workspaceOfflineReason != null ) {
// workspace offline
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
ws = browser.getWorkspace(this);
if (ws != null) {
return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
}
}
// build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().print(Messages.AbstractProject_NoWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return BUILD_NOW;
}
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
return pollWithWorkspace(listener, scm, lb, ws, l);
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
}
private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
enum WorkspaceOfflineReason {
nonexisting_workspace,
builton_node_gone,
builton_node_no_executors
}
private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {
FilePath ws = build.getWorkspace();
if (ws==null || !ws.exists()) {
return WorkspaceOfflineReason.nonexisting_workspace;
}
Node builtOn = build.getBuiltOn();
if (builtOn == null) { // node built-on doesn't exist anymore
return WorkspaceOfflineReason.builton_node_gone;
}
if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
return WorkspaceOfflineReason.builton_node_no_executors;
}
return null;
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
@Exported
public SCM getScm() {
return scm;
}
public void setScm(SCM scm) throws IOException {
this.scm = scm;
save();
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
public void addTrigger(Trigger<?> trigger) throws IOException {
addToList(trigger,triggers());
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
removeFromList(trigger,triggers());
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i,item);
save();
return;
}
}
// add
collection.add(item);
save();
updateTransientActions();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
updateTransientActions();
return;
}
}
}
@SuppressWarnings("unchecked")
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(triggers());
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : triggers()) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects(ap).contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {
if (delay==null) delay=new TimeDuration(getQuietPeriod());
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
if (pp != null) {
pp._doBuild(req,rsp,delay);
return;
}
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));
rsp.sendRedirect(".");
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
/*package*/ CauseAction getBuildCause(StaplerRequest req) {
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserIdCause();
}
return new CauseAction(cause);
}
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*
* @deprecated as of 1.488
* Inject {@link TimeDuration}.
*/
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
return Integer.parseInt(delay);
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp,delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.sendRedirect(".");
}
/**
* Cancels a scheduled build.
*/
@RequirePOST
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ABORT);
Jenkins.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
/**
* Deletes this project.
*/
@Override
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
delete();
if (req == null || rsp == null)
return;
View view = req.findAncestorObject(View.class);
if (view == null)
rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());
else
rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
makeDisabled(req.getParameter("disable")!=null);
jdk = req.getParameter("jdk");
if(req.getParameter("hasCustomQuietPeriod")!=null) {
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
} else {
quietPeriod = null;
}
if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
} else {
scmCheckoutRetryCount = null;
}
blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;
if(req.hasParameter("customWorkspace")) {
customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
} else {
customWorkspace = null;
}
if (json.has("scmCheckoutStrategy"))
scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,
json.getJSONObject("scmCheckoutStrategy"));
else
scmCheckoutStrategy = null;
if(req.getParameter("hasSlaveAffinity")!=null) {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
} else {
assignedNode = null;
}
canRoam = assignedNode==null;
concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
for (Trigger t : triggers())
t.stop();
triggers = buildDescribable(req, Trigger.for_(this));
for (Trigger t : triggers)
t.start(this,true);
for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
BuildTrigger t = (BuildTrigger) _t;
List<AbstractProject> childProjects;
SecurityContext orig = ACL.impersonate(ACL.SYSTEM);
try {
childProjects = t.getChildProjects(this);
} finally {
SecurityContextHolder.setContext(orig);
}
for (AbstractProject downstream : childProjects) {
downstream.checkPermission(BUILD);
}
}
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
T instance = d.newInstance(req, data.getJSONObject(safeName));
r.add(instance);
}
}
return r;
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
// Would be good if when asked for *plain*, do something else!
// (E.g. return 404, or send empty doc.)
// Not critical; client can just check if content type is not text/plain,
// which also serves to detect old versions of Hudson.
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b!=null ? b.getWorkspace() : null;
if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
for (WorkspaceListener wl : WorkspaceListener.all()) {
wl.afterDelete(this);
}
return new HttpRedirect(".");
} else {
// If we get here, that means the SCM blocked the workspace deletion.
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
@CLIMethod(name="disable-job")
@RequirePOST
public HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
@RequirePOST
public HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return JenkinsLocationConfiguration.get().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
if (Util.fixEmpty(value)==null)
return FormValidation.ok(); // nothing typed yet
try {
Label.parseExpression(value);
} catch (ANTLRException e) {
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
Label l = Jenkins.getInstance().getLabel(value);
if (l.isEmpty()) {
for (LabelAtom a : l.listAtoms()) {
if (a.isEmpty()) {
LabelAtom nearest = LabelAtom.findNearest(a.getName());
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));
}
}
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
}
return FormValidation.ok();
}
public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
if(Util.fixEmptyAndTrim(customWorkspace)==null)
return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
else
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
AutoCompletionCandidates candidates = new AutoCompletionCandidates();
List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
for (Job job: jobs) {
if (job.getFullName().startsWith(value)) {
if (job.hasPermission(Item.READ)) {
candidates.add(job.getFullName());
}
}
}
return candidates;
}
public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
AutoCompletionCandidates c = new AutoCompletionCandidates();
Set<Label> labels = Jenkins.getInstance().getLabels();
List<String> queries = new AutoCompleteSeeder(value).getSeeds();
for (String term : queries) {
for (Label l : labels) {
if (l.getName().startsWith(term)) {
c.add(l.getName());
}
}
}
return c;
}
public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
return SCMCheckoutStrategyDescriptor._for(p);
}
/**
* Utility class for taking the current input value and computing a list
* of potential terms to match against the list of defined labels.
*/
static class AutoCompleteSeeder {
private String source;
AutoCompleteSeeder(String source) {
this.source = source;
}
List<String> getSeeds() {
ArrayList<String> terms = new ArrayList<String>();
boolean trailingQuote = source.endsWith("\"");
boolean leadingQuote = source.startsWith("\"");
boolean trailingSpace = source.endsWith(" ");
if (trailingQuote || (trailingSpace && !leadingQuote)) {
terms.add("");
} else {
if (leadingQuote) {
int quote = source.lastIndexOf('"');
if (quote == 0) {
terms.add(source.substring(1));
} else {
terms.add("");
}
} else {
int space = source.lastIndexOf(' ');
if (space > -1) {
terms.add(source.substring(space+1));
} else {
terms.add(source);
}
}
}
return terms;
}
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
return findNearest(name,Hudson.getInstance());
}
/**
* Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
*
* @since 1.419
*/
public static AbstractProject findNearest(String name, ItemGroup context) {
List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getRelativeNameFrom(context);
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build
*/
public static final Permission ABORT = CANCEL;
/**
* Replaceable "Build Now" text.
*/
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();
/**
* Used for CLI binding.
*/
@CLIResolver
public static AbstractProject resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
if (item==null)
throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
return item;
}
public String getCustomWorkspace() {
return customWorkspace;
}
/**
* User-specified workspace directory, or null if it's up to Jenkins.
*
* <p>
* Normally a project uses the workspace location assigned by its parent container,
* but sometimes people have builds that have hard-coded paths.
*
* <p>
* This is not {@link File} because it may have to hold a path representation on another OS.
*
* <p>
* If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace
* is prepared.
*
* @since 1.410
*/
public void setCustomWorkspace(String customWorkspace) throws IOException {
this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
save();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2091_0
|
crossvul-java_data_good_2153_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.activemq.broker;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.transaction.xa.XAResource;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.region.ConnectionStatistics;
import org.apache.activemq.broker.region.RegionBroker;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.CommandTypes;
import org.apache.activemq.command.ConnectionControl;
import org.apache.activemq.command.ConnectionError;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerControl;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.ControlCommand;
import org.apache.activemq.command.DataArrayResponse;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.ExceptionResponse;
import org.apache.activemq.command.FlushCommand;
import org.apache.activemq.command.IntegerResponse;
import org.apache.activemq.command.KeepAliveInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageDispatch;
import org.apache.activemq.command.MessageDispatchNotification;
import org.apache.activemq.command.MessagePull;
import org.apache.activemq.command.ProducerAck;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.RemoveSubscriptionInfo;
import org.apache.activemq.command.Response;
import org.apache.activemq.command.SessionId;
import org.apache.activemq.command.SessionInfo;
import org.apache.activemq.command.ShutdownInfo;
import org.apache.activemq.command.TransactionId;
import org.apache.activemq.command.TransactionInfo;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.network.MBeanNetworkListener;
import org.apache.activemq.network.NetworkBridgeConfiguration;
import org.apache.activemq.network.NetworkBridgeFactory;
import org.apache.activemq.security.MessageAuthorizationPolicy;
import org.apache.activemq.state.CommandVisitor;
import org.apache.activemq.state.ConnectionState;
import org.apache.activemq.state.ConsumerState;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.state.SessionState;
import org.apache.activemq.state.TransactionState;
import org.apache.activemq.thread.Task;
import org.apache.activemq.thread.TaskRunner;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.transaction.Transaction;
import org.apache.activemq.transport.DefaultTransportListener;
import org.apache.activemq.transport.ResponseCorrelator;
import org.apache.activemq.transport.TransmitCallback;
import org.apache.activemq.transport.Transport;
import org.apache.activemq.transport.TransportDisposedIOException;
import org.apache.activemq.util.IntrospectionSupport;
import org.apache.activemq.util.MarshallingSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class TransportConnection implements Connection, Task, CommandVisitor {
private static final Logger LOG = LoggerFactory.getLogger(TransportConnection.class);
private static final Logger TRANSPORTLOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Transport");
private static final Logger SERVICELOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Service");
// Keeps track of the broker and connector that created this connection.
protected final Broker broker;
protected final TransportConnector connector;
// Keeps track of the state of the connections.
// protected final ConcurrentHashMap localConnectionStates=new
// ConcurrentHashMap();
protected final Map<ConnectionId, ConnectionState> brokerConnectionStates;
// The broker and wireformat info that was exchanged.
protected BrokerInfo brokerInfo;
protected final List<Command> dispatchQueue = new LinkedList<Command>();
protected TaskRunner taskRunner;
protected final AtomicReference<IOException> transportException = new AtomicReference<IOException>();
protected AtomicBoolean dispatchStopped = new AtomicBoolean(false);
private final Transport transport;
private MessageAuthorizationPolicy messageAuthorizationPolicy;
private WireFormatInfo wireFormatInfo;
// Used to do async dispatch.. this should perhaps be pushed down into the
// transport layer..
private boolean inServiceException;
private final ConnectionStatistics statistics = new ConnectionStatistics();
private boolean manageable;
private boolean slow;
private boolean markedCandidate;
private boolean blockedCandidate;
private boolean blocked;
private boolean connected;
private boolean active;
private boolean starting;
private boolean pendingStop;
private long timeStamp;
private final AtomicBoolean stopping = new AtomicBoolean(false);
private final CountDownLatch stopped = new CountDownLatch(1);
private final AtomicBoolean asyncException = new AtomicBoolean(false);
private final Map<ProducerId, ProducerBrokerExchange> producerExchanges = new HashMap<ProducerId, ProducerBrokerExchange>();
private final Map<ConsumerId, ConsumerBrokerExchange> consumerExchanges = new HashMap<ConsumerId, ConsumerBrokerExchange>();
private final CountDownLatch dispatchStoppedLatch = new CountDownLatch(1);
private ConnectionContext context;
private boolean networkConnection;
private boolean faultTolerantConnection;
private final AtomicInteger protocolVersion = new AtomicInteger(CommandTypes.PROTOCOL_VERSION);
private DemandForwardingBridge duplexBridge;
private final TaskRunnerFactory taskRunnerFactory;
private final TaskRunnerFactory stopTaskRunnerFactory;
private TransportConnectionStateRegister connectionStateRegister = new SingleTransportConnectionStateRegister();
private final ReentrantReadWriteLock serviceLock = new ReentrantReadWriteLock();
private String duplexNetworkConnectorId;
private Throwable stopError = null;
/**
* @param taskRunnerFactory - can be null if you want direct dispatch to the transport
* else commands are sent async.
* @param stopTaskRunnerFactory - can <b>not</b> be null, used for stopping this connection.
*/
public TransportConnection(TransportConnector connector, final Transport transport, Broker broker,
TaskRunnerFactory taskRunnerFactory, TaskRunnerFactory stopTaskRunnerFactory) {
this.connector = connector;
this.broker = broker;
RegionBroker rb = (RegionBroker) broker.getAdaptor(RegionBroker.class);
brokerConnectionStates = rb.getConnectionStates();
if (connector != null) {
this.statistics.setParent(connector.getStatistics());
this.messageAuthorizationPolicy = connector.getMessageAuthorizationPolicy();
}
this.taskRunnerFactory = taskRunnerFactory;
this.stopTaskRunnerFactory = stopTaskRunnerFactory;
this.transport = transport;
final BrokerService brokerService = this.broker.getBrokerService();
if( this.transport instanceof BrokerServiceAware ) {
((BrokerServiceAware)this.transport).setBrokerService(brokerService);
}
this.transport.setTransportListener(new DefaultTransportListener() {
@Override
public void onCommand(Object o) {
serviceLock.readLock().lock();
try {
if (!(o instanceof Command)) {
throw new RuntimeException("Protocol violation - Command corrupted: " + o.toString());
}
Command command = (Command) o;
if (!brokerService.isStopping()) {
Response response = service(command);
if (response != null && !brokerService.isStopping()) {
dispatchSync(response);
}
} else {
throw new BrokerStoppedException("Broker " + brokerService + " is being stopped");
}
} finally {
serviceLock.readLock().unlock();
}
}
@Override
public void onException(IOException exception) {
serviceLock.readLock().lock();
try {
serviceTransportException(exception);
} finally {
serviceLock.readLock().unlock();
}
}
});
connected = true;
}
/**
* Returns the number of messages to be dispatched to this connection
*
* @return size of dispatch queue
*/
@Override
public int getDispatchQueueSize() {
synchronized (dispatchQueue) {
return dispatchQueue.size();
}
}
public void serviceTransportException(IOException e) {
BrokerService bService = connector.getBrokerService();
if (bService.isShutdownOnSlaveFailure()) {
if (brokerInfo != null) {
if (brokerInfo.isSlaveBroker()) {
LOG.error("Slave has exception: {} shutting down master now.", e.getMessage(), e);
try {
doStop();
bService.stop();
} catch (Exception ex) {
LOG.warn("Failed to stop the master", ex);
}
}
}
}
if (!stopping.get() && !pendingStop) {
transportException.set(e);
if (TRANSPORTLOG.isDebugEnabled()) {
TRANSPORTLOG.debug(this + " failed: " + e, e);
} else if (TRANSPORTLOG.isWarnEnabled() && !expected(e)) {
TRANSPORTLOG.warn(this + " failed: " + e);
}
stopAsync();
}
}
private boolean expected(IOException e) {
return isStomp() && ((e instanceof SocketException && e.getMessage().indexOf("reset") != -1) || e instanceof EOFException);
}
private boolean isStomp() {
URI uri = connector.getUri();
return uri != null && uri.getScheme() != null && uri.getScheme().indexOf("stomp") != -1;
}
/**
* Calls the serviceException method in an async thread. Since handling a
* service exception closes a socket, we should not tie up broker threads
* since client sockets may hang or cause deadlocks.
*/
@Override
public void serviceExceptionAsync(final IOException e) {
if (asyncException.compareAndSet(false, true)) {
new Thread("Async Exception Handler") {
@Override
public void run() {
serviceException(e);
}
}.start();
}
}
/**
* Closes a clients connection due to a detected error. Errors are ignored
* if: the client is closing or broker is closing. Otherwise, the connection
* error transmitted to the client before stopping it's transport.
*/
@Override
public void serviceException(Throwable e) {
// are we a transport exception such as not being able to dispatch
// synchronously to a transport
if (e instanceof IOException) {
serviceTransportException((IOException) e);
} else if (e.getClass() == BrokerStoppedException.class) {
// Handle the case where the broker is stopped
// But the client is still connected.
if (!stopping.get()) {
SERVICELOG.debug("Broker has been stopped. Notifying client and closing his connection.");
ConnectionError ce = new ConnectionError();
ce.setException(e);
dispatchSync(ce);
// Record the error that caused the transport to stop
this.stopError = e;
// Wait a little bit to try to get the output buffer to flush
// the exception notification to the client.
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
// Worst case is we just kill the connection before the
// notification gets to him.
stopAsync();
}
} else if (!stopping.get() && !inServiceException) {
inServiceException = true;
try {
SERVICELOG.warn("Async error occurred: ", e);
ConnectionError ce = new ConnectionError();
ce.setException(e);
if (pendingStop) {
dispatchSync(ce);
} else {
dispatchAsync(ce);
}
} finally {
inServiceException = false;
}
}
}
@Override
public Response service(Command command) {
MDC.put("activemq.connector", connector.getUri().toString());
Response response = null;
boolean responseRequired = command.isResponseRequired();
int commandId = command.getCommandId();
try {
if (!pendingStop) {
response = command.visit(this);
} else {
response = new ExceptionResponse(this.stopError);
}
} catch (Throwable e) {
if (SERVICELOG.isDebugEnabled() && e.getClass() != BrokerStoppedException.class) {
SERVICELOG.debug("Error occured while processing " + (responseRequired ? "sync" : "async")
+ " command: " + command + ", exception: " + e, e);
}
if (e instanceof SuppressReplyException || (e.getCause() instanceof SuppressReplyException)) {
LOG.info("Suppressing reply to: " + command + " on: " + e + ", cause: " + e.getCause());
responseRequired = false;
}
if (responseRequired) {
if (e instanceof SecurityException || e.getCause() instanceof SecurityException) {
SERVICELOG.warn("Security Error occurred: {}", e.getMessage());
}
response = new ExceptionResponse(e);
} else {
serviceException(e);
}
}
if (responseRequired) {
if (response == null) {
response = new Response();
}
response.setCorrelationId(commandId);
}
// The context may have been flagged so that the response is not
// sent.
if (context != null) {
if (context.isDontSendReponse()) {
context.setDontSendReponse(false);
response = null;
}
context = null;
}
MDC.remove("activemq.connector");
return response;
}
@Override
public Response processKeepAlive(KeepAliveInfo info) throws Exception {
return null;
}
@Override
public Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception {
broker.removeSubscription(lookupConnectionState(info.getConnectionId()).getContext(), info);
return null;
}
@Override
public Response processWireFormat(WireFormatInfo info) throws Exception {
wireFormatInfo = info;
protocolVersion.set(info.getVersion());
return null;
}
@Override
public Response processShutdown(ShutdownInfo info) throws Exception {
stopAsync();
return null;
}
@Override
public Response processFlush(FlushCommand command) throws Exception {
return null;
}
@Override
public Response processBeginTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = null;
if (cs != null) {
context = cs.getContext();
}
if (cs == null) {
throw new NullPointerException("Context is null");
}
// Avoid replaying dup commands
if (cs.getTransactionState(info.getTransactionId()) == null) {
cs.addTransactionState(info.getTransactionId());
broker.beginTransaction(context, info.getTransactionId());
}
return null;
}
@Override
public int getActiveTransactionCount() {
int rc = 0;
for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
Collection<TransactionState> transactions = cs.getTransactionStates();
for (TransactionState transaction : transactions) {
rc++;
}
}
return rc;
}
@Override
public Long getOldestActiveTransactionDuration() {
TransactionState oldestTX = null;
for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
Collection<TransactionState> transactions = cs.getTransactionStates();
for (TransactionState transaction : transactions) {
if( oldestTX ==null || oldestTX.getCreatedAt() < transaction.getCreatedAt() ) {
oldestTX = transaction;
}
}
}
if( oldestTX == null ) {
return null;
}
return System.currentTimeMillis() - oldestTX.getCreatedAt();
}
@Override
public Response processEndTransaction(TransactionInfo info) throws Exception {
// No need to do anything. This packet is just sent by the client
// make sure he is synced with the server as commit command could
// come from a different connection.
return null;
}
@Override
public Response processPrepareTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = null;
if (cs != null) {
context = cs.getContext();
}
if (cs == null) {
throw new NullPointerException("Context is null");
}
TransactionState transactionState = cs.getTransactionState(info.getTransactionId());
if (transactionState == null) {
throw new IllegalStateException("Cannot prepare a transaction that had not been started or previously returned XA_RDONLY: "
+ info.getTransactionId());
}
// Avoid dups.
if (!transactionState.isPrepared()) {
transactionState.setPrepared(true);
int result = broker.prepareTransaction(context, info.getTransactionId());
transactionState.setPreparedResult(result);
if (result == XAResource.XA_RDONLY) {
// we are done, no further rollback or commit from TM
cs.removeTransactionState(info.getTransactionId());
}
IntegerResponse response = new IntegerResponse(result);
return response;
} else {
IntegerResponse response = new IntegerResponse(transactionState.getPreparedResult());
return response;
}
}
@Override
public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.commitTransaction(context, info.getTransactionId(), true);
return null;
}
@Override
public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.commitTransaction(context, info.getTransactionId(), false);
return null;
}
@Override
public Response processRollbackTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
cs.removeTransactionState(info.getTransactionId());
broker.rollbackTransaction(context, info.getTransactionId());
return null;
}
@Override
public Response processForgetTransaction(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
broker.forgetTransaction(context, info.getTransactionId());
return null;
}
@Override
public Response processRecoverTransactions(TransactionInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
context = cs.getContext();
TransactionId[] preparedTransactions = broker.getPreparedTransactions(context);
return new DataArrayResponse(preparedTransactions);
}
@Override
public Response processMessage(Message messageSend) throws Exception {
ProducerId producerId = messageSend.getProducerId();
ProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId);
if (producerExchange.canDispatch(messageSend)) {
broker.send(producerExchange, messageSend);
}
return null;
}
@Override
public Response processMessageAck(MessageAck ack) throws Exception {
ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(ack.getConsumerId());
if (consumerExchange != null) {
broker.acknowledge(consumerExchange, ack);
} else if (ack.isInTransaction()) {
LOG.warn("no matching consumer, ignoring ack {}", consumerExchange, ack);
}
return null;
}
@Override
public Response processMessagePull(MessagePull pull) throws Exception {
return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull);
}
@Override
public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception {
broker.processDispatchNotification(notification);
return null;
}
@Override
public Response processAddDestination(DestinationInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
broker.addDestinationInfo(cs.getContext(), info);
if (info.getDestination().isTemporary()) {
cs.addTempDestination(info);
}
return null;
}
@Override
public Response processRemoveDestination(DestinationInfo info) throws Exception {
TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
broker.removeDestinationInfo(cs.getContext(), info);
if (info.getDestination().isTemporary()) {
cs.removeTempDestination(info.getDestination());
}
return null;
}
@Override
public Response processAddProducer(ProducerInfo info) throws Exception {
SessionId sessionId = info.getProducerId().getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot add a producer to a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot add a producer to a session that had not been registered: "
+ sessionId);
}
// Avoid replaying dup commands
if (!ss.getProducerIds().contains(info.getProducerId())) {
ActiveMQDestination destination = info.getDestination();
if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) {
if (getProducerCount(connectionId) >= connector.getMaximumProducersAllowedPerConnection()){
throw new IllegalStateException("Can't add producer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumProducersAllowedPerConnection());
}
}
broker.addProducer(cs.getContext(), info);
try {
ss.addProducer(info);
} catch (IllegalStateException e) {
broker.removeProducer(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveProducer(ProducerId id) throws Exception {
SessionId sessionId = id.getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: "
+ sessionId);
}
ProducerState ps = ss.removeProducer(id);
if (ps == null) {
throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id);
}
removeProducerBrokerExchange(id);
broker.removeProducer(cs.getContext(), ps.getInfo());
return null;
}
@Override
public Response processAddConsumer(ConsumerInfo info) throws Exception {
SessionId sessionId = info.getConsumerId().getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot add a consumer to a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException(broker.getBrokerName()
+ " Cannot add a consumer to a session that had not been registered: " + sessionId);
}
// Avoid replaying dup commands
if (!ss.getConsumerIds().contains(info.getConsumerId())) {
ActiveMQDestination destination = info.getDestination();
if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) {
if (getConsumerCount(connectionId) >= connector.getMaximumConsumersAllowedPerConnection()){
throw new IllegalStateException("Can't add consumer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumConsumersAllowedPerConnection());
}
}
broker.addConsumer(cs.getContext(), info);
try {
ss.addConsumer(info);
addConsumerBrokerExchange(info.getConsumerId());
} catch (IllegalStateException e) {
broker.removeConsumer(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveConsumer(ConsumerId id, long lastDeliveredSequenceId) throws Exception {
SessionId sessionId = id.getParentId();
ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot remove a consumer from a connection that had not been registered: "
+ connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: "
+ sessionId);
}
ConsumerState consumerState = ss.removeConsumer(id);
if (consumerState == null) {
throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id);
}
ConsumerInfo info = consumerState.getInfo();
info.setLastDeliveredSequenceId(lastDeliveredSequenceId);
broker.removeConsumer(cs.getContext(), consumerState.getInfo());
removeConsumerBrokerExchange(id);
return null;
}
@Override
public Response processAddSession(SessionInfo info) throws Exception {
ConnectionId connectionId = info.getSessionId().getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
// Avoid replaying dup commands
if (cs != null && !cs.getSessionIds().contains(info.getSessionId())) {
broker.addSession(cs.getContext(), info);
try {
cs.addSession(info);
} catch (IllegalStateException e) {
e.printStackTrace();
broker.removeSession(cs.getContext(), info);
}
}
return null;
}
@Override
public Response processRemoveSession(SessionId id, long lastDeliveredSequenceId) throws Exception {
ConnectionId connectionId = id.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs == null) {
throw new IllegalStateException("Cannot remove session from connection that had not been registered: " + connectionId);
}
SessionState session = cs.getSessionState(id);
if (session == null) {
throw new IllegalStateException("Cannot remove session that had not been registered: " + id);
}
// Don't let new consumers or producers get added while we are closing
// this down.
session.shutdown();
// Cascade the connection stop to the consumers and producers.
for (ConsumerId consumerId : session.getConsumerIds()) {
try {
processRemoveConsumer(consumerId, lastDeliveredSequenceId);
} catch (Throwable e) {
LOG.warn("Failed to remove consumer: {}", consumerId, e);
}
}
for (ProducerId producerId : session.getProducerIds()) {
try {
processRemoveProducer(producerId);
} catch (Throwable e) {
LOG.warn("Failed to remove producer: {}", producerId, e);
}
}
cs.removeSession(id);
broker.removeSession(cs.getContext(), session.getInfo());
return null;
}
@Override
public Response processAddConnection(ConnectionInfo info) throws Exception {
// Older clients should have been defaulting this field to true.. but
// they were not.
if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) {
info.setClientMaster(true);
}
TransportConnectionState state;
// Make sure 2 concurrent connections by the same ID only generate 1
// TransportConnectionState object.
synchronized (brokerConnectionStates) {
state = (TransportConnectionState) brokerConnectionStates.get(info.getConnectionId());
if (state == null) {
state = new TransportConnectionState(info, this);
brokerConnectionStates.put(info.getConnectionId(), state);
}
state.incrementReference();
}
// If there are 2 concurrent connections for the same connection id,
// then last one in wins, we need to sync here
// to figure out the winner.
synchronized (state.getConnectionMutex()) {
if (state.getConnection() != this) {
LOG.debug("Killing previous stale connection: {}", state.getConnection().getRemoteAddress());
state.getConnection().stop();
LOG.debug("Connection {} taking over previous connection: {}", getRemoteAddress(), state.getConnection().getRemoteAddress());
state.setConnection(this);
state.reset(info);
}
}
registerConnectionState(info.getConnectionId(), state);
LOG.debug("Setting up new connection id: {}, address: {}, info: {}", new Object[]{ info.getConnectionId(), getRemoteAddress(), info });
this.faultTolerantConnection = info.isFaultTolerant();
// Setup the context.
String clientId = info.getClientId();
context = new ConnectionContext();
context.setBroker(broker);
context.setClientId(clientId);
context.setClientMaster(info.isClientMaster());
context.setConnection(this);
context.setConnectionId(info.getConnectionId());
context.setConnector(connector);
context.setMessageAuthorizationPolicy(getMessageAuthorizationPolicy());
context.setNetworkConnection(networkConnection);
context.setFaultTolerant(faultTolerantConnection);
context.setTransactions(new ConcurrentHashMap<TransactionId, Transaction>());
context.setUserName(info.getUserName());
context.setWireFormatInfo(wireFormatInfo);
context.setReconnect(info.isFailoverReconnect());
this.manageable = info.isManageable();
context.setConnectionState(state);
state.setContext(context);
state.setConnection(this);
if (info.getClientIp() == null) {
info.setClientIp(getRemoteAddress());
}
try {
broker.addConnection(context, info);
} catch (Exception e) {
synchronized (brokerConnectionStates) {
brokerConnectionStates.remove(info.getConnectionId());
}
unregisterConnectionState(info.getConnectionId());
LOG.warn("Failed to add Connection {}", info.getConnectionId(), e);
if (e instanceof SecurityException) {
// close this down - in case the peer of this transport doesn't play nice
delayedStop(2000, "Failed with SecurityException: " + e.getLocalizedMessage(), e);
}
throw e;
}
if (info.isManageable()) {
// send ConnectionCommand
ConnectionControl command = this.connector.getConnectionControl();
command.setFaultTolerant(broker.isFaultTolerantConfiguration());
if (info.isFailoverReconnect()) {
command.setRebalanceConnection(false);
}
dispatchAsync(command);
}
return null;
}
@Override
public synchronized Response processRemoveConnection(ConnectionId id, long lastDeliveredSequenceId)
throws InterruptedException {
LOG.debug("remove connection id: {}", id);
TransportConnectionState cs = lookupConnectionState(id);
if (cs != null) {
// Don't allow things to be added to the connection state while we
// are shutting down.
cs.shutdown();
// Cascade the connection stop to the sessions.
for (SessionId sessionId : cs.getSessionIds()) {
try {
processRemoveSession(sessionId, lastDeliveredSequenceId);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove session {}", sessionId, e);
}
}
// Cascade the connection stop to temp destinations.
for (Iterator<DestinationInfo> iter = cs.getTempDestinations().iterator(); iter.hasNext(); ) {
DestinationInfo di = iter.next();
try {
broker.removeDestination(cs.getContext(), di.getDestination(), 0);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove tmp destination {}", di.getDestination(), e);
}
iter.remove();
}
try {
broker.removeConnection(cs.getContext(), cs.getInfo(), null);
} catch (Throwable e) {
SERVICELOG.warn("Failed to remove connection {}", cs.getInfo(), e);
}
TransportConnectionState state = unregisterConnectionState(id);
if (state != null) {
synchronized (brokerConnectionStates) {
// If we are the last reference, we should remove the state
// from the broker.
if (state.decrementReference() == 0) {
brokerConnectionStates.remove(id);
}
}
}
}
return null;
}
@Override
public Response processProducerAck(ProducerAck ack) throws Exception {
// A broker should not get ProducerAck messages.
return null;
}
@Override
public Connector getConnector() {
return connector;
}
@Override
public void dispatchSync(Command message) {
try {
processDispatch(message);
} catch (IOException e) {
serviceExceptionAsync(e);
}
}
@Override
public void dispatchAsync(Command message) {
if (!stopping.get()) {
if (taskRunner == null) {
dispatchSync(message);
} else {
synchronized (dispatchQueue) {
dispatchQueue.add(message);
}
try {
taskRunner.wakeup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} else {
if (message.isMessageDispatch()) {
MessageDispatch md = (MessageDispatch) message;
TransmitCallback sub = md.getTransmitCallback();
broker.postProcessDispatch(md);
if (sub != null) {
sub.onFailure();
}
}
}
}
protected void processDispatch(Command command) throws IOException {
MessageDispatch messageDispatch = (MessageDispatch) (command.isMessageDispatch() ? command : null);
try {
if (!stopping.get()) {
if (messageDispatch != null) {
broker.preProcessDispatch(messageDispatch);
}
dispatch(command);
}
} catch (IOException e) {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
broker.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onFailure();
}
messageDispatch = null;
throw e;
}
} finally {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
broker.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onSuccess();
}
}
}
}
@Override
public boolean iterate() {
try {
if (pendingStop || stopping.get()) {
if (dispatchStopped.compareAndSet(false, true)) {
if (transportException.get() == null) {
try {
dispatch(new ShutdownInfo());
} catch (Throwable ignore) {
}
}
dispatchStoppedLatch.countDown();
}
return false;
}
if (!dispatchStopped.get()) {
Command command = null;
synchronized (dispatchQueue) {
if (dispatchQueue.isEmpty()) {
return false;
}
command = dispatchQueue.remove(0);
}
processDispatch(command);
return true;
}
return false;
} catch (IOException e) {
if (dispatchStopped.compareAndSet(false, true)) {
dispatchStoppedLatch.countDown();
}
serviceExceptionAsync(e);
return false;
}
}
/**
* Returns the statistics for this connection
*/
@Override
public ConnectionStatistics getStatistics() {
return statistics;
}
public MessageAuthorizationPolicy getMessageAuthorizationPolicy() {
return messageAuthorizationPolicy;
}
public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) {
this.messageAuthorizationPolicy = messageAuthorizationPolicy;
}
@Override
public boolean isManageable() {
return manageable;
}
@Override
public void start() throws Exception {
try {
synchronized (this) {
starting = true;
if (taskRunnerFactory != null) {
taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: "
+ getRemoteAddress());
} else {
taskRunner = null;
}
transport.start();
active = true;
BrokerInfo info = connector.getBrokerInfo().copy();
if (connector.isUpdateClusterClients()) {
info.setPeerBrokerInfos(this.broker.getPeerBrokerInfos());
} else {
info.setPeerBrokerInfos(null);
}
dispatchAsync(info);
connector.onStarted(this);
}
} catch (Exception e) {
// Force clean up on an error starting up.
pendingStop = true;
throw e;
} finally {
// stop() can be called from within the above block,
// but we want to be sure start() completes before
// stop() runs, so queue the stop until right now:
setStarting(false);
if (isPendingStop()) {
LOG.debug("Calling the delayed stop() after start() {}", this);
stop();
}
}
}
@Override
public void stop() throws Exception {
// do not stop task the task runner factories (taskRunnerFactory, stopTaskRunnerFactory)
// as their lifecycle is handled elsewhere
stopAsync();
while (!stopped.await(5, TimeUnit.SECONDS)) {
LOG.info("The connection to '{}' is taking a long time to shutdown.", transport.getRemoteAddress());
}
}
public void delayedStop(final int waitTime, final String reason, Throwable cause) {
if (waitTime > 0) {
synchronized (this) {
pendingStop = true;
stopError = cause;
}
try {
stopTaskRunnerFactory.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(waitTime);
stopAsync();
LOG.info("Stopping {} because {}", transport.getRemoteAddress(), reason);
} catch (InterruptedException e) {
}
}
});
} catch (Throwable t) {
LOG.warn("Cannot create stopAsync. This exception will be ignored.", t);
}
}
}
public void stopAsync() {
// If we're in the middle of starting then go no further... for now.
synchronized (this) {
pendingStop = true;
if (starting) {
LOG.debug("stopAsync() called in the middle of start(). Delaying till start completes..");
return;
}
}
if (stopping.compareAndSet(false, true)) {
// Let all the connection contexts know we are shutting down
// so that in progress operations can notice and unblock.
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
ConnectionContext connectionContext = cs.getContext();
if (connectionContext != null) {
connectionContext.getStopping().set(true);
}
}
try {
stopTaskRunnerFactory.execute(new Runnable() {
@Override
public void run() {
serviceLock.writeLock().lock();
try {
doStop();
} catch (Throwable e) {
LOG.debug("Error occurred while shutting down a connection {}", this, e);
} finally {
stopped.countDown();
serviceLock.writeLock().unlock();
}
}
});
} catch (Throwable t) {
LOG.warn("Cannot create async transport stopper thread. This exception is ignored. Not waiting for stop to complete", t);
stopped.countDown();
}
}
}
@Override
public String toString() {
return "Transport Connection to: " + transport.getRemoteAddress();
}
protected void doStop() throws Exception {
LOG.debug("Stopping connection: {}", transport.getRemoteAddress());
connector.onStopped(this);
try {
synchronized (this) {
if (duplexBridge != null) {
duplexBridge.stop();
}
}
} catch (Exception ignore) {
LOG.trace("Exception caught stopping. This exception is ignored.", ignore);
}
try {
transport.stop();
LOG.debug("Stopped transport: {}", transport.getRemoteAddress());
} catch (Exception e) {
LOG.debug("Could not stop transport to {}. This exception is ignored.", transport.getRemoteAddress(), e);
}
if (taskRunner != null) {
taskRunner.shutdown(1);
taskRunner = null;
}
active = false;
// Run the MessageDispatch callbacks so that message references get
// cleaned up.
synchronized (dispatchQueue) {
for (Iterator<Command> iter = dispatchQueue.iterator(); iter.hasNext(); ) {
Command command = iter.next();
if (command.isMessageDispatch()) {
MessageDispatch md = (MessageDispatch) command;
TransmitCallback sub = md.getTransmitCallback();
broker.postProcessDispatch(md);
if (sub != null) {
sub.onFailure();
}
}
}
dispatchQueue.clear();
}
//
// Remove all logical connection associated with this connection
// from the broker.
if (!broker.isStopped()) {
List<TransportConnectionState> connectionStates = listConnectionStates();
connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
cs.getContext().getStopping().set(true);
try {
LOG.debug("Cleaning up connection resources: {}", getRemoteAddress());
processRemoveConnection(cs.getInfo().getConnectionId(), 0l);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}
LOG.debug("Connection Stopped: {}", getRemoteAddress());
}
/**
* @return Returns the blockedCandidate.
*/
public boolean isBlockedCandidate() {
return blockedCandidate;
}
/**
* @param blockedCandidate The blockedCandidate to set.
*/
public void setBlockedCandidate(boolean blockedCandidate) {
this.blockedCandidate = blockedCandidate;
}
/**
* @return Returns the markedCandidate.
*/
public boolean isMarkedCandidate() {
return markedCandidate;
}
/**
* @param markedCandidate The markedCandidate to set.
*/
public void setMarkedCandidate(boolean markedCandidate) {
this.markedCandidate = markedCandidate;
if (!markedCandidate) {
timeStamp = 0;
blockedCandidate = false;
}
}
/**
* @param slow The slow to set.
*/
public void setSlow(boolean slow) {
this.slow = slow;
}
/**
* @return true if the Connection is slow
*/
@Override
public boolean isSlow() {
return slow;
}
/**
* @return true if the Connection is potentially blocked
*/
public boolean isMarkedBlockedCandidate() {
return markedCandidate;
}
/**
* Mark the Connection, so we can deem if it's collectable on the next sweep
*/
public void doMark() {
if (timeStamp == 0) {
timeStamp = System.currentTimeMillis();
}
}
/**
* @return if after being marked, the Connection is still writing
*/
@Override
public boolean isBlocked() {
return blocked;
}
/**
* @return true if the Connection is connected
*/
@Override
public boolean isConnected() {
return connected;
}
/**
* @param blocked The blocked to set.
*/
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
/**
* @param connected The connected to set.
*/
public void setConnected(boolean connected) {
this.connected = connected;
}
/**
* @return true if the Connection is active
*/
@Override
public boolean isActive() {
return active;
}
/**
* @param active The active to set.
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* @return true if the Connection is starting
*/
public synchronized boolean isStarting() {
return starting;
}
@Override
public synchronized boolean isNetworkConnection() {
return networkConnection;
}
@Override
public boolean isFaultTolerantConnection() {
return this.faultTolerantConnection;
}
protected synchronized void setStarting(boolean starting) {
this.starting = starting;
}
/**
* @return true if the Connection needs to stop
*/
public synchronized boolean isPendingStop() {
return pendingStop;
}
protected synchronized void setPendingStop(boolean pendingStop) {
this.pendingStop = pendingStop;
}
@Override
public Response processBrokerInfo(BrokerInfo info) {
if (info.isSlaveBroker()) {
LOG.error(" Slave Brokers are no longer supported - slave trying to attach is: {}", info.getBrokerName());
} else if (info.isNetworkConnection() && info.isDuplexConnection()) {
// so this TransportConnection is the rear end of a network bridge
// We have been requested to create a two way pipe ...
try {
Properties properties = MarshallingSupport.stringToProperties(info.getNetworkProperties());
Map<String, String> props = createMap(properties);
NetworkBridgeConfiguration config = new NetworkBridgeConfiguration();
IntrospectionSupport.setProperties(config, props, "");
config.setBrokerName(broker.getBrokerName());
// check for existing duplex connection hanging about
// We first look if existing network connection already exists for the same broker Id and network connector name
// It's possible in case of brief network fault to have this transport connector side of the connection always active
// and the duplex network connector side wanting to open a new one
// In this case, the old connection must be broken
String duplexNetworkConnectorId = config.getName() + "@" + info.getBrokerId();
CopyOnWriteArrayList<TransportConnection> connections = this.connector.getConnections();
synchronized (connections) {
for (Iterator<TransportConnection> iter = connections.iterator(); iter.hasNext(); ) {
TransportConnection c = iter.next();
if ((c != this) && (duplexNetworkConnectorId.equals(c.getDuplexNetworkConnectorId()))) {
LOG.warn("Stopping an existing active duplex connection [{}] for network connector ({}).", c, duplexNetworkConnectorId);
c.stopAsync();
// better to wait for a bit rather than get connection id already in use and failure to start new bridge
c.getStopped().await(1, TimeUnit.SECONDS);
}
}
setDuplexNetworkConnectorId(duplexNetworkConnectorId);
}
Transport localTransport = NetworkBridgeFactory.createLocalTransport(broker);
Transport remoteBridgeTransport = transport;
if (! (remoteBridgeTransport instanceof ResponseCorrelator)) {
// the vm transport case is already wrapped
remoteBridgeTransport = new ResponseCorrelator(remoteBridgeTransport);
}
String duplexName = localTransport.toString();
if (duplexName.contains("#")) {
duplexName = duplexName.substring(duplexName.lastIndexOf("#"));
}
MBeanNetworkListener listener = new MBeanNetworkListener(broker.getBrokerService(), config, broker.getBrokerService().createDuplexNetworkConnectorObjectName(duplexName));
listener.setCreatedByDuplex(true);
duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, remoteBridgeTransport, listener);
duplexBridge.setBrokerService(broker.getBrokerService());
// now turn duplex off this side
info.setDuplexConnection(false);
duplexBridge.setCreatedByDuplex(true);
duplexBridge.duplexStart(this, brokerInfo, info);
LOG.info("Started responder end of duplex bridge {}", duplexNetworkConnectorId);
return null;
} catch (TransportDisposedIOException e) {
LOG.warn("Duplex bridge {} was stopped before it was correctly started.", duplexNetworkConnectorId);
return null;
} catch (Exception e) {
LOG.error("Failed to create responder end of duplex network bridge {}", duplexNetworkConnectorId, e);
return null;
}
}
// We only expect to get one broker info command per connection
if (this.brokerInfo != null) {
LOG.warn("Unexpected extra broker info command received: {}", info);
}
this.brokerInfo = info;
networkConnection = true;
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
cs.getContext().setNetworkConnection(true);
}
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private HashMap<String, String> createMap(Properties properties) {
return new HashMap(properties);
}
protected void dispatch(Command command) throws IOException {
try {
setMarkedCandidate(true);
transport.oneway(command);
} finally {
setMarkedCandidate(false);
}
}
@Override
public String getRemoteAddress() {
return transport.getRemoteAddress();
}
public Transport getTransport() {
return transport;
}
@Override
public String getConnectionId() {
List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) {
if (cs.getInfo().getClientId() != null) {
return cs.getInfo().getClientId();
}
return cs.getInfo().getConnectionId().toString();
}
return null;
}
@Override
public void updateClient(ConnectionControl control) {
if (isActive() && isBlocked() == false && isFaultTolerantConnection() && this.wireFormatInfo != null
&& this.wireFormatInfo.getVersion() >= 6) {
dispatchAsync(control);
}
}
public ProducerBrokerExchange getProducerBrokerExchangeIfExists(ProducerInfo producerInfo){
ProducerBrokerExchange result = null;
if (producerInfo != null && producerInfo.getProducerId() != null){
synchronized (producerExchanges){
result = producerExchanges.get(producerInfo.getProducerId());
}
}
return result;
}
private ProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
ProducerBrokerExchange result = producerExchanges.get(id);
if (result == null) {
synchronized (producerExchanges) {
result = new ProducerBrokerExchange();
TransportConnectionState state = lookupConnectionState(id);
context = state.getContext();
result.setConnectionContext(context);
if (context.isReconnect() || (context.isNetworkConnection() && connector.isAuditNetworkProducers())) {
result.setLastStoredSequenceId(broker.getBrokerService().getPersistenceAdapter().getLastProducerSequenceId(id));
}
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
result.setProducerState(ss.getProducerState(id));
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
}
}
producerExchanges.put(id, result);
}
} else {
context = result.getConnectionContext();
}
return result;
}
private void removeProducerBrokerExchange(ProducerId id) {
synchronized (producerExchanges) {
producerExchanges.remove(id);
}
}
private ConsumerBrokerExchange getConsumerBrokerExchange(ConsumerId id) {
ConsumerBrokerExchange result = consumerExchanges.get(id);
return result;
}
private ConsumerBrokerExchange addConsumerBrokerExchange(ConsumerId id) {
ConsumerBrokerExchange result = consumerExchanges.get(id);
if (result == null) {
synchronized (consumerExchanges) {
result = new ConsumerBrokerExchange();
TransportConnectionState state = lookupConnectionState(id);
context = state.getContext();
result.setConnectionContext(context);
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
ConsumerState cs = ss.getConsumerState(id);
if (cs != null) {
ConsumerInfo info = cs.getInfo();
if (info != null) {
if (info.getDestination() != null && info.getDestination().isPattern()) {
result.setWildcard(true);
}
}
}
}
consumerExchanges.put(id, result);
}
}
return result;
}
private void removeConsumerBrokerExchange(ConsumerId id) {
synchronized (consumerExchanges) {
consumerExchanges.remove(id);
}
}
public int getProtocolVersion() {
return protocolVersion.get();
}
@Override
public Response processControlCommand(ControlCommand command) throws Exception {
return null;
}
@Override
public Response processMessageDispatch(MessageDispatch dispatch) throws Exception {
return null;
}
@Override
public Response processConnectionControl(ConnectionControl control) throws Exception {
if (control != null) {
faultTolerantConnection = control.isFaultTolerant();
}
return null;
}
@Override
public Response processConnectionError(ConnectionError error) throws Exception {
return null;
}
@Override
public Response processConsumerControl(ConsumerControl control) throws Exception {
ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(control.getConsumerId());
broker.processConsumerControl(consumerExchange, control);
return null;
}
protected synchronized TransportConnectionState registerConnectionState(ConnectionId connectionId,
TransportConnectionState state) {
TransportConnectionState cs = null;
if (!connectionStateRegister.isEmpty() && !connectionStateRegister.doesHandleMultipleConnectionStates()) {
// swap implementations
TransportConnectionStateRegister newRegister = new MapTransportConnectionStateRegister();
newRegister.intialize(connectionStateRegister);
connectionStateRegister = newRegister;
}
cs = connectionStateRegister.registerConnectionState(connectionId, state);
return cs;
}
protected synchronized TransportConnectionState unregisterConnectionState(ConnectionId connectionId) {
return connectionStateRegister.unregisterConnectionState(connectionId);
}
protected synchronized List<TransportConnectionState> listConnectionStates() {
return connectionStateRegister.listConnectionStates();
}
protected synchronized TransportConnectionState lookupConnectionState(String connectionId) {
return connectionStateRegister.lookupConnectionState(connectionId);
}
protected synchronized TransportConnectionState lookupConnectionState(ConsumerId id) {
return connectionStateRegister.lookupConnectionState(id);
}
protected synchronized TransportConnectionState lookupConnectionState(ProducerId id) {
return connectionStateRegister.lookupConnectionState(id);
}
protected synchronized TransportConnectionState lookupConnectionState(SessionId id) {
return connectionStateRegister.lookupConnectionState(id);
}
// public only for testing
public synchronized TransportConnectionState lookupConnectionState(ConnectionId connectionId) {
return connectionStateRegister.lookupConnectionState(connectionId);
}
protected synchronized void setDuplexNetworkConnectorId(String duplexNetworkConnectorId) {
this.duplexNetworkConnectorId = duplexNetworkConnectorId;
}
protected synchronized String getDuplexNetworkConnectorId() {
return this.duplexNetworkConnectorId;
}
public boolean isStopping() {
return stopping.get();
}
protected CountDownLatch getStopped() {
return stopped;
}
private int getProducerCount(ConnectionId connectionId) {
int result = 0;
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs != null) {
for (SessionId sessionId : cs.getSessionIds()) {
SessionState sessionState = cs.getSessionState(sessionId);
if (sessionState != null) {
result += sessionState.getProducerIds().size();
}
}
}
return result;
}
private int getConsumerCount(ConnectionId connectionId) {
int result = 0;
TransportConnectionState cs = lookupConnectionState(connectionId);
if (cs != null) {
for (SessionId sessionId : cs.getSessionIds()) {
SessionState sessionState = cs.getSessionState(sessionId);
if (sessionState != null) {
result += sessionState.getConsumerIds().size();
}
}
}
return result;
}
public WireFormatInfo getRemoteWireFormatInfo() {
return wireFormatInfo;
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2153_0
|
crossvul-java_data_bad_4727_5
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_5
|
crossvul-java_data_good_2293_0
|
package org.uberfire.commons.regex.util;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* PathMatcher implementation for Ant-style path patterns.
* <p/>
* This code has been borrowed from <a href="http://camel.apache.org">Apache Camel</a>.
* <p/>
*/
public class AntPathMatcher {
/**
* Default path separator: "/"
*/
public static final String DEFAULT_PATH_SEPARATOR = "/";
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
/**
* Set the path separator to use for pattern parsing. Default is "/", as in
* Ant.
*/
public void setPathSeparator( final String pathSeparator ) {
this.pathSeparator = pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR;
}
public boolean isPattern( final String path ) {
return path.indexOf( '*' ) != -1 || path.indexOf( '?' ) != -1;
}
public boolean match( final String pattern,
final String path ) {
return doMatch( pattern, path, true );
}
public boolean matchStart( final String pattern,
final String path ) {
return doMatch( pattern, path, false );
}
/**
* Actually match the given <code>path</code> against the given
* <code>pattern</code>.
* @param pattern the pattern to match against
* @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern
* match as far as the given base path goes is sufficient)
* @return <code>true</code> if the supplied <code>path</code> matched,
* <code>false</code> if it didn't
*/
protected boolean doMatch( String pattern,
String path,
boolean fullMatch ) {
if ( path.startsWith( this.pathSeparator ) != pattern.startsWith( this.pathSeparator ) ) {
return false;
}
String[] pattDirs = tokenizeToStringArray( pattern, this.pathSeparator );
String[] pathDirs = tokenizeToStringArray( path, this.pathSeparator );
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while ( pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
String patDir = pattDirs[ pattIdxStart ];
if ( "**".equals( patDir ) ) {
break;
}
if ( !matchStrings( patDir, pathDirs[ pathIdxStart ] ) ) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if ( pathIdxStart > pathIdxEnd ) {
// Path is exhausted, only match if rest of pattern is * or **'s
if ( pattIdxStart > pattIdxEnd ) {
return pattern.endsWith( this.pathSeparator ) ? path.endsWith( this.pathSeparator ) : !path
.endsWith( this.pathSeparator );
}
if ( !fullMatch ) {
return true;
}
if ( pattIdxStart == pattIdxEnd && pattDirs[ pattIdxStart ].equals( "*" )
&& path.endsWith( this.pathSeparator ) ) {
return true;
}
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !pattDirs[ i ].equals( "**" ) ) {
return false;
}
}
return true;
} else if ( pattIdxStart > pattIdxEnd ) {
// String not exhausted, but pattern is. Failure.
return false;
} else if ( !fullMatch && "**".equals( pattDirs[ pattIdxStart ] ) ) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while ( pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
String patDir = pattDirs[ pattIdxEnd ];
if ( patDir.equals( "**" ) ) {
break;
}
if ( !matchStrings( patDir, pathDirs[ pathIdxEnd ] ) ) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if ( pathIdxStart > pathIdxEnd ) {
// String is exhausted
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !pattDirs[ i ].equals( "**" ) ) {
return false;
}
}
return true;
}
while ( pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd ) {
int patIdxTmp = -1;
for ( int i = pattIdxStart + 1; i <= pattIdxEnd; i++ ) {
if ( pattDirs[ i ].equals( "**" ) ) {
patIdxTmp = i;
break;
}
}
if ( patIdxTmp == pattIdxStart + 1 ) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = patIdxTmp - pattIdxStart - 1;
int strLength = pathIdxEnd - pathIdxStart + 1;
int foundIdx = -1;
strLoop:
for ( int i = 0; i <= strLength - patLength; i++ ) {
for ( int j = 0; j < patLength; j++ ) {
String subPat = pattDirs[ pattIdxStart + j + 1 ];
String subStr = pathDirs[ pathIdxStart + i + j ];
if ( !matchStrings( subPat, subStr ) ) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if ( foundIdx == -1 ) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for ( int i = pattIdxStart; i <= pattIdxEnd; i++ ) {
if ( !pattDirs[ i ].equals( "**" ) ) {
return false;
}
}
return true;
}
/**
* Tests whether or not a string matches against a pattern. The pattern may
* contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be
* <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or
* <code>false</code> otherwise.
*/
private boolean matchStrings( String pattern,
String str ) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = false;
for ( char c : patArr ) {
if ( c == '*' ) {
containsStar = true;
break;
}
}
if ( !containsStar ) {
// No '*'s, so we make a shortcut
if ( patIdxEnd != strIdxEnd ) {
return false; // Pattern and string do not have the same size
}
for ( int i = 0; i <= patIdxEnd; i++ ) {
ch = patArr[ i ];
if ( ch != '?' ) {
if ( ch != strArr[ i ] ) {
return false;
// Character mismatch
}
}
}
return true; // String matches against pattern
}
if ( patIdxEnd == 0 ) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ( ( ch = patArr[ patIdxStart ] ) != '*' && strIdxStart <= strIdxEnd ) {
if ( ch != '?' ) {
if ( ch != strArr[ strIdxStart ] ) {
return false;
// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if ( strIdxStart > strIdxEnd ) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
// Process characters after last star
while ( ( ch = patArr[ patIdxEnd ] ) != '*' && strIdxStart <= strIdxEnd ) {
if ( ch != '?' ) {
if ( ch != strArr[ strIdxEnd ] ) {
return false;
// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if ( strIdxStart > strIdxEnd ) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) {
int patIdxTmp = -1;
for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] == '*' ) {
patIdxTmp = i;
break;
}
}
if ( patIdxTmp == patIdxStart + 1 ) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = patIdxTmp - patIdxStart - 1;
int strLength = strIdxEnd - strIdxStart + 1;
int foundIdx = -1;
strLoop:
for ( int i = 0; i <= strLength - patLength; i++ ) {
for ( int j = 0; j < patLength; j++ ) {
ch = patArr[ patIdxStart + j + 1 ];
if ( ch != '?' ) {
if ( ch != strArr[ strIdxStart + i + j ] ) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if ( foundIdx == -1 ) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for ( int i = patIdxStart; i <= patIdxEnd; i++ ) {
if ( patArr[ i ] != '*' ) {
return false;
}
}
return true;
}
/**
* Given a pattern and a full path, determine the pattern-mapped part.
* <p/>
* For example:
* <ul>
* <li>'<code>/docs/cvs/commit.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> ''</li>
* <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '
* <code>cvs/commit</code>'</li>
* <li>'<code>/docs/cvs/*.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>
* <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '
* <code>cvs/commit</code>'</li>
* <li>'<code>/docs/**\/*.html</code>' and '
* <code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>
* <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>docs/cvs/commit.html</code>'</li>
* <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>/docs/cvs/commit.html</code>'</li>
* <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '
* <code>/docs/cvs/commit.html</code>'</li>
* </ul>
* <p/>
* Assumes that {@link #match} returns <code>true</code> for '
* <code>pattern</code>' and '<code>path</code>', but does
* <strong>not</strong> enforce this.
*/
public String extractPathWithinPattern( String pattern,
String path ) {
final String[] patternParts = tokenizeToStringArray( pattern, this.pathSeparator );
final String[] pathParts = tokenizeToStringArray( path, this.pathSeparator );
final StringBuilder buffer = new StringBuilder();
// Add any path parts that have a wildcarded pattern part.
int puts = 0;
for ( int i = 0; i < patternParts.length; i++ ) {
final String patternPart = patternParts[ i ];
if ( ( patternPart.indexOf( '*' ) > -1 || patternPart.indexOf( '?' ) > -1 ) && pathParts.length >= i + 1 ) {
if ( puts > 0 || ( i == 0 && !pattern.startsWith( this.pathSeparator ) ) ) {
buffer.append( this.pathSeparator );
}
buffer.append( pathParts[ i ] );
puts++;
}
}
// Append any trailing path parts.
for ( int i = patternParts.length; i < pathParts.length; i++ ) {
if ( puts > 0 || i > 0 ) {
buffer.append( this.pathSeparator );
}
buffer.append( pathParts[ i ] );
}
return buffer.toString();
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
* <p/>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String (each of
* those characters is individually considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
*/
public static String[] tokenizeToStringArray( String str,
String delimiters ) {
if ( str == null ) {
return null;
}
final StringTokenizer st = new StringTokenizer( str, delimiters );
final List<String> tokens = new ArrayList<String>();
while ( st.hasMoreTokens() ) {
final String token = st.nextToken().trim();
if ( token.length() > 0 ) {
tokens.add( token );
}
}
return tokens.toArray( new String[ tokens.size() ] );
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2293_0
|
crossvul-java_data_bad_4708_0
|
package org.orbeon.oxf.xml.xerces;
import org.orbeon.oxf.common.OXFException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
/**
* Boasts a couple of improvements over the 'stock' xerces parser factory.
*
* o Doesn't create a new parser every time one calls setFeature or getFeature. Stock one
* has to do this because valid feature set is encapsulated in the parser code.
*
* o Creates a XercesJAXPSAXParser instead of SaxParserImpl. See XercesJAXPSAXParser for
* why this is an improvement.
*
* o The improvements cut the time it takes to a SAX parser via JAXP in
* half and reduce the amount of garbage created when accessing '/' in
* the examples app from 9019216 bytes to 8402880 bytes.
*/
public class XercesSAXParserFactoryImpl extends SAXParserFactory {
private static final Collection recognizedFeaturesNonValidatingXInclude;
private static final Map defaultFeaturesNonValidatingXInclude;
private static final Collection recognizedFeaturesNonValidatingNoXInclude;
private static final Map defaultFeaturesNonValidatingNoXInclude;
private static final Collection recognizedFeaturesValidatingXInclude;
private static final Map defaultFeaturesValidatingXInclude;
private static final Collection recognizedFeaturesValidatingNoXInclude;
private static final Map defaultFeaturesValidatingNoXInclude;
static {
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(false, true);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesNonValidatingXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesNonValidatingXInclude = configuration.getFeatures();
// This was being done in XMLUtils.createSaxParserFactory before. Maybe want to
// move it back if we decide to make this class more general purpose.
defaultFeaturesNonValidatingXInclude.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
defaultFeaturesNonValidatingXInclude.put("http://xml.org/sax/features/namespace-prefixes", Boolean.FALSE);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(false, false);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesNonValidatingNoXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesNonValidatingNoXInclude = configuration.getFeatures();
// This was being done in XMLUtils.createSaxParserFactory before. Maybe want to
// move it back if we decide to make this class more general purpose.
defaultFeaturesNonValidatingNoXInclude.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
defaultFeaturesNonValidatingNoXInclude.put("http://xml.org/sax/features/namespace-prefixes", Boolean.FALSE);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(true, true);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesValidatingXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesValidatingXInclude = configuration.getFeatures();
// This was being done in XMLUtils.createSaxParserFactory before. Maybe want to
// move it back if we decide to make this class more general purpose.
defaultFeaturesValidatingXInclude.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
defaultFeaturesValidatingXInclude.put("http://xml.org/sax/features/namespace-prefixes", Boolean.FALSE);
}
{
final OrbeonParserConfiguration configuration = XercesSAXParser.makeConfig(true, false);
final Collection features = configuration.getRecognizedFeatures();
recognizedFeaturesValidatingNoXInclude = Collections.unmodifiableCollection(features);
defaultFeaturesValidatingNoXInclude = configuration.getFeatures();
// This was being done in XMLUtils.createSaxParserFactory before. Maybe want to
// move it back if we decide to make this class more general purpose.
defaultFeaturesValidatingNoXInclude.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
defaultFeaturesValidatingNoXInclude.put("http://xml.org/sax/features/namespace-prefixes", Boolean.FALSE);
}
}
private final Hashtable features;
private final boolean validating;
private final boolean handleXInclude;
public XercesSAXParserFactoryImpl() {
this(false, false);
}
public XercesSAXParserFactoryImpl(boolean validating, boolean handleXInclude) {
this.validating = validating;
this.handleXInclude = handleXInclude;
if (!validating) {
features = new Hashtable(handleXInclude ? defaultFeaturesNonValidatingXInclude : defaultFeaturesNonValidatingNoXInclude);
} else {
features = new Hashtable(handleXInclude ? defaultFeaturesValidatingXInclude : defaultFeaturesValidatingNoXInclude);
}
setNamespaceAware(true); // this is needed by some tools in addition to the feature
}
public boolean getFeature(final String key) throws SAXNotRecognizedException {
if (!getRecognizedFeatures().contains(key)) throw new SAXNotRecognizedException(key);
return features.get(key) == Boolean.TRUE;
}
public void setFeature(final String key, final boolean val) throws SAXNotRecognizedException {
if (!getRecognizedFeatures().contains(key)) throw new SAXNotRecognizedException(key);
features.put(key, val ? Boolean.TRUE : Boolean.FALSE);
}
public SAXParser newSAXParser() throws ParserConfigurationException {
final SAXParser ret;
try {
ret = new XercesJAXPSAXParser(this, features, validating, handleXInclude);
} catch (final SAXException se) {
// Translate to ParserConfigurationException
throw new OXFException(se); // so we see a decent stack trace!
// throw new ParserConfigurationException(se.getMessage());
}
return ret;
}
private Collection getRecognizedFeatures() {
if (!validating) {
return handleXInclude ? recognizedFeaturesNonValidatingXInclude : recognizedFeaturesNonValidatingNoXInclude;
} else {
return handleXInclude ? recognizedFeaturesValidatingXInclude : recognizedFeaturesValidatingNoXInclude;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4708_0
|
crossvul-java_data_bad_2293_1
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2293_1
|
crossvul-java_data_bad_4727_0
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.deploy.hot;
import com.liferay.portal.kernel.deploy.hot.HotDeploy;
import com.liferay.portal.kernel.deploy.hot.HotDeployEvent;
import com.liferay.portal.kernel.deploy.hot.HotDeployException;
import com.liferay.portal.kernel.deploy.hot.HotDeployListener;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.ServletContextPool;
import com.liferay.portal.kernel.util.BasePortalLifecycle;
import com.liferay.portal.kernel.util.HttpUtil;
import com.liferay.portal.kernel.util.PortalLifecycle;
import com.liferay.portal.kernel.util.PortalLifecycleUtil;
import com.liferay.portal.kernel.util.PropertiesUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
import com.liferay.portal.security.pacl.PACLPolicy;
import com.liferay.portal.security.pacl.PACLPolicyManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.ServletContext;
/**
* @author Ivica Cardic
* @author Brian Wing Shun Chan
* @author Raymond Augé
*/
public class HotDeployImpl implements HotDeploy {
public HotDeployImpl() {
if (_log.isDebugEnabled()) {
_log.debug("Initializing hot deploy manager " + this.hashCode());
}
_dependentHotDeployEvents = new ArrayList<HotDeployEvent>();
_deployedServletContextNames = new HashSet<String>();
_hotDeployListeners = new CopyOnWriteArrayList<HotDeployListener>();
}
public void fireDeployEvent(final HotDeployEvent hotDeployEvent) {
PortalLifecycleUtil.register(
new PACLPortalLifecycle(hotDeployEvent),
PortalLifecycle.METHOD_INIT);
if (_capturePrematureEvents) {
// Capture events that are fired before the portal initialized
PortalLifecycle portalLifecycle = new BasePortalLifecycle() {
@Override
protected void doPortalDestroy() {
}
@Override
protected void doPortalInit() {
fireDeployEvent(hotDeployEvent);
}
};
PortalLifecycleUtil.register(
portalLifecycle, PortalLifecycle.METHOD_INIT);
}
else {
// Fire event
doFireDeployEvent(hotDeployEvent);
}
}
public void fireUndeployEvent(HotDeployEvent hotDeployEvent) {
for (HotDeployListener hotDeployListener : _hotDeployListeners) {
try {
hotDeployListener.invokeUndeploy(hotDeployEvent);
}
catch (HotDeployException hde) {
_log.error(hde, hde);
}
}
_deployedServletContextNames.remove(
hotDeployEvent.getServletContextName());
PACLPolicyManager.unregister(hotDeployEvent.getContextClassLoader());
}
public void registerListener(HotDeployListener hotDeployListener) {
_hotDeployListeners.add(hotDeployListener);
}
public void reset() {
_capturePrematureEvents = true;
_dependentHotDeployEvents.clear();
_deployedServletContextNames.clear();
_hotDeployListeners.clear();
}
public void setCapturePrematureEvents(boolean capturePrematureEvents) {
_capturePrematureEvents = capturePrematureEvents;
}
public void unregisterListener(HotDeployListener hotDeployListener) {
_hotDeployListeners.remove(hotDeployListener);
}
public void unregisterListeners() {
_hotDeployListeners.clear();
}
protected void doFireDeployEvent(HotDeployEvent hotDeployEvent) {
String servletContextName = hotDeployEvent.getServletContextName();
if (_deployedServletContextNames.contains(servletContextName)) {
return;
}
boolean hasDependencies = true;
for (String dependentServletContextName :
hotDeployEvent.getDependentServletContextNames()) {
if (!_deployedServletContextNames.contains(
dependentServletContextName)) {
hasDependencies = false;
break;
}
}
if (hasDependencies) {
if (_log.isInfoEnabled()) {
_log.info("Deploying " + servletContextName + " from queue");
}
for (HotDeployListener hotDeployListener : _hotDeployListeners) {
try {
hotDeployListener.invokeDeploy(hotDeployEvent);
}
catch (HotDeployException hde) {
_log.error(hde, hde);
}
}
_deployedServletContextNames.add(servletContextName);
_dependentHotDeployEvents.remove(hotDeployEvent);
ClassLoader contextClassLoader = getContextClassLoader();
try {
setContextClassLoader(
PACLClassLoaderUtil.getPortalClassLoader());
List<HotDeployEvent> dependentEvents =
new ArrayList<HotDeployEvent>(_dependentHotDeployEvents);
for (HotDeployEvent dependentEvent : dependentEvents) {
setContextClassLoader(
dependentEvent.getContextClassLoader());
doFireDeployEvent(dependentEvent);
}
}
finally {
setContextClassLoader(contextClassLoader);
}
}
else {
if (!_dependentHotDeployEvents.contains(hotDeployEvent)) {
if (_log.isInfoEnabled()) {
StringBundler sb = new StringBundler(4);
sb.append("Queueing ");
sb.append(servletContextName);
sb.append(" for deploy because it is missing ");
sb.append(getRequiredServletContextNames(hotDeployEvent));
_log.info(sb.toString());
}
_dependentHotDeployEvents.add(hotDeployEvent);
}
else {
if (_log.isInfoEnabled()) {
for (HotDeployEvent dependentHotDeployEvent :
_dependentHotDeployEvents) {
StringBundler sb = new StringBundler(3);
sb.append(servletContextName);
sb.append(" is still in queue because it is missing ");
sb.append(
getRequiredServletContextNames(
dependentHotDeployEvent));
_log.info(sb.toString());
}
}
}
}
}
protected ClassLoader getContextClassLoader() {
return PACLClassLoaderUtil.getContextClassLoader();
}
protected String getRequiredServletContextNames(
HotDeployEvent hotDeployEvent) {
List<String> requiredServletContextNames = new ArrayList<String>();
for (String dependentServletContextName :
hotDeployEvent.getDependentServletContextNames()) {
if (!_deployedServletContextNames.contains(
dependentServletContextName)) {
requiredServletContextNames.add(dependentServletContextName);
}
}
Collections.sort(requiredServletContextNames);
return StringUtil.merge(requiredServletContextNames, ", ");
}
protected void setContextClassLoader(ClassLoader contextClassLoader) {
PACLClassLoaderUtil.setContextClassLoader(contextClassLoader);
}
private static Log _log = LogFactoryUtil.getLog(HotDeployImpl.class);
private boolean _capturePrematureEvents = true;
private List<HotDeployEvent> _dependentHotDeployEvents;
private Set<String> _deployedServletContextNames;
private List<HotDeployListener> _hotDeployListeners;
private class PACLPortalLifecycle extends BasePortalLifecycle {
public PACLPortalLifecycle(HotDeployEvent hotDeployEvent) {
_servletContext = hotDeployEvent.getServletContext();
_classLoader = hotDeployEvent.getContextClassLoader();
ServletContextPool.put(
_servletContext.getServletContextName(), _servletContext);
}
@Override
protected void doPortalDestroy() {
}
@Override
protected void doPortalInit() throws Exception {
Properties properties = null;
String propertiesString = HttpUtil.URLtoString(
_servletContext.getResource(
"/WEB-INF/liferay-plugin-package.properties"));
if (propertiesString != null) {
properties = PropertiesUtil.load(propertiesString);
}
else {
properties = new Properties();
}
PACLPolicy paclPolicy = PACLPolicyManager.buildPACLPolicy(
_servletContext.getServletContextName(), _classLoader,
properties);
PACLPolicyManager.register(_classLoader, paclPolicy);
}
private ClassLoader _classLoader;
private ServletContext _servletContext;
};
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_0
|
crossvul-java_data_good_5851_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.DescriptorExtensionList;
import hudson.PluginWrapper;
import hudson.RelativePath;
import hudson.XmlFile;
import hudson.BulkChange;
import hudson.Util;
import hudson.model.listeners.SaveableListener;
import hudson.util.FormApply;
import hudson.util.ReflectionUtils;
import hudson.util.ReflectionUtils.Parameter;
import hudson.views.ListViewColumn;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.jelly.JellyCompatibleFacet;
import org.kohsuke.stapler.lang.Klass;
import org.springframework.util.StringUtils;
import org.jvnet.tiger_types.Types;
import org.apache.commons.io.IOUtils;
import static hudson.Functions.*;
import static hudson.util.QuotedStringTokenizer.*;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Locale;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.beans.Introspector;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Metadata about a configurable instance.
*
* <p>
* {@link Descriptor} is an object that has metadata about a {@link Describable}
* object, and also serves as a factory (in a way this relationship is similar
* to {@link Object}/{@link Class} relationship.
*
* A {@link Descriptor}/{@link Describable}
* combination is used throughout in Hudson to implement a
* configuration/extensibility mechanism.
*
* <p>
* Take the list view support as an example, which is implemented
* in {@link ListView} class. Whenever a new view is created, a new
* {@link ListView} instance is created with the configuration
* information. This instance gets serialized to XML, and this instance
* will be called to render the view page. This is the job
* of {@link Describable} — each instance represents a specific
* configuration of a view (what projects are in it, regular expression, etc.)
*
* <p>
* For Hudson to create such configured {@link ListView} instance, Hudson
* needs another object that captures the metadata of {@link ListView},
* and that is what a {@link Descriptor} is for. {@link ListView} class
* has a singleton descriptor, and this descriptor helps render
* the configuration form, remember system-wide configuration, and works as a factory.
*
* <p>
* {@link Descriptor} also usually have its associated views.
*
*
* <h2>Persistence</h2>
* <p>
* {@link Descriptor} can persist data just by storing them in fields.
* However, it is the responsibility of the derived type to properly
* invoke {@link #save()} and {@link #load()}.
*
* <h2>Reflection Enhancement</h2>
* {@link Descriptor} defines addition to the standard Java reflection
* and provides reflective information about its corresponding {@link Describable}.
* These are primarily used by tag libraries to
* keep the Jelly scripts concise.
*
* @author Kohsuke Kawaguchi
* @see Describable
*/
public abstract class Descriptor<T extends Describable<T>> implements Saveable {
/**
* The class being described by this descriptor.
*/
public transient final Class<? extends T> clazz;
private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>();
/**
* Lazily computed list of properties on {@link #clazz} and on the descriptor itself.
*/
private transient volatile Map<String, PropertyType> propertyTypes,globalPropertyTypes;
/**
* Represents a readable property on {@link Describable}.
*/
public static final class PropertyType {
public final Class clazz;
public final Type type;
private volatile Class itemType;
public final String displayName;
PropertyType(Class clazz, Type type, String displayName) {
this.clazz = clazz;
this.type = type;
this.displayName = displayName;
}
PropertyType(Field f) {
this(f.getType(),f.getGenericType(),f.toString());
}
PropertyType(Method getter) {
this(getter.getReturnType(),getter.getGenericReturnType(),getter.toString());
}
public Enum[] getEnumConstants() {
return (Enum[])clazz.getEnumConstants();
}
/**
* If the property is a collection/array type, what is an item type?
*/
public Class getItemType() {
if(itemType==null)
itemType = computeItemType();
return itemType;
}
private Class computeItemType() {
if(clazz.isArray()) {
return clazz.getComponentType();
}
if(Collection.class.isAssignableFrom(clazz)) {
Type col = Types.getBaseClass(type, Collection.class);
if (col instanceof ParameterizedType)
return Types.erasure(Types.getTypeArgument(col,0));
else
return Object.class;
}
return null;
}
/**
* Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}.
*/
public Descriptor getItemTypeDescriptor() {
return Jenkins.getInstance().getDescriptor(getItemType());
}
public Descriptor getItemTypeDescriptorOrDie() {
Class it = getItemType();
if (it == null) {
throw new AssertionError(clazz + " is not an array/collection type in " + displayName + ". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor");
}
Descriptor d = Jenkins.getInstance().getDescriptor(it);
if (d==null)
throw new AssertionError(it +" is missing its descriptor in "+displayName+". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor");
return d;
}
/**
* Returns all the descriptors that produce types assignable to the property type.
*/
public List<? extends Descriptor> getApplicableDescriptors() {
return Jenkins.getInstance().getDescriptorList(clazz);
}
/**
* Returns all the descriptors that produce types assignable to the item type for a collection property.
*/
public List<? extends Descriptor> getApplicableItemDescriptors() {
return Jenkins.getInstance().getDescriptorList(getItemType());
}
}
/**
* Help file redirect, keyed by the field name to the path.
*
* @see #getHelpFile(String)
*/
private transient final Map<String,String> helpRedirect = new HashMap<String, String>();
/**
*
* @param clazz
* Pass in {@link #self()} to have the descriptor describe itself,
* (this hack is needed since derived types can't call "getClass()" to refer to itself.
*/
protected Descriptor(Class<? extends T> clazz) {
if (clazz==self())
clazz = (Class)getClass();
this.clazz = clazz;
// doing this turns out to be very error prone,
// as field initializers in derived types will override values.
// load();
}
/**
* Infers the type of the corresponding {@link Describable} from the outer class.
* This version works when you follow the common convention, where a descriptor
* is written as the static nested class of the describable class.
*
* @since 1.278
*/
protected Descriptor() {
this.clazz = (Class<T>)getClass().getEnclosingClass();
if(clazz==null)
throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly.");
// detect an type error
Type bt = Types.getBaseClass(getClass(), Descriptor.class);
if (bt instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) bt;
// this 't' is the closest approximation of T of Descriptor<T>.
Class t = Types.erasure(pt.getActualTypeArguments()[0]);
if(!t.isAssignableFrom(clazz))
throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?");
}
// detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up.
// this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html
try {
Method getd = clazz.getMethod("getDescriptor");
if(!getd.getReturnType().isAssignableFrom(getClass())) {
throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType());
}
} catch (NoSuchMethodException e) {
throw new AssertionError(getClass()+" is missing getDescriptor method.");
}
}
/**
* Human readable name of this kind of configurable object.
*/
public abstract String getDisplayName();
/**
* Uniquely identifies this {@link Descriptor} among all the other {@link Descriptor}s.
*
* <p>
* Historically {@link #clazz} is assumed to be unique, so this method uses that as the default,
* but if you are adding {@link Descriptor}s programmatically for the same type, you can change
* this to disambiguate them.
*
* <p>
* To look up {@link Descriptor} from ID, use {@link Jenkins#getDescriptor(String)}.
*
* @return
* Stick to valid Java identifier character, plus '.', which had to be allowed for historical reasons.
*
* @since 1.391
*/
public String getId() {
return clazz.getName();
}
/**
* Unlike {@link #clazz}, return the parameter type 'T', which determines
* the {@link DescriptorExtensionList} that this goes to.
*
* <p>
* In those situations where subtypes cannot provide the type parameter,
* this method can be overridden to provide it.
*/
public Class<T> getT() {
Type subTyping = Types.getBaseClass(getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
throw new IllegalStateException(getClass()+" doesn't extend Descriptor with a type parameter.");
}
return Types.erasure(Types.getTypeArgument(subTyping, 0));
}
/**
* Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}.
* Since {@link Jenkins} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request.
*/
public String getDescriptorUrl() {
return "descriptorByName/"+getId();
}
/**
* Gets the URL that this Descriptor is bound to, relative to the context path.
* @since 1.406
*/
public final String getDescriptorFullUrl() {
return getCurrentDescriptorByNameUrl()+'/'+getDescriptorUrl();
}
/**
* @since 1.402
*/
public static String getCurrentDescriptorByNameUrl() {
StaplerRequest req = Stapler.getCurrentRequest();
// this override allows RenderOnDemandClosure to preserve the proper value
Object url = req.getAttribute("currentDescriptorByNameUrl");
if (url!=null) return url.toString();
Ancestor a = req.findAncestor(DescriptorByNameOwner.class);
return a.getUrl();
}
/**
* If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method,
* return the form-field validation string. Otherwise null.
* <p>
* This method is used to hook up the form validation method to the corresponding HTML input element.
*/
public String getCheckUrl(String fieldName) {
String method = checkMethods.get(fieldName);
if(method==null) {
method = calcCheckUrl(fieldName);
checkMethods.put(fieldName,method);
}
if (method.equals(NONE)) // == would do, but it makes IDE flag a warning
return null;
// put this under the right contextual umbrella.
// a is always non-null because we already have Hudson as the sentinel
return '\'' + jsStringEscape(getCurrentDescriptorByNameUrl()) + "/'+" + method;
}
private String calcCheckUrl(String fieldName) {
String capitalizedFieldName = StringUtils.capitalize(fieldName);
Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName);
if(method==null)
return NONE;
return '\'' + getDescriptorUrl() + "/check" + capitalizedFieldName + '\'' + buildParameterList(method, new StringBuilder()).append(".toString()");
}
/**
* Builds query parameter line by figuring out what should be submitted
*/
private StringBuilder buildParameterList(Method method, StringBuilder query) {
for (Parameter p : ReflectionUtils.getParameters(method)) {
QueryParameter qp = p.annotation(QueryParameter.class);
if (qp!=null) {
String name = qp.value();
if (name.length()==0) name = p.name();
if (name==null || name.length()==0)
continue; // unknown parameter name. we'll report the error when the form is submitted.
RelativePath rp = p.annotation(RelativePath.class);
if (rp!=null)
name = rp.value()+'/'+name;
if (query.length()==0) query.append("+qs(this)");
if (name.equals("value")) {
// The special 'value' parameter binds to the the current field
query.append(".addThis()");
} else {
query.append(".nearBy('"+name+"')");
}
continue;
}
Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler");
if (m!=null) buildParameterList(m,query);
}
return query;
}
/**
* Computes the list of other form fields that the given field depends on, via the doFillXyzItems method,
* and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and
* sets that as the 'fillUrl' attribute.
*/
public void calcFillSettings(String field, Map<String,Object> attributes) {
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doFill" + capitalizedFieldName + "Items";
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName));
// build query parameter line by figuring out what should be submitted
List<String> depends = buildFillDependencies(method, new ArrayList<String>());
if (!depends.isEmpty())
attributes.put("fillDependsOn",Util.join(depends," "));
attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
}
private List<String> buildFillDependencies(Method method, List<String> depends) {
for (Parameter p : ReflectionUtils.getParameters(method)) {
QueryParameter qp = p.annotation(QueryParameter.class);
if (qp!=null) {
String name = qp.value();
if (name.length()==0) name = p.name();
if (name==null || name.length()==0)
continue; // unknown parameter name. we'll report the error when the form is submitted.
RelativePath rp = p.annotation(RelativePath.class);
if (rp!=null)
name = rp.value()+'/'+name;
depends.add(name);
continue;
}
Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler");
if (m!=null)
buildFillDependencies(m,depends);
}
return depends;
}
/**
* Computes the auto-completion setting
*/
public void calcAutoCompleteSettings(String field, Map<String,Object> attributes) {
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doAutoComplete" + capitalizedFieldName;
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
return; // no auto-completion
attributes.put("autoCompleteUrl", String.format("%s/%s/autoComplete%s", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
}
/**
* Used by Jelly to abstract away the handlign of global.jelly vs config.jelly databinding difference.
*/
public @CheckForNull PropertyType getPropertyType(@Nonnull Object instance, @Nonnull String field) {
// in global.jelly, instance==descriptor
return instance==this ? getGlobalPropertyType(field) : getPropertyType(field);
}
/**
* Akin to {@link #getPropertyType(Object,String) but never returns null.
* @throws AssertionError in case the field cannot be found
* @since 1.492
*/
public @Nonnull PropertyType getPropertyTypeOrDie(@Nonnull Object instance, @Nonnull String field) {
PropertyType propertyType = getPropertyType(instance, field);
if (propertyType != null) {
return propertyType;
} else if (instance == this) {
throw new AssertionError(getClass().getName() + " has no property " + field);
} else {
throw new AssertionError(clazz.getName() + " has no property " + field);
}
}
/**
* Obtains the property type of the given field of {@link #clazz}
*/
public PropertyType getPropertyType(String field) {
if(propertyTypes==null)
propertyTypes = buildPropertyTypes(clazz);
return propertyTypes.get(field);
}
/**
* Obtains the property type of the given field of this descriptor.
*/
public PropertyType getGlobalPropertyType(String field) {
if(globalPropertyTypes==null)
globalPropertyTypes = buildPropertyTypes(getClass());
return globalPropertyTypes.get(field);
}
/**
* Given the class, list up its {@link PropertyType}s from its public fields/getters.
*/
private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) {
Map<String, PropertyType> r = new HashMap<String, PropertyType>();
for (Field f : clazz.getFields())
r.put(f.getName(),new PropertyType(f));
for (Method m : clazz.getMethods())
if(m.getName().startsWith("get"))
r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m));
return r;
}
/**
* Gets the class name nicely escaped to be usable as a key in the structured form submission.
*/
public final String getJsonSafeClassName() {
return getId().replace('.','-');
}
/**
* @deprecated
* Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead.
* Deprecated as of 1.145.
*/
public T newInstance(StaplerRequest req) throws FormException {
throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)");
}
/**
* Creates a configured instance from the submitted form.
*
* <p>
* Hudson only invokes this method when the user wants an instance of <tt>T</tt>.
* So there's no need to check that in the implementation.
*
* <p>
* Starting 1.206, the default implementation of this method does the following:
* <pre>
* req.bindJSON(clazz,formData);
* </pre>
* <p>
* ... which performs the databinding on the constructor of {@link #clazz}.
*
* <p>
* For some types of {@link Describable}, such as {@link ListViewColumn}, this method
* can be invoked with null request object for historical reason. Such design is considered
* broken, but due to the compatibility reasons we cannot fix it. Because of this, the
* default implementation gracefully handles null request, but the contract of the method
* still is "request is always non-null." Extension points that need to define the "default instance"
* semantics should define a descriptor subtype and add the no-arg newInstance method.
*
* @param req
* Always non-null (see note above.) This object includes represents the entire submission.
* @param formData
* The JSON object that captures the configuration data for this {@link Descriptor}.
* See http://wiki.jenkins-ci.org/display/JENKINS/Structured+Form+Submission
* Always non-null.
*
* @throws FormException
* Signals a problem in the submitted form.
* @since 1.145
*/
public T newInstance(StaplerRequest req, JSONObject formData) throws FormException {
try {
Method m = getClass().getMethod("newInstance", StaplerRequest.class);
if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) {
// this class overrides newInstance(StaplerRequest).
// maintain the backward compatible behavior
return verifyNewInstance(newInstance(req));
} else {
if (req==null) {
// yes, req is supposed to be always non-null, but see the note above
return verifyNewInstance(clazz.newInstance());
}
// new behavior as of 1.206
return verifyNewInstance(req.bindJSON(clazz,formData));
}
} catch (NoSuchMethodException e) {
throw new AssertionError(e); // impossible
} catch (InstantiationException e) {
throw new Error("Failed to instantiate "+clazz+" from "+formData,e);
} catch (IllegalAccessException e) {
throw new Error("Failed to instantiate "+clazz+" from "+formData,e);
} catch (RuntimeException e) {
throw new RuntimeException("Failed to instantiate "+clazz+" from "+formData,e);
}
}
/**
* Look out for a typical error a plugin developer makes.
* See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html
*/
private T verifyNewInstance(T t) {
if (t!=null && t.getDescriptor()!=this) {
// TODO: should this be a fatal error?
LOGGER.warning("Father of "+ t+" and its getDescriptor() points to two different instances. Probably malplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html");
}
return t;
}
/**
* Returns the {@link Klass} object used for the purpose of loading resources from this descriptor.
*
* This hook enables other JVM languages to provide more integrated lookup.
*/
public Klass<?> getKlass() {
return Klass.java(clazz);
}
/**
* Returns the resource path to the help screen HTML, if any.
*
* <p>
* Starting 1.282, this method uses "convention over configuration" — you should
* just put the "help.html" (and its localized versions, if any) in the same directory
* you put your Jelly view files, and this method will automatically does the right thing.
*
* <p>
* This value is relative to the context root of Hudson, so normally
* the values are something like <tt>"/plugin/emma/help.html"</tt> to
* refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt>
* to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>.
*
* @return
* null to indicate that there's no help.
*/
public String getHelpFile() {
return getHelpFile(null);
}
/**
* Returns the path to the help screen HTML for the given field.
*
* <p>
* The help files are assumed to be at "help/FIELDNAME.html" with possible
* locale variations.
*/
public String getHelpFile(final String fieldName) {
return getHelpFile(getKlass(),fieldName);
}
public String getHelpFile(Klass<?> clazz, String fieldName) {
String v = helpRedirect.get(fieldName);
if (v!=null) return v;
for (Klass<?> c : clazz.getAncestors()) {
String page = "/descriptor/" + getId() + "/help";
String suffix;
if(fieldName==null) {
suffix="";
} else {
page += '/'+fieldName;
suffix='-'+fieldName;
}
try {
if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null)
return page;
} catch (IOException e) {
throw new Error(e);
}
if(getStaticHelpUrl(c, suffix) !=null) return page;
}
return null;
}
/**
* Tells Jenkins that the help file for the field 'fieldName' is defined in the help file for
* the 'fieldNameToRedirectTo' in the 'owner' class.
* @since 1.425
*/
protected void addHelpFileRedirect(String fieldName, Class<? extends Describable> owner, String fieldNameToRedirectTo) {
helpRedirect.put(fieldName,
Jenkins.getInstance().getDescriptor(owner).getHelpFile(fieldNameToRedirectTo));
}
/**
* Checks if the given object is created from this {@link Descriptor}.
*/
public final boolean isInstance( T instance ) {
return clazz.isInstance(instance);
}
/**
* Checks if the type represented by this descriptor is a subtype of the given type.
*/
public final boolean isSubTypeOf(Class type) {
return type.isAssignableFrom(clazz);
}
/**
* @deprecated
* As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}.
*/
public boolean configure( StaplerRequest req ) throws FormException {
return true;
}
/**
* Invoked when the global configuration page is submitted.
*
* Can be overriden to store descriptor-specific information.
*
* @param json
* The JSON object that captures the configuration data for this {@link Descriptor}.
* See http://wiki.jenkins-ci.org/display/JENKINS/Structured+Form+Submission
* @return false
* to keep the client in the same config page.
*/
public boolean configure( StaplerRequest req, JSONObject json ) throws FormException {
// compatibility
return configure(req);
}
public String getConfigPage() {
return getViewPage(clazz, getPossibleViewNames("config"), "config.jelly");
}
public String getGlobalConfigPage() {
return getViewPage(clazz, getPossibleViewNames("global"), null);
}
private String getViewPage(Class<?> clazz, String pageName, String defaultValue) {
return getViewPage(clazz,Collections.singleton(pageName),defaultValue);
}
private String getViewPage(Class<?> clazz, Collection<String> pageNames, String defaultValue) {
while(clazz!=Object.class && clazz!=null) {
for (String pageName : pageNames) {
String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName;
if(clazz.getClassLoader().getResource(name)!=null)
return '/'+name;
}
clazz = clazz.getSuperclass();
}
return defaultValue;
}
protected final String getViewPage(Class<?> clazz, String pageName) {
// We didn't find the configuration page.
// Either this is non-fatal, in which case it doesn't matter what string we return so long as
// it doesn't exist.
// Or this error is fatal, in which case we want the developer to see what page he's missing.
// so we put the page name.
return getViewPage(clazz,pageName,pageName);
}
protected List<String> getPossibleViewNames(String baseName) {
List<String> names = new ArrayList<String>();
for (Facet f : WebApp.get(Jenkins.getInstance().servletContext).facets) {
if (f instanceof JellyCompatibleFacet) {
JellyCompatibleFacet jcf = (JellyCompatibleFacet) f;
for (String ext : jcf.getScriptExtensions())
names.add(baseName +ext);
}
}
return names;
}
/**
* Saves the configuration info to the disk.
*/
public synchronized void save() {
if(BulkChange.contains(this)) return;
try {
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
}
}
/**
* Loads the data from the disk into this object.
*
* <p>
* The constructor of the derived class must call this method.
* (If we do that in the base class, the derived class won't
* get a chance to set default values.)
*/
public synchronized void load() {
XmlFile file = getConfigFile();
if(!file.exists())
return;
try {
file.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+file, e);
}
}
protected final XmlFile getConfigFile() {
return new XmlFile(new File(Jenkins.getInstance().getRootDir(),getId()+".xml"));
}
/**
* Returns the plugin in which this descriptor is defined.
*
* @return
* null to indicate that this descriptor came from the core.
*/
protected PluginWrapper getPlugin() {
return Jenkins.getInstance().getPluginManager().whichPlugin(clazz);
}
/**
* Serves <tt>help.html</tt> from the resource of {@link #clazz}.
*/
public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
if(path.contains("..")) throw new ServletException("Illegal path: "+path);
path = path.replace('/','-');
PluginWrapper pw = getPlugin();
if (pw!=null) {
rsp.setHeader("X-Plugin-Short-Name",pw.getShortName());
rsp.setHeader("X-Plugin-Long-Name",pw.getLongName());
rsp.setHeader("X-Plugin-From", Messages.Descriptor_From(
pw.getLongName().replace("Hudson","Jenkins").replace("hudson","jenkins"), pw.getUrl()));
}
for (Klass<?> c= getKlass(); c!=null; c=c.getSuperClass()) {
RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path);
if(rd!=null) {// template based help page
rd.forward(req,rsp);
return;
}
URL url = getStaticHelpUrl(c, path);
if(url!=null) {
// TODO: generalize macro expansion and perhaps even support JEXL
rsp.setContentType("text/html;charset=UTF-8");
InputStream in = url.openStream();
try {
String literal = IOUtils.toString(in,"UTF-8");
rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath())));
} finally {
IOUtils.closeQuietly(in);
}
return;
}
}
rsp.sendError(SC_NOT_FOUND);
}
private URL getStaticHelpUrl(Klass<?> c, String suffix) {
Locale locale = Stapler.getCurrentRequest().getLocale();
String base = "help"+suffix;
URL url;
url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html");
if(url!=null) return url;
url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html");
if(url!=null) return url;
url = c.getResource(base + '_' + locale.getLanguage() + ".html");
if(url!=null) return url;
// default
return c.getResource(base + ".html");
}
//
// static methods
//
// to work around warning when creating a generic array type
public static <T> T[] toArray( T... values ) {
return values;
}
public static <T> List<T> toList( T... values ) {
return new ArrayList<T>(Arrays.asList(values));
}
public static <T extends Describable<T>>
Map<Descriptor<T>,T> toMap(Iterable<T> describables) {
Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>();
for (T d : describables) {
m.put(d.getDescriptor(),d);
}
return m;
}
/**
* Used to build {@link Describable} instance list from <f:hetero-list> tag.
*
* @param req
* Request that represents the form submission.
* @param formData
* Structured form data that represents the contains data for the list of describables.
* @param key
* The JSON property name for 'formData' that represents the data for the list of describables.
* @param descriptors
* List of descriptors to create instances from.
* @return
* Can be empty but never null.
*/
public static <T extends Describable<T>>
List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
return newInstancesFromHeteroList(req,formData.get(key),descriptors);
}
public static <T extends Describable<T>>
List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
List<T> items = new ArrayList<T>();
if (formData!=null) {
for (Object o : JSONArray.fromObject(formData)) {
JSONObject jo = (JSONObject)o;
String kind = jo.getString("kind");
Descriptor<T> d = find(descriptors, kind);
if (d != null) {
items.add(d.newInstance(req, jo));
}
}
}
return items;
}
/**
* Finds a descriptor from a collection by its class name.
*/
public static @CheckForNull <T extends Descriptor> T find(Collection<? extends T> list, String className) {
for (T d : list) {
if(d.getClass().getName().equals(className))
return d;
}
// Since we introduced Descriptor.getId(), it is a preferred method of identifying descriptor by a string.
// To make that migration easier without breaking compatibility, let's also match up with the id.
for (T d : list) {
if(d.getId().equals(className))
return d;
}
return null;
}
public static @CheckForNull Descriptor find(String className) {
return find(Jenkins.getInstance().getExtensionList(Descriptor.class),className);
}
public static final class FormException extends Exception implements HttpResponse {
private final String formField;
public FormException(String message, String formField) {
super(message);
this.formField = formField;
}
public FormException(String message, Throwable cause, String formField) {
super(message, cause);
this.formField = formField;
}
public FormException(Throwable cause, String formField) {
super(cause);
this.formField = formField;
}
/**
* Which form field contained an error?
*/
public String getFormField() {
return formField;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
if (FormApply.isApply(req)) {
FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.defaultOptions.ERROR)")
.generateResponse(req, rsp, node);
} else {
// for now, we can't really use the field name that caused the problem.
new Failure(getMessage()).generateResponse(req,rsp,node);
}
}
}
private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName());
/**
* Used in {@link #checkMethods} to indicate that there's no check method.
*/
private static final String NONE = "\u0000";
/**
* Special type indicating that {@link Descriptor} describes itself.
* @see Descriptor#Descriptor(Class)
*/
public static final class Self {}
protected static Class self() { return Self.class; }
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_5851_1
|
crossvul-java_data_good_4727_0
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.deploy.hot;
import com.liferay.portal.kernel.deploy.hot.HotDeploy;
import com.liferay.portal.kernel.deploy.hot.HotDeployEvent;
import com.liferay.portal.kernel.deploy.hot.HotDeployException;
import com.liferay.portal.kernel.deploy.hot.HotDeployListener;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.ServletContextPool;
import com.liferay.portal.kernel.template.TemplateManagerUtil;
import com.liferay.portal.kernel.util.BasePortalLifecycle;
import com.liferay.portal.kernel.util.HttpUtil;
import com.liferay.portal.kernel.util.PortalLifecycle;
import com.liferay.portal.kernel.util.PortalLifecycleUtil;
import com.liferay.portal.kernel.util.PropertiesUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
import com.liferay.portal.security.pacl.PACLPolicy;
import com.liferay.portal.security.pacl.PACLPolicyManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.ServletContext;
/**
* @author Ivica Cardic
* @author Brian Wing Shun Chan
* @author Raymond Augé
*/
public class HotDeployImpl implements HotDeploy {
public HotDeployImpl() {
if (_log.isDebugEnabled()) {
_log.debug("Initializing hot deploy manager " + this.hashCode());
}
_dependentHotDeployEvents = new ArrayList<HotDeployEvent>();
_deployedServletContextNames = new HashSet<String>();
_hotDeployListeners = new CopyOnWriteArrayList<HotDeployListener>();
}
public void fireDeployEvent(final HotDeployEvent hotDeployEvent) {
PortalLifecycleUtil.register(
new PACLPortalLifecycle(hotDeployEvent),
PortalLifecycle.METHOD_INIT);
if (_capturePrematureEvents) {
// Capture events that are fired before the portal initialized
PortalLifecycle portalLifecycle = new BasePortalLifecycle() {
@Override
protected void doPortalDestroy() {
}
@Override
protected void doPortalInit() {
fireDeployEvent(hotDeployEvent);
}
};
PortalLifecycleUtil.register(
portalLifecycle, PortalLifecycle.METHOD_INIT);
}
else {
// Fire event
doFireDeployEvent(hotDeployEvent);
}
}
public void fireUndeployEvent(HotDeployEvent hotDeployEvent) {
for (HotDeployListener hotDeployListener : _hotDeployListeners) {
try {
hotDeployListener.invokeUndeploy(hotDeployEvent);
}
catch (HotDeployException hde) {
_log.error(hde, hde);
}
}
_deployedServletContextNames.remove(
hotDeployEvent.getServletContextName());
ClassLoader classLoader = hotDeployEvent.getContextClassLoader();
TemplateManagerUtil.destroy(classLoader);
PACLPolicyManager.unregister(classLoader);
}
public void registerListener(HotDeployListener hotDeployListener) {
_hotDeployListeners.add(hotDeployListener);
}
public void reset() {
_capturePrematureEvents = true;
_dependentHotDeployEvents.clear();
_deployedServletContextNames.clear();
_hotDeployListeners.clear();
}
public void setCapturePrematureEvents(boolean capturePrematureEvents) {
_capturePrematureEvents = capturePrematureEvents;
}
public void unregisterListener(HotDeployListener hotDeployListener) {
_hotDeployListeners.remove(hotDeployListener);
}
public void unregisterListeners() {
_hotDeployListeners.clear();
}
protected void doFireDeployEvent(HotDeployEvent hotDeployEvent) {
String servletContextName = hotDeployEvent.getServletContextName();
if (_deployedServletContextNames.contains(servletContextName)) {
return;
}
boolean hasDependencies = true;
for (String dependentServletContextName :
hotDeployEvent.getDependentServletContextNames()) {
if (!_deployedServletContextNames.contains(
dependentServletContextName)) {
hasDependencies = false;
break;
}
}
if (hasDependencies) {
if (_log.isInfoEnabled()) {
_log.info("Deploying " + servletContextName + " from queue");
}
for (HotDeployListener hotDeployListener : _hotDeployListeners) {
try {
hotDeployListener.invokeDeploy(hotDeployEvent);
}
catch (HotDeployException hde) {
_log.error(hde, hde);
}
}
_deployedServletContextNames.add(servletContextName);
_dependentHotDeployEvents.remove(hotDeployEvent);
ClassLoader contextClassLoader = getContextClassLoader();
try {
setContextClassLoader(
PACLClassLoaderUtil.getPortalClassLoader());
List<HotDeployEvent> dependentEvents =
new ArrayList<HotDeployEvent>(_dependentHotDeployEvents);
for (HotDeployEvent dependentEvent : dependentEvents) {
setContextClassLoader(
dependentEvent.getContextClassLoader());
doFireDeployEvent(dependentEvent);
}
}
finally {
setContextClassLoader(contextClassLoader);
}
}
else {
if (!_dependentHotDeployEvents.contains(hotDeployEvent)) {
if (_log.isInfoEnabled()) {
StringBundler sb = new StringBundler(4);
sb.append("Queueing ");
sb.append(servletContextName);
sb.append(" for deploy because it is missing ");
sb.append(getRequiredServletContextNames(hotDeployEvent));
_log.info(sb.toString());
}
_dependentHotDeployEvents.add(hotDeployEvent);
}
else {
if (_log.isInfoEnabled()) {
for (HotDeployEvent dependentHotDeployEvent :
_dependentHotDeployEvents) {
StringBundler sb = new StringBundler(3);
sb.append(servletContextName);
sb.append(" is still in queue because it is missing ");
sb.append(
getRequiredServletContextNames(
dependentHotDeployEvent));
_log.info(sb.toString());
}
}
}
}
}
protected ClassLoader getContextClassLoader() {
return PACLClassLoaderUtil.getContextClassLoader();
}
protected String getRequiredServletContextNames(
HotDeployEvent hotDeployEvent) {
List<String> requiredServletContextNames = new ArrayList<String>();
for (String dependentServletContextName :
hotDeployEvent.getDependentServletContextNames()) {
if (!_deployedServletContextNames.contains(
dependentServletContextName)) {
requiredServletContextNames.add(dependentServletContextName);
}
}
Collections.sort(requiredServletContextNames);
return StringUtil.merge(requiredServletContextNames, ", ");
}
protected void setContextClassLoader(ClassLoader contextClassLoader) {
PACLClassLoaderUtil.setContextClassLoader(contextClassLoader);
}
private static Log _log = LogFactoryUtil.getLog(HotDeployImpl.class);
private boolean _capturePrematureEvents = true;
private List<HotDeployEvent> _dependentHotDeployEvents;
private Set<String> _deployedServletContextNames;
private List<HotDeployListener> _hotDeployListeners;
private class PACLPortalLifecycle extends BasePortalLifecycle {
public PACLPortalLifecycle(HotDeployEvent hotDeployEvent) {
_servletContext = hotDeployEvent.getServletContext();
_classLoader = hotDeployEvent.getContextClassLoader();
ServletContextPool.put(
_servletContext.getServletContextName(), _servletContext);
}
@Override
protected void doPortalDestroy() {
}
@Override
protected void doPortalInit() throws Exception {
Properties properties = null;
String propertiesString = HttpUtil.URLtoString(
_servletContext.getResource(
"/WEB-INF/liferay-plugin-package.properties"));
if (propertiesString != null) {
properties = PropertiesUtil.load(propertiesString);
}
else {
properties = new Properties();
}
PACLPolicy paclPolicy = PACLPolicyManager.buildPACLPolicy(
_servletContext.getServletContextName(), _classLoader,
properties);
PACLPolicyManager.register(_classLoader, paclPolicy);
}
private ClassLoader _classLoader;
private ServletContext _servletContext;
};
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_0
|
crossvul-java_data_good_2293_3
|
/*
* Copyright 2012 JBoss Inc
*
* Licensed 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.uberfire.security.server;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.uberfire.security.Resource;
import org.uberfire.security.ResourceManager;
import org.uberfire.security.Role;
import org.uberfire.security.impl.RoleImpl;
import org.uberfire.commons.regex.util.AntPathMatcher;
import org.yaml.snakeyaml.Yaml;
import static java.util.Collections.*;
import static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;
import static org.uberfire.commons.validation.Preconditions.*;
import static org.uberfire.security.server.SecurityConstants.*;
public class URLResourceManager implements ResourceManager {
private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
private static final Collection<Class<? extends Resource>> SUPPORTED_TYPES = new ArrayList<Class<? extends Resource>>( 1 ) {{
add( URLResource.class );
}};
private static final String DEFAULT_CONFIG = "exclude:\n" +
" - /*.ico\n" +
" - /image/**\n" +
" - /css/**";
private String configFile = URL_FILTER_CONFIG_YAML;
private final Resources resources;
private final Set<String> excludeCache = Collections.newSetFromMap( new ConcurrentHashMap<String, Boolean>() );
public URLResourceManager( final String configFile ) {
if ( configFile != null && !configFile.isEmpty() ) {
this.configFile = configFile;
}
this.resources = loadConfigData();
}
private Resources loadConfigData() {
final Yaml yaml = new Yaml();
final InputStream stream = URLResourceManager.class.getClassLoader().getResourceAsStream( this.configFile );
final Map result;
if ( stream != null ) {
result = (Map) yaml.load( stream );
} else {
result = (Map) yaml.load( DEFAULT_CONFIG );
}
return new Resources( result );
}
@Override
public boolean supports( final Resource resource ) {
if ( resource instanceof URLResource ) {
return true;
}
return false;
}
@Override
public boolean requiresAuthentication( final Resource resource ) {
final URLResource urlResource;
try {
urlResource = checkInstanceOf( "context", resource, URLResource.class );
} catch ( IllegalArgumentException e ) {
return false;
}
if ( !excludeCache.contains( urlResource.getURL() ) ) {
boolean isExcluded = false;
for ( String excluded : resources.getExcludedResources() ) {
if ( ANT_PATH_MATCHER.match( excluded, urlResource.getURL() ) ) {
isExcluded = true;
excludeCache.add( urlResource.getURL() );
break;
}
}
if ( isExcluded ) {
return false;
}
} else {
return false;
}
return true;
}
public List<Role> getMandatoryRoles( final URLResource urlResource ) {
for ( Map.Entry<String, List<Role>> activeFilteredResource : resources.getMandatoryFilteredResources().entrySet() ) {
if ( ANT_PATH_MATCHER.match( activeFilteredResource.getKey(), urlResource.getURL() ) ) {
return activeFilteredResource.getValue();
}
}
return emptyList();
}
private static class Resources {
private final Map<String, List<Role>> filteredResources;
private final Map<String, List<Role>> mandatoryFilteredResources;
private final Set<String> excludedResources;
private Resources( final Map yaml ) {
checkNotNull( "yaml", yaml );
final Object ofilter = yaml.get( "filter" );
if ( ofilter != null ) {
final List<Map<String, String>> filter = checkInstanceOf( "ofilter", ofilter, List.class );
this.filteredResources = new HashMap<String, List<Role>>( filter.size() );
this.mandatoryFilteredResources = new HashMap<String, List<Role>>( filter.size() );
for ( final Map<String, String> activeFilter : filter ) {
final String pattern = activeFilter.get( "pattern" );
final String access = activeFilter.get( "access" );
checkNotNull( "pattern", pattern );
final List<Role> roles;
if ( access != null ) {
final String[] textRoles = access.split( "," );
roles = new ArrayList<Role>( textRoles.length );
for ( final String textRole : textRoles ) {
roles.add( new RoleImpl( textRole ) );
}
mandatoryFilteredResources.put( pattern, roles );
} else {
roles = emptyList();
}
filteredResources.put( pattern, roles );
}
} else {
this.filteredResources = emptyMap();
this.mandatoryFilteredResources = emptyMap();
}
final Object oexclude = yaml.get( "exclude" );
final List exclude = checkInstanceOf( "exclude", oexclude, List.class );
this.excludedResources = new HashSet<String>( exclude );
}
public Map<String, List<Role>> getFilteredResources() {
return filteredResources;
}
public Set<String> getExcludedResources() {
return excludedResources;
}
public Map<String, List<Role>> getMandatoryFilteredResources() {
return mandatoryFilteredResources;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2293_3
|
crossvul-java_data_good_4727_4
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
import com.liferay.portal.util.PropsValues;
import freemarker.core.Environment;
import freemarker.core.TemplateClassResolver;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.utility.ObjectConstructor;
/**
* @author Raymond Augé
*/
public class LiferayTemplateClassResolver implements TemplateClassResolver {
public Class<?> resolve(
String className, Environment environment, Template template)
throws TemplateException {
if (className.equals(ObjectConstructor.class.getName())) {
throw new TemplateException(
"Instantiating " + className + " is not allowed in the " +
"template for security reasons",
environment);
}
for (String restrictedClassName :
PropsValues.FREEMARKER_ENGINE_RESTRICTED_CLASSES) {
if (className.equals(restrictedClassName)) {
throw new TemplateException(
"Instantiating " + className + " is not allowed in the " +
"template for security reasons",
environment);
}
}
for (String restrictedPackageName :
PropsValues.FREEMARKER_ENGINE_RESTRICTED_PACKAGES) {
if (className.startsWith(restrictedPackageName)) {
throw new TemplateException(
"Instantiating " + className + " is not allowed in the " +
"template for security reasons",
environment);
}
}
try {
return Class.forName(
className, true, PACLClassLoaderUtil.getContextClassLoader());
}
catch (Exception e) {
throw new TemplateException(e, environment);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_4
|
crossvul-java_data_good_2091_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Alan Harder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.model.Result;
import hudson.model.Run;
import hudson.security.AuthorizationMatrixProperty;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.ProjectMatrixAuthorizationStrategy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import jenkins.model.Jenkins;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.MockBuilder;
/**
* Tests for hudson.tasks.BuildTrigger
* @author Alan.Harder@sun.com
*/
public class BuildTriggerTest extends HudsonTestCase {
private FreeStyleProject createDownstreamProject() throws Exception {
FreeStyleProject dp = createFreeStyleProject("downstream");
// Hm, no setQuietPeriod, have to submit form..
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(dp,"configure");
HtmlForm form = page.getFormByName("config");
form.getInputByName("hasCustomQuietPeriod").click();
form.getInputByName("quiet_period").setValueAttribute("0");
submit(form);
assertEquals("set quiet period", 0, dp.getQuietPeriod());
return dp;
}
private void doTriggerTest(boolean evenWhenUnstable, Result triggerResult,
Result dontTriggerResult) throws Exception {
FreeStyleProject p = createFreeStyleProject(),
dp = createDownstreamProject();
p.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
p.getBuildersList().add(new MockBuilder(dontTriggerResult));
jenkins.rebuildDependencyGraph();
// First build should not trigger downstream job
FreeStyleBuild b = p.scheduleBuild2(0).get();
assertNoDownstreamBuild(dp, b);
// Next build should trigger downstream job
p.getBuildersList().replace(new MockBuilder(triggerResult));
b = p.scheduleBuild2(0).get();
assertDownstreamBuild(dp, b);
}
private void assertNoDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
for (int i = 0; i < 3; i++) {
Thread.sleep(200);
assertTrue("downstream build should not run! upstream log: " + getLog(b),
!dp.isInQueue() && !dp.isBuilding() && dp.getLastBuild()==null);
}
}
private void assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
// Wait for downstream build
for (int i = 0; dp.getLastBuild()==null && i < 20; i++) Thread.sleep(100);
assertNotNull("downstream build didn't run.. upstream log: " + getLog(b), dp.getLastBuild());
}
public void testBuildTrigger() throws Exception {
doTriggerTest(false, Result.SUCCESS, Result.UNSTABLE);
}
public void testTriggerEvenWhenUnstable() throws Exception {
doTriggerTest(true, Result.UNSTABLE, Result.FAILURE);
}
private void doMavenTriggerTest(boolean evenWhenUnstable) throws Exception {
FreeStyleProject dp = createDownstreamProject();
configureDefaultMaven();
MavenModuleSet m = createMavenProject();
m.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
if (!evenWhenUnstable) {
// Configure for UNSTABLE
m.setGoals("clean test");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-test-failure.zip")));
} // otherwise do nothing which gets FAILURE
// First build should not trigger downstream project
MavenModuleSetBuild b = m.scheduleBuild2(0).get();
assertNoDownstreamBuild(dp, b);
if (evenWhenUnstable) {
// Configure for UNSTABLE
m.setGoals("clean test");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-test-failure.zip")));
} else {
// Configure for SUCCESS
m.setGoals("clean");
m.setScm(new ExtractResourceSCM(getClass().getResource("maven-empty.zip")));
}
// Next build should trigger downstream project
b = m.scheduleBuild2(0).get();
assertDownstreamBuild(dp, b);
}
public void testMavenBuildTrigger() throws Exception {
doMavenTriggerTest(false);
}
public void testMavenTriggerEvenWhenUnstable() throws Exception {
doMavenTriggerTest(true);
}
public void testConfigureDownstreamProjectSecurity() throws Exception {
jenkins.setSecurityRealm(new LegacySecurityRealm());
ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
auth.add(Jenkins.READ, "alice");
jenkins.setAuthorizationStrategy(auth);
FreeStyleProject upstream = createFreeStyleProject("upstream");
Map<Permission,Set<String>> perms = new HashMap<Permission,Set<String>>();
perms.put(Item.READ, Collections.singleton("alice"));
perms.put(Item.CONFIGURE, Collections.singleton("alice"));
upstream.addProperty(new AuthorizationMatrixProperty(perms));
FreeStyleProject downstream = createFreeStyleProject("downstream");
/* Original SECURITY-55 test case:
downstream.addProperty(new AuthorizationMatrixProperty(Collections.singletonMap(Item.READ, Collections.singleton("alice"))));
*/
WebClient wc = createWebClient();
wc.login("alice");
HtmlPage page = wc.getPage(upstream, "configure");
HtmlForm config = page.getFormByName("config");
config.getButtonByCaption("Add post-build action").click(); // lib/hudson/project/config-publishers2.jelly
page.getAnchorByText("Build other projects").click();
HtmlTextInput childProjects = config.getInputByName("buildTrigger.childProjects");
childProjects.setValueAttribute("downstream");
try {
submit(config);
fail();
} catch (FailingHttpStatusCodeException x) {
assertEquals(403, x.getStatusCode());
}
assertEquals(Collections.emptyList(), upstream.getDownstreamProjects());
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2091_1
|
crossvul-java_data_good_2100_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.FilePath;
import hudson.Functions;
import jenkins.model.Jenkins;
import hudson.remoting.AsyncFutureImpl;
import hudson.remoting.Callable;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.VirtualChannel;
import hudson.security.AccessControlled;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* Various remoting operations related to diagnostics.
*
* <p>
* These code are useful wherever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc.
*
* @author Kohsuke Kawaguchi
* @since 1.175
*/
public final class RemotingDiagnostics {
public static Map<Object,Object> getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.<Object,Object>singletonMap("N/A","N/A");
return channel.call(new GetSystemProperties());
}
private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> {
public Map<Object,Object> call() {
return new TreeMap<Object,Object>(System.getProperties());
}
private static final long serialVersionUID = 1L;
}
public static Map<String,String> getThreadDump(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.singletonMap("N/A","N/A");
return channel.call(new GetThreadDump());
}
public static Future<Map<String,String>> getThreadDumpAsync(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return new AsyncFutureImpl<Map<String, String>>(Collections.singletonMap("N/A","offline"));
return channel.callAsync(new GetThreadDump());
}
private static final class GetThreadDump implements Callable<Map<String,String>,RuntimeException> {
public Map<String,String> call() {
Map<String,String> r = new LinkedHashMap<String,String>();
try {
ThreadInfo[] data = Functions.getThreadInfos();
Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data);
for (ThreadInfo ti : data)
r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti,map));
} catch (LinkageError _) {
// not in JDK6. fall back to JDK5
r.clear();
for (Map.Entry<Thread,StackTraceElement[]> t : Functions.dumpAllThreads().entrySet()) {
StringBuilder buf = new StringBuilder();
for (StackTraceElement e : t.getValue())
buf.append(e).append('\n');
r.put(t.getKey().getName(),buf.toString());
}
}
return r;
}
private static final long serialVersionUID = 1L;
}
/**
* Executes Groovy script remotely.
*/
public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException {
return channel.call(new Script(script));
}
private static final class Script implements DelegatingCallable<String,RuntimeException> {
private final String script;
private transient ClassLoader cl;
private Script(String script) {
this.script = script;
cl = getClassLoader();
}
public ClassLoader getClassLoader() {
return Jenkins.getInstance().getPluginManager().uberClassLoader;
}
public String call() throws RuntimeException {
// if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader.
if (cl==null) cl = Thread.currentThread().getContextClassLoader();
CompilerConfiguration cc = new CompilerConfiguration();
cc.addCompilationCustomizers(new ImportCustomizer().addStarImports(
"jenkins",
"jenkins.model",
"hudson",
"hudson.model"));
GroovyShell shell = new GroovyShell(cl,new Binding(),cc);
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
shell.setVariable("out", pw);
try {
Object output = shell.evaluate(script);
if(output!=null)
pw.println("Result: "+output);
} catch (Throwable t) {
t.printStackTrace(pw);
}
return out.toString();
}
}
/**
* Obtains the heap dump in an HPROF file.
*/
public static FilePath getHeapDump(VirtualChannel channel) throws IOException, InterruptedException {
return channel.call(new Callable<FilePath, IOException>() {
public FilePath call() throws IOException {
final File hprof = File.createTempFile("hudson-heapdump", "hprof");
hprof.delete();
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap",
new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()});
return new FilePath(hprof);
} catch (JMException e) {
throw new IOException2(e);
}
}
private static final long serialVersionUID = 1L;
});
}
/**
* Heap dump, exposable to URL via Stapler.
*
*/
public static class HeapDump {
private final AccessControlled owner;
private final VirtualChannel channel;
public HeapDump(AccessControlled owner, VirtualChannel channel) {
this.owner = owner;
this.channel = channel;
}
/**
* Obtains the heap dump.
*/
public void doIndex(StaplerResponse rsp) throws IOException {
rsp.sendRedirect("heapdump.hprof");
}
@WebMethod(name="heapdump.hprof")
public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {
owner.checkPermission(Jenkins.RUN_SCRIPTS);
rsp.setContentType("application/octet-stream");
FilePath dump = obtain();
try {
dump.copyTo(rsp.getCompressedOutputStream(req));
} finally {
dump.delete();
}
}
public FilePath obtain() throws IOException, InterruptedException {
return RemotingDiagnostics.getHeapDump(channel);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2100_0
|
crossvul-java_data_good_3820_3
|
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.sync;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.PersistenceException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.candlepin.audit.EventSink;
import org.candlepin.config.Config;
import org.candlepin.controller.PoolManager;
import org.candlepin.controller.Refresher;
import org.candlepin.model.CertificateSerialCurator;
import org.candlepin.model.ConsumerType;
import org.candlepin.model.ConsumerTypeCurator;
import org.candlepin.model.ContentCurator;
import org.candlepin.model.ExporterMetadata;
import org.candlepin.model.ExporterMetadataCurator;
import org.candlepin.model.Owner;
import org.candlepin.model.OwnerCurator;
import org.candlepin.model.Product;
import org.candlepin.model.ProductCurator;
import org.candlepin.model.Subscription;
import org.candlepin.model.SubscriptionCurator;
import org.candlepin.pki.PKIUtility;
import org.candlepin.util.VersionUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.exception.ConstraintViolationException;
import org.xnap.commons.i18n.I18n;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
/**
* Importer
*/
public class Importer {
private static Logger log = Logger.getLogger(Importer.class);
/**
*
* files we use to perform import
*/
enum ImportFile {
META("meta.json"),
CONSUMER_TYPE("consumer_types"),
CONSUMER("consumer.json"),
ENTITLEMENTS("entitlements"),
ENTITLEMENT_CERTIFICATES("entitlement_certificates"),
PRODUCTS("products"),
RULES("rules");
private String fileName;
ImportFile(String fileName) {
this.fileName = fileName;
}
public String fileName() {
return fileName;
}
}
/**
* Keys representing the various errors that can occur during a manifest
* import, but be overridden with forces.
*/
public enum Conflict {
MANIFEST_OLD, MANIFEST_SAME, DISTRIBUTOR_CONFLICT, SIGNATURE_CONFLICT
}
private ConsumerTypeCurator consumerTypeCurator;
private ProductCurator productCurator;
private ObjectMapper mapper;
private RulesImporter rulesImporter;
private OwnerCurator ownerCurator;
private ContentCurator contentCurator;
private SubscriptionCurator subCurator;
private PoolManager poolManager;
private PKIUtility pki;
private Config config;
private ExporterMetadataCurator expMetaCurator;
private CertificateSerialCurator csCurator;
private EventSink sink;
private I18n i18n;
@Inject
public Importer(ConsumerTypeCurator consumerTypeCurator, ProductCurator productCurator,
RulesImporter rulesImporter, OwnerCurator ownerCurator,
ContentCurator contentCurator, SubscriptionCurator subCurator, PoolManager pm,
PKIUtility pki, Config config, ExporterMetadataCurator emc,
CertificateSerialCurator csc, EventSink sink, I18n i18n) {
this.config = config;
this.consumerTypeCurator = consumerTypeCurator;
this.productCurator = productCurator;
this.rulesImporter = rulesImporter;
this.ownerCurator = ownerCurator;
this.contentCurator = contentCurator;
this.subCurator = subCurator;
this.poolManager = pm;
this.mapper = SyncUtils.getObjectMapper(this.config);
this.pki = pki;
this.expMetaCurator = emc;
this.csCurator = csc;
this.sink = sink;
this.i18n = i18n;
}
/**
* Check to make sure the meta data is newer than the imported data.
* @param type ExporterMetadata.TYPE_PER_USER or TYPE_SYSTEM
* @param owner Owner in the case of PER_USER
* @param meta meta.json file
* @param forcedConflicts Conflicts we will override if encountered
* @throws IOException thrown if there's a problem reading the file
* @throws ImporterException thrown if the metadata is invalid.
*/
public void validateMetadata(String type, Owner owner, File meta,
ConflictOverrides forcedConflicts)
throws IOException, ImporterException {
Meta m = mapper.readValue(meta, Meta.class);
if (type == null) {
throw new ImporterException(i18n.tr("Wrong metadata type"));
}
ExporterMetadata lastrun = null;
if (ExporterMetadata.TYPE_SYSTEM.equals(type)) {
lastrun = expMetaCurator.lookupByType(type);
}
else if (ExporterMetadata.TYPE_PER_USER.equals(type)) {
if (owner == null) {
throw new ImporterException(i18n.tr("Invalid owner"));
}
lastrun = expMetaCurator.lookupByTypeAndOwner(type, owner);
}
if (lastrun == null) {
// this is our first import, let's create a new entry
lastrun = new ExporterMetadata(type, m.getCreated(), owner);
lastrun = expMetaCurator.create(lastrun);
}
else {
if (lastrun.getExported().compareTo(m.getCreated()) > 0) {
if (!forcedConflicts.isForced(Importer.Conflict.MANIFEST_OLD)) {
throw new ImportConflictException(i18n.tr(
"Import is older than existing data"),
Importer.Conflict.MANIFEST_OLD);
}
else {
log.warn("Manifest older than existing data.");
}
}
else if (lastrun.getExported().compareTo(m.getCreated()) == 0) {
if (!forcedConflicts.isForced(Importer.Conflict.MANIFEST_SAME)) {
throw new ImportConflictException(i18n.tr(
"Import is the same as existing data"),
Importer.Conflict.MANIFEST_SAME);
}
else {
log.warn("Manifest same as existing data.");
}
}
lastrun.setExported(m.getCreated());
expMetaCurator.merge(lastrun);
}
}
public Map<String, Object> loadExport(Owner owner, File exportFile,
ConflictOverrides overrides)
throws ImporterException {
File tmpDir = null;
InputStream exportStream = null;
Map<String, Object> result = new HashMap<String, Object>();
try {
tmpDir = new SyncUtils(config).makeTempDir("import");
extractArchive(tmpDir, exportFile);
File signature = new File(tmpDir, "signature");
if (signature.length() == 0) {
throw new ImportExtractionException(i18n.tr("The archive does not " +
"contain the required signature file"));
}
exportStream = new FileInputStream(new File(tmpDir, "consumer_export.zip"));
boolean verifiedSignature = pki.verifySHA256WithRSAHashWithUpstreamCACert(
exportStream,
loadSignature(new File(tmpDir, "signature")));
if (!verifiedSignature) {
log.warn("Archive signature check failed.");
if (!overrides
.isForced(Conflict.SIGNATURE_CONFLICT)) {
/*
* Normally for import conflicts that can be overridden, we try to
* report them all the first time so if the user intends to override,
* they can do so with just one more request. However in the case of
* a bad signature, we're going to report immediately due to the nature
* of what this might mean.
*/
throw new ImportConflictException(
i18n.tr("Archive failed signature check"),
Conflict.SIGNATURE_CONFLICT);
}
else {
log.warn("Ignoring signature check failure.");
}
}
File consumerExport = new File(tmpDir, "consumer_export.zip");
File exportDir = extractArchive(tmpDir, consumerExport);
Map<String, File> importFiles = new HashMap<String, File>();
File[] listFiles = exportDir.listFiles();
if (listFiles == null || listFiles.length == 0) {
throw new ImportExtractionException(i18n.tr("The consumer_export " +
"archive has no contents"));
}
for (File file : listFiles) {
importFiles.put(file.getName(), file);
}
ConsumerDto consumer = importObjects(owner, importFiles, overrides);
Meta m = mapper.readValue(importFiles.get(ImportFile.META.fileName()),
Meta.class);
result.put("consumer", consumer);
result.put("meta", m);
return result;
}
catch (FileNotFoundException fnfe) {
log.error("Archive file does not contain consumer_export.zip", fnfe);
throw new ImportExtractionException(i18n.tr("The archive does not contain " +
"the required consumer_export.zip file"));
}
catch (ConstraintViolationException cve) {
log.error("Failed to import archive", cve);
throw new ImporterException(i18n.tr("Failed to import archive"),
cve);
}
catch (PersistenceException pe) {
log.error("Failed to import archive", pe);
throw new ImporterException(i18n.tr("Failed to import archive"),
pe);
}
catch (IOException e) {
log.error("Exception caught importing archive", e);
throw new ImportExtractionException("unable to extract export archive", e);
}
catch (CertificateException e) {
log.error("Certificate exception checking archive signature", e);
throw new ImportExtractionException(
"Certificate exception checking archive signature", e);
}
finally {
if (tmpDir != null) {
try {
FileUtils.deleteDirectory(tmpDir);
}
catch (IOException e) {
log.error("Failed to delete extracted export", e);
}
}
if (exportStream != null) {
try {
exportStream.close();
}
catch (Exception e) {
// nothing we can do.
}
}
}
}
@Transactional(rollbackOn = {IOException.class, ImporterException.class,
RuntimeException.class, ImportConflictException.class})
// WARNING: Keep this method public, otherwise @Transactional is ignored:
ConsumerDto importObjects(Owner owner, Map<String, File> importFiles,
ConflictOverrides overrides)
throws IOException, ImporterException {
File metadata = importFiles.get(ImportFile.META.fileName());
if (metadata == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required meta.json file"));
}
File rules = importFiles.get(ImportFile.RULES.fileName());
if (rules == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required rules directory"));
}
if (rules.listFiles().length == 0) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required rules file(s)"));
}
File consumerTypes = importFiles.get(ImportFile.CONSUMER_TYPE.fileName());
if (consumerTypes == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required consumer_types directory"));
}
File consumerFile = importFiles.get(ImportFile.CONSUMER.fileName());
if (consumerFile == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required consumer.json file"));
}
File products = importFiles.get(ImportFile.PRODUCTS.fileName());
File entitlements = importFiles.get(ImportFile.ENTITLEMENTS.fileName());
if (products != null && entitlements == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required entitlements directory"));
}
// system level elements
/*
* Checking a system wide last import date breaks multi-tenant deployments whenever
* one org imports a manifest slightly older than another org who has already
* imported. Disabled for now. See bz #769644.
*/
// validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, metadata, force);
// If any calls find conflicts we'll assemble them into one exception detailing all
// the conflicts which occurred, so the caller can override them all at once
// if desired:
List<ImportConflictException> conflictExceptions =
new LinkedList<ImportConflictException>();
importRules(rules.listFiles(), metadata);
importConsumerTypes(consumerTypes.listFiles());
// per user elements
try {
validateMetadata(ExporterMetadata.TYPE_PER_USER, owner, metadata,
overrides);
}
catch (ImportConflictException e) {
conflictExceptions.add(e);
}
ConsumerDto consumer = null;
try {
consumer = importConsumer(owner, consumerFile, overrides);
}
catch (ImportConflictException e) {
conflictExceptions.add(e);
}
// At this point we're done checking for any potential conflicts:
if (!conflictExceptions.isEmpty()) {
log.error("Conflicts occurred during import that were not overridden:");
for (ImportConflictException e : conflictExceptions) {
log.error(e.message().getConflicts());
}
throw new ImportConflictException(conflictExceptions);
}
// If the consumer has no entitlements, this products directory will end up empty.
// This also implies there will be no entitlements to import.
if (importFiles.get(ImportFile.PRODUCTS.fileName()) != null) {
Refresher refresher = poolManager.getRefresher();
ProductImporter importer = new ProductImporter(productCurator, contentCurator, poolManager);
Set<Product> productsToImport = importProducts(
importFiles.get(ImportFile.PRODUCTS.fileName()).listFiles(),
importer);
Set<Product> modifiedProducts = importer.getChangedProducts(productsToImport);
for (Product product : modifiedProducts) {
refresher.add(product);
}
importer.store(productsToImport);
importEntitlements(owner, productsToImport, entitlements.listFiles());
refresher.add(owner);
refresher.run();
}
else {
log.warn("No products found to import, skipping product and entitlement import.");
}
return consumer;
}
public void importRules(File[] rulesFiles, File metadata) throws IOException {
// only import rules if versions are ok
Meta m = mapper.readValue(metadata, Meta.class);
if (VersionUtil.getRulesVersionCompatibility(m.getVersion())) {
// Only importing a single rules file now.
Reader reader = null;
try {
reader = new FileReader(rulesFiles[0]);
rulesImporter.importObject(reader, m.getVersion());
}
finally {
if (reader != null) {
reader.close();
}
}
}
else {
log.warn(
i18n.tr(
"Incompatible rules: import version {0} older than our version {1}.",
m.getVersion(), VersionUtil.getVersionString()));
log.warn(
i18n.tr("Manifest data will be imported without rules import."));
}
}
public void importConsumerTypes(File[] consumerTypes) throws IOException {
ConsumerTypeImporter importer = new ConsumerTypeImporter(consumerTypeCurator);
Set<ConsumerType> consumerTypeObjs = new HashSet<ConsumerType>();
for (File consumerType : consumerTypes) {
Reader reader = null;
try {
reader = new FileReader(consumerType);
consumerTypeObjs.add(importer.createObject(mapper, reader));
}
finally {
if (reader != null) {
reader.close();
}
}
}
importer.store(consumerTypeObjs);
}
public ConsumerDto importConsumer(Owner owner, File consumerFile,
ConflictOverrides forcedConflicts)
throws IOException, SyncDataFormatException {
ConsumerImporter importer = new ConsumerImporter(ownerCurator, i18n);
Reader reader = null;
ConsumerDto consumer = null;
try {
reader = new FileReader(consumerFile);
consumer = importer.createObject(mapper, reader);
importer.store(owner, consumer, forcedConflicts);
}
finally {
if (reader != null) {
reader.close();
}
}
return consumer;
}
public Set<Product> importProducts(File[] products, ProductImporter importer)
throws IOException {
Set<Product> productsToImport = new HashSet<Product>();
for (File product : products) {
// Skip product.pem's, we just need the json to import:
if (product.getName().endsWith(".json")) {
log.debug("Import product: " + product.getName());
Reader reader = null;
try {
reader = new FileReader(product);
productsToImport.add(importer.createObject(mapper, reader));
}
finally {
if (reader != null) {
reader.close();
}
}
}
}
// TODO: Do we need to cleanup unused products? Looked at this earlier and it
// looks somewhat complex and a little bit dangerous, so we're leaving them
// around for now.
return productsToImport;
}
public void importEntitlements(Owner owner, Set<Product> products, File[] entitlements)
throws IOException, SyncDataFormatException {
EntitlementImporter importer = new EntitlementImporter(subCurator, csCurator,
sink, i18n);
Map<String, Product> productsById = new HashMap<String, Product>();
for (Product product : products) {
productsById.put(product.getId(), product);
}
Set<Subscription> subscriptionsToImport = new HashSet<Subscription>();
for (File entitlement : entitlements) {
Reader reader = null;
try {
log.debug("Import entitlement: " + entitlement.getName());
reader = new FileReader(entitlement);
subscriptionsToImport.add(importer.importObject(mapper, reader, owner, productsById));
}
finally {
if (reader != null) {
reader.close();
}
}
}
importer.store(owner, subscriptionsToImport);
}
/**
* Create a tar.gz archive of the exported directory.
*
* @param exportDir Directory where Candlepin data was exported.
* @return File reference to the new archive tar.gz.
*/
private File extractArchive(File tempDir, File exportFile)
throws IOException, ImportExtractionException {
log.info("Extracting archive to: " + tempDir.getAbsolutePath());
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(exportFile));
ZipEntry zipentry = zipinputstream.getNextEntry();
if (zipentry == null) {
throw new ImportExtractionException(i18n.tr("The archive {0} is not " +
"a properly compressed file or is empty", exportFile.getName()));
}
while (zipentry != null) {
//for each entry to be extracted
String entryName = zipentry.getName();
if (log.isDebugEnabled()) {
log.debug("entryname " + entryName);
}
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory != null) {
new File(tempDir, directory).mkdirs();
}
fileoutputstream = new FileOutputStream(new File(tempDir, entryName));
int n;
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
return new File(tempDir.getAbsolutePath(), "export");
}
private byte[] loadSignature(File signatureFile) throws IOException {
FileInputStream signature = null;
// signature is never going to be a huge file, therefore cast is a-okay
byte[] signatureBytes = new byte[(int) signatureFile.length()];
try {
signature = new FileInputStream(signatureFile);
int offset = 0;
int numRead = 0;
while (offset < signatureBytes.length && numRead >= 0) {
numRead = signature.read(signatureBytes, offset,
signatureBytes.length - offset);
offset += numRead;
}
return signatureBytes;
}
finally {
if (signature != null) {
try {
signature.close();
}
catch (IOException e) {
// nothing we can do about this
}
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_3820_3
|
crossvul-java_data_good_5851_2
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Martin Eigenbrodt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
import jenkins.model.DependencyDeclarer;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import jenkins.model.Jenkins;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.tasks.BuildTrigger.DescriptorImpl.ItemListenerImpl;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Triggers builds of other projects.
*
* <p>
* Despite what the name suggests, this class doesn't actually trigger other jobs
* as a part of {@link #perform} method. Its main job is to simply augment
* {@link DependencyGraph}. Jobs are responsible for triggering downstream jobs
* on its own, because dependencies may come from other sources.
*
* <p>
* This class, however, does provide the {@link #execute(AbstractBuild, BuildListener, BuildTrigger)}
* method as a convenience method to invoke downstream builds.
*
* @author Kohsuke Kawaguchi
*/
public class BuildTrigger extends Recorder implements DependencyDeclarer {
/**
* Comma-separated list of other projects to be scheduled.
*/
private String childProjects;
/**
* Threshold status to trigger other builds.
*
* For compatibility reasons, this field could be null, in which case
* it should read as "SUCCESS".
*/
private final Result threshold;
public BuildTrigger(String childProjects, boolean evenIfUnstable) {
this(childProjects,evenIfUnstable ? Result.UNSTABLE : Result.SUCCESS);
}
@DataBoundConstructor
public BuildTrigger(String childProjects, String threshold) {
this(childProjects, Result.fromString(StringUtils.defaultString(threshold, Result.SUCCESS.toString())));
}
public BuildTrigger(String childProjects, Result threshold) {
if(childProjects==null)
throw new IllegalArgumentException();
this.childProjects = childProjects;
this.threshold = threshold;
}
public BuildTrigger(List<AbstractProject> childProjects, Result threshold) {
this((Collection<AbstractProject>)childProjects,threshold);
}
public BuildTrigger(Collection<? extends AbstractProject> childProjects, Result threshold) {
this(Items.toNameList(childProjects),threshold);
}
public String getChildProjectsValue() {
return childProjects;
}
public Result getThreshold() {
if(threshold==null)
return Result.SUCCESS;
else
return threshold;
}
/**
* @deprecated as of 1.406
* Use {@link #getChildProjects(ItemGroup)}
*/
public List<AbstractProject> getChildProjects() {
return getChildProjects(Jenkins.getInstance());
}
public List<AbstractProject> getChildProjects(AbstractProject owner) {
return getChildProjects(owner==null?null:owner.getParent());
}
public List<AbstractProject> getChildProjects(ItemGroup base) {
return Items.fromNameList(base,childProjects,AbstractProject.class);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/**
* Checks if this trigger has the exact same set of children as the given list.
*/
public boolean hasSame(AbstractProject owner, Collection<? extends AbstractProject> projects) {
List<AbstractProject> children = getChildProjects(owner);
return children.size()==projects.size() && children.containsAll(projects);
}
/**
* @deprecated as of 1.406
* Use {@link #hasSame(AbstractProject, Collection)}
*/
public boolean hasSame(Collection<? extends AbstractProject> projects) {
return hasSame(null,projects);
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
return true;
}
/**
* @deprecated since 1.341; use {@link #execute(AbstractBuild,BuildListener)}
*/
@Deprecated
public static boolean execute(AbstractBuild build, BuildListener listener, BuildTrigger trigger) {
return execute(build, listener);
}
/**
* Convenience method to trigger downstream builds.
*
* @param build
* The current build. Its downstreams will be triggered.
* @param listener
* Receives the progress report.
*/
public static boolean execute(AbstractBuild build, BuildListener listener) {
PrintStream logger = listener.getLogger();
// Check all downstream Project of the project, not just those defined by BuildTrigger
final DependencyGraph graph = Jenkins.getInstance().getDependencyGraph();
List<Dependency> downstreamProjects = new ArrayList<Dependency>(
graph.getDownstreamDependencies(build.getProject()));
// Sort topologically
Collections.sort(downstreamProjects, new Comparator<Dependency>() {
public int compare(Dependency lhs, Dependency rhs) {
// Swapping lhs/rhs to get reverse sort:
return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
}
});
for (Dependency dep : downstreamProjects) {
AbstractProject p = dep.getDownstreamProject();
if (p.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
continue;
}
List<Action> buildActions = new ArrayList<Action>();
if (dep.shouldTriggerBuild(build, listener, buildActions)) {
// this is not completely accurate, as a new build might be triggered
// between these calls
String name = ModelHyperlinkNote.encodeTo(p)+" #"+p.getNextBuildNumber();
if(p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build),
buildActions.toArray(new Action[buildActions.size()]))) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
}
}
return true;
}
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
for (AbstractProject p : getChildProjects(owner))
graph.addDependency(new Dependency(owner, p) {
@Override
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener,
List<Action> actions) {
return build.getResult().isBetterOrEqualTo(threshold);
}
});
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/**
* Called from {@link ItemListenerImpl} when a job is renamed.
*
* @return true if this {@link BuildTrigger} is changed and needs to be saved.
*/
public boolean onJobRenamed(String oldName, String newName) {
// quick test
if(!childProjects.contains(oldName))
return false;
boolean changed = false;
// we need to do this per string, since old Project object is already gone.
String[] projects = childProjects.split(",");
for( int i=0; i<projects.length; i++ ) {
if(projects[i].trim().equals(oldName)) {
projects[i] = newName;
changed = true;
}
}
if(changed) {
StringBuilder b = new StringBuilder();
for (String p : projects) {
if(b.length()>0) b.append(',');
b.append(p);
}
childProjects = b.toString();
}
return changed;
}
/**
* Correct broken data gracefully (#1537)
*/
private Object readResolve() {
if(childProjects==null)
return childProjects="";
return this;
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.BuildTrigger_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/downstream.html";
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String childProjectsString = formData.getString("childProjects").trim();
if (childProjectsString.endsWith(",")) {
childProjectsString = childProjectsString.substring(0, childProjectsString.length() - 1).trim();
}
return new BuildTrigger(
childProjectsString,
formData.optString("threshold", Result.SUCCESS.toString()));
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public boolean showEvenIfUnstableOption(@CheckForNull Class<? extends AbstractProject<?,?>> jobType) {
// UGLY: for promotion process, this option doesn't make sense.
return jobType == null || !jobType.getName().contains("PromotionProcess");
}
/**
* Form validation method.
*/
public FormValidation doCheck(@AncestorInPath Item project, @QueryParameter String value, @QueryParameter boolean upstream) {
// Require CONFIGURE permission on this project
if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.getInstance().getItem(projectName,project,Item.class);
if(item==null)
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName,
AbstractProject.findNearest(projectName,project.getParent()).getRelativeNameFrom(project)));
if(!(item instanceof AbstractProject))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
if (!upstream && !item.hasPermission(Item.BUILD)) {
return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName));
}
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteChildProjects(@QueryParameter String value, @AncestorInPath Item self, @AncestorInPath ItemGroup container) {
return AutoCompletionCandidates.ofJobNames(Job.class,value,self,container);
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onRenamed(Item item, String oldName, String newName) {
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for( Project<?,?> p : Jenkins.getInstance().getAllItems(Project.class) ) {
BuildTrigger t = p.getPublishersList().get(BuildTrigger.class);
if(t!=null) {
if(t.onJobRenamed(oldName,newName)) {
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from "+oldName+" to "+newName,e);
}
}
}
}
}
}
}
private static final Logger LOGGER = Logger.getLogger(BuildTrigger.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_5851_2
|
crossvul-java_data_bad_3820_3
|
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.sync;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.PersistenceException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.candlepin.audit.EventSink;
import org.candlepin.config.Config;
import org.candlepin.controller.PoolManager;
import org.candlepin.controller.Refresher;
import org.candlepin.model.CertificateSerialCurator;
import org.candlepin.model.ConsumerType;
import org.candlepin.model.ConsumerTypeCurator;
import org.candlepin.model.ContentCurator;
import org.candlepin.model.ExporterMetadata;
import org.candlepin.model.ExporterMetadataCurator;
import org.candlepin.model.Owner;
import org.candlepin.model.OwnerCurator;
import org.candlepin.model.Product;
import org.candlepin.model.ProductCurator;
import org.candlepin.model.Subscription;
import org.candlepin.model.SubscriptionCurator;
import org.candlepin.pki.PKIUtility;
import org.candlepin.util.VersionUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.exception.ConstraintViolationException;
import org.xnap.commons.i18n.I18n;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
/**
* Importer
*/
public class Importer {
private static Logger log = Logger.getLogger(Importer.class);
/**
*
* files we use to perform import
*/
enum ImportFile {
META("meta.json"),
CONSUMER_TYPE("consumer_types"),
CONSUMER("consumer.json"),
ENTITLEMENTS("entitlements"),
ENTITLEMENT_CERTIFICATES("entitlement_certificates"),
PRODUCTS("products"),
RULES("rules");
private String fileName;
ImportFile(String fileName) {
this.fileName = fileName;
}
public String fileName() {
return fileName;
}
}
/**
* Keys representing the various errors that can occur during a manifest
* import, but be overridden with forces.
*/
public enum Conflict {
MANIFEST_OLD, MANIFEST_SAME, DISTRIBUTOR_CONFLICT, SIGNATURE_CONFLICT
}
private ConsumerTypeCurator consumerTypeCurator;
private ProductCurator productCurator;
private ObjectMapper mapper;
private RulesImporter rulesImporter;
private OwnerCurator ownerCurator;
private ContentCurator contentCurator;
private SubscriptionCurator subCurator;
private PoolManager poolManager;
private PKIUtility pki;
private Config config;
private ExporterMetadataCurator expMetaCurator;
private CertificateSerialCurator csCurator;
private EventSink sink;
private I18n i18n;
@Inject
public Importer(ConsumerTypeCurator consumerTypeCurator, ProductCurator productCurator,
RulesImporter rulesImporter, OwnerCurator ownerCurator,
ContentCurator contentCurator, SubscriptionCurator subCurator, PoolManager pm,
PKIUtility pki, Config config, ExporterMetadataCurator emc,
CertificateSerialCurator csc, EventSink sink, I18n i18n) {
this.config = config;
this.consumerTypeCurator = consumerTypeCurator;
this.productCurator = productCurator;
this.rulesImporter = rulesImporter;
this.ownerCurator = ownerCurator;
this.contentCurator = contentCurator;
this.subCurator = subCurator;
this.poolManager = pm;
this.mapper = SyncUtils.getObjectMapper(this.config);
this.pki = pki;
this.expMetaCurator = emc;
this.csCurator = csc;
this.sink = sink;
this.i18n = i18n;
}
/**
* Check to make sure the meta data is newer than the imported data.
* @param type ExporterMetadata.TYPE_PER_USER or TYPE_SYSTEM
* @param owner Owner in the case of PER_USER
* @param meta meta.json file
* @param forcedConflicts Conflicts we will override if encountered
* @throws IOException thrown if there's a problem reading the file
* @throws ImporterException thrown if the metadata is invalid.
*/
public void validateMetadata(String type, Owner owner, File meta,
ConflictOverrides forcedConflicts)
throws IOException, ImporterException {
Meta m = mapper.readValue(meta, Meta.class);
if (type == null) {
throw new ImporterException(i18n.tr("Wrong metadata type"));
}
ExporterMetadata lastrun = null;
if (ExporterMetadata.TYPE_SYSTEM.equals(type)) {
lastrun = expMetaCurator.lookupByType(type);
}
else if (ExporterMetadata.TYPE_PER_USER.equals(type)) {
if (owner == null) {
throw new ImporterException(i18n.tr("Invalid owner"));
}
lastrun = expMetaCurator.lookupByTypeAndOwner(type, owner);
}
if (lastrun == null) {
// this is our first import, let's create a new entry
lastrun = new ExporterMetadata(type, m.getCreated(), owner);
lastrun = expMetaCurator.create(lastrun);
}
else {
if (lastrun.getExported().compareTo(m.getCreated()) > 0) {
if (!forcedConflicts.isForced(Importer.Conflict.MANIFEST_OLD)) {
throw new ImportConflictException(i18n.tr(
"Import is older than existing data"),
Importer.Conflict.MANIFEST_OLD);
}
else {
log.warn("Manifest older than existing data.");
}
}
else if (lastrun.getExported().compareTo(m.getCreated()) == 0) {
if (!forcedConflicts.isForced(Importer.Conflict.MANIFEST_SAME)) {
throw new ImportConflictException(i18n.tr(
"Import is the same as existing data"),
Importer.Conflict.MANIFEST_SAME);
}
else {
log.warn("Manifest same as existing data.");
}
}
lastrun.setExported(m.getCreated());
expMetaCurator.merge(lastrun);
}
}
public Map<String, Object> loadExport(Owner owner, File exportFile,
ConflictOverrides overrides)
throws ImporterException {
File tmpDir = null;
InputStream exportStream = null;
Map<String, Object> result = new HashMap<String, Object>();
try {
tmpDir = new SyncUtils(config).makeTempDir("import");
extractArchive(tmpDir, exportFile);
// only need this call when sig file is verified
// exportStream = new FileInputStream(new File(tmpDir, "consumer_export.zip"));
/*
* Disabling this once again for a little bit longer. Dependent projects
* are not yet ready for it, and we're having some difficulty with the actual
* upstream cert to use.
*
* When we bring this back, we should probably report this conflict
* immediately, rather than continuing to extract and trying to find any
* other conflicts to pass back.
*/
// boolean verifiedSignature = pki.verifySHA256WithRSAHashWithUpstreamCACert(
// exportStream,
// loadSignature(new File(tmpDir, "signature")));
// if (!verifiedSignature) {
// log.warn("Manifest signature check failed.");
// if (!forcedConflicts
// .isForced(ImportConflicts.Conflict.SIGNATURE_CONFLICT)) {
// conflicts.addConflict(
// i18n.tr("Failed import file hash check."),
// ImportConflicts.Conflict.SIGNATURE_CONFLICT);
// }
// else {
// log.warn("Ignoring signature check failure.");
// }
// }
File signature = new File(tmpDir, "signature");
if (signature.length() == 0) {
throw new ImportExtractionException(i18n.tr("The archive does not " +
"contain the required signature file"));
}
File consumerExport = new File(tmpDir, "consumer_export.zip");
File exportDir = extractArchive(tmpDir, consumerExport);
Map<String, File> importFiles = new HashMap<String, File>();
File[] listFiles = exportDir.listFiles();
if (listFiles == null || listFiles.length == 0) {
throw new ImportExtractionException(i18n.tr("The consumer_export " +
"archive has no contents"));
}
for (File file : listFiles) {
importFiles.put(file.getName(), file);
}
ConsumerDto consumer = importObjects(owner, importFiles, overrides);
Meta m = mapper.readValue(importFiles.get(ImportFile.META.fileName()),
Meta.class);
result.put("consumer", consumer);
result.put("meta", m);
return result;
}
// catch (CertificateException e) {
// log.error("Exception caught importing archive", e);
// throw new ImportExtractionException("unable to extract export archive", e);
// }
catch (FileNotFoundException fnfe) {
log.error("Archive file does not contain consumer_export.zip", fnfe);
throw new ImportExtractionException(i18n.tr("The archive does not contain " +
"the required consumer_export.zip file"));
}
catch (ConstraintViolationException cve) {
log.error("Failed to import archive", cve);
throw new ImporterException(i18n.tr("Failed to import archive"),
cve);
}
catch (PersistenceException pe) {
log.error("Failed to import archive", pe);
throw new ImporterException(i18n.tr("Failed to import archive"),
pe);
}
catch (IOException e) {
log.error("Exception caught importing archive", e);
throw new ImportExtractionException("unable to extract export archive", e);
}
finally {
if (tmpDir != null) {
try {
FileUtils.deleteDirectory(tmpDir);
}
catch (IOException e) {
log.error("Failed to delete extracted export", e);
}
}
if (exportStream != null) {
try {
exportStream.close();
}
catch (Exception e) {
// nothing we can do.
}
}
}
}
@Transactional(rollbackOn = {IOException.class, ImporterException.class,
RuntimeException.class, ImportConflictException.class})
// WARNING: Keep this method public, otherwise @Transactional is ignored:
ConsumerDto importObjects(Owner owner, Map<String, File> importFiles,
ConflictOverrides overrides)
throws IOException, ImporterException {
File metadata = importFiles.get(ImportFile.META.fileName());
if (metadata == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required meta.json file"));
}
File rules = importFiles.get(ImportFile.RULES.fileName());
if (rules == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required rules directory"));
}
if (rules.listFiles().length == 0) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required rules file(s)"));
}
File consumerTypes = importFiles.get(ImportFile.CONSUMER_TYPE.fileName());
if (consumerTypes == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required consumer_types directory"));
}
File consumerFile = importFiles.get(ImportFile.CONSUMER.fileName());
if (consumerFile == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required consumer.json file"));
}
File products = importFiles.get(ImportFile.PRODUCTS.fileName());
File entitlements = importFiles.get(ImportFile.ENTITLEMENTS.fileName());
if (products != null && entitlements == null) {
throw new ImporterException(i18n.tr("The archive does not contain the " +
"required entitlements directory"));
}
// system level elements
/*
* Checking a system wide last import date breaks multi-tenant deployments whenever
* one org imports a manifest slightly older than another org who has already
* imported. Disabled for now. See bz #769644.
*/
// validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, metadata, force);
// If any calls find conflicts we'll assemble them into one exception detailing all
// the conflicts which occurred, so the caller can override them all at once
// if desired:
List<ImportConflictException> conflictExceptions =
new LinkedList<ImportConflictException>();
importRules(rules.listFiles(), metadata);
importConsumerTypes(consumerTypes.listFiles());
// per user elements
try {
validateMetadata(ExporterMetadata.TYPE_PER_USER, owner, metadata,
overrides);
}
catch (ImportConflictException e) {
conflictExceptions.add(e);
}
ConsumerDto consumer = null;
try {
consumer = importConsumer(owner, consumerFile, overrides);
}
catch (ImportConflictException e) {
conflictExceptions.add(e);
}
// At this point we're done checking for any potential conflicts:
if (!conflictExceptions.isEmpty()) {
log.error("Conflicts occurred during import that were not overridden:");
for (ImportConflictException e : conflictExceptions) {
log.error(e.message().getConflicts());
}
throw new ImportConflictException(conflictExceptions);
}
// If the consumer has no entitlements, this products directory will end up empty.
// This also implies there will be no entitlements to import.
if (importFiles.get(ImportFile.PRODUCTS.fileName()) != null) {
Refresher refresher = poolManager.getRefresher();
ProductImporter importer = new ProductImporter(productCurator, contentCurator, poolManager);
Set<Product> productsToImport = importProducts(
importFiles.get(ImportFile.PRODUCTS.fileName()).listFiles(),
importer);
Set<Product> modifiedProducts = importer.getChangedProducts(productsToImport);
for (Product product : modifiedProducts) {
refresher.add(product);
}
importer.store(productsToImport);
importEntitlements(owner, productsToImport, entitlements.listFiles());
refresher.add(owner);
refresher.run();
}
else {
log.warn("No products found to import, skipping product and entitlement import.");
}
return consumer;
}
public void importRules(File[] rulesFiles, File metadata) throws IOException {
// only import rules if versions are ok
Meta m = mapper.readValue(metadata, Meta.class);
if (VersionUtil.getRulesVersionCompatibility(m.getVersion())) {
// Only importing a single rules file now.
Reader reader = null;
try {
reader = new FileReader(rulesFiles[0]);
rulesImporter.importObject(reader, m.getVersion());
}
finally {
if (reader != null) {
reader.close();
}
}
}
else {
log.warn(
i18n.tr(
"Incompatible rules: import version {0} older than our version {1}.",
m.getVersion(), VersionUtil.getVersionString()));
log.warn(
i18n.tr("Manifest data will be imported without rules import."));
}
}
public void importConsumerTypes(File[] consumerTypes) throws IOException {
ConsumerTypeImporter importer = new ConsumerTypeImporter(consumerTypeCurator);
Set<ConsumerType> consumerTypeObjs = new HashSet<ConsumerType>();
for (File consumerType : consumerTypes) {
Reader reader = null;
try {
reader = new FileReader(consumerType);
consumerTypeObjs.add(importer.createObject(mapper, reader));
}
finally {
if (reader != null) {
reader.close();
}
}
}
importer.store(consumerTypeObjs);
}
public ConsumerDto importConsumer(Owner owner, File consumerFile,
ConflictOverrides forcedConflicts)
throws IOException, SyncDataFormatException {
ConsumerImporter importer = new ConsumerImporter(ownerCurator, i18n);
Reader reader = null;
ConsumerDto consumer = null;
try {
reader = new FileReader(consumerFile);
consumer = importer.createObject(mapper, reader);
importer.store(owner, consumer, forcedConflicts);
}
finally {
if (reader != null) {
reader.close();
}
}
return consumer;
}
public Set<Product> importProducts(File[] products, ProductImporter importer)
throws IOException {
Set<Product> productsToImport = new HashSet<Product>();
for (File product : products) {
// Skip product.pem's, we just need the json to import:
if (product.getName().endsWith(".json")) {
log.debug("Import product: " + product.getName());
Reader reader = null;
try {
reader = new FileReader(product);
productsToImport.add(importer.createObject(mapper, reader));
}
finally {
if (reader != null) {
reader.close();
}
}
}
}
// TODO: Do we need to cleanup unused products? Looked at this earlier and it
// looks somewhat complex and a little bit dangerous, so we're leaving them
// around for now.
return productsToImport;
}
public void importEntitlements(Owner owner, Set<Product> products, File[] entitlements)
throws IOException, SyncDataFormatException {
EntitlementImporter importer = new EntitlementImporter(subCurator, csCurator,
sink, i18n);
Map<String, Product> productsById = new HashMap<String, Product>();
for (Product product : products) {
productsById.put(product.getId(), product);
}
Set<Subscription> subscriptionsToImport = new HashSet<Subscription>();
for (File entitlement : entitlements) {
Reader reader = null;
try {
log.debug("Import entitlement: " + entitlement.getName());
reader = new FileReader(entitlement);
subscriptionsToImport.add(importer.importObject(mapper, reader, owner, productsById));
}
finally {
if (reader != null) {
reader.close();
}
}
}
importer.store(owner, subscriptionsToImport);
}
/**
* Create a tar.gz archive of the exported directory.
*
* @param exportDir Directory where Candlepin data was exported.
* @return File reference to the new archive tar.gz.
*/
private File extractArchive(File tempDir, File exportFile)
throws IOException, ImportExtractionException {
log.info("Extracting archive to: " + tempDir.getAbsolutePath());
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(exportFile));
ZipEntry zipentry = zipinputstream.getNextEntry();
if (zipentry == null) {
throw new ImportExtractionException(i18n.tr("The archive {0} is not " +
"a properly compressed file or is empty", exportFile.getName()));
}
while (zipentry != null) {
//for each entry to be extracted
String entryName = zipentry.getName();
if (log.isDebugEnabled()) {
log.debug("entryname " + entryName);
}
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory != null) {
new File(tempDir, directory).mkdirs();
}
fileoutputstream = new FileOutputStream(new File(tempDir, entryName));
int n;
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
return new File(tempDir.getAbsolutePath(), "export");
}
private byte[] loadSignature(File signatureFile) throws IOException {
FileInputStream signature = null;
// signature is never going to be a huge file, therefore cast is a-okay
byte[] signatureBytes = new byte[(int) signatureFile.length()];
try {
signature = new FileInputStream(signatureFile);
int offset = 0;
int numRead = 0;
while (offset < signatureBytes.length && numRead >= 0) {
numRead = signature.read(signatureBytes, offset,
signatureBytes.length - offset);
offset += numRead;
}
return signatureBytes;
}
finally {
if (signature != null) {
try {
signature.close();
}
catch (IOException e) {
// nothing we can do about this
}
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_3820_3
|
crossvul-java_data_bad_4727_3
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_3
|
crossvul-java_data_bad_5851_2
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Martin Eigenbrodt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
import jenkins.model.DependencyDeclarer;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import jenkins.model.Jenkins;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.tasks.BuildTrigger.DescriptorImpl.ItemListenerImpl;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Triggers builds of other projects.
*
* <p>
* Despite what the name suggests, this class doesn't actually trigger other jobs
* as a part of {@link #perform} method. Its main job is to simply augment
* {@link DependencyGraph}. Jobs are responsible for triggering downstream jobs
* on its own, because dependencies may come from other sources.
*
* <p>
* This class, however, does provide the {@link #execute(AbstractBuild, BuildListener, BuildTrigger)}
* method as a convenience method to invoke downstream builds.
*
* @author Kohsuke Kawaguchi
*/
public class BuildTrigger extends Recorder implements DependencyDeclarer {
/**
* Comma-separated list of other projects to be scheduled.
*/
private String childProjects;
/**
* Threshold status to trigger other builds.
*
* For compatibility reasons, this field could be null, in which case
* it should read as "SUCCESS".
*/
private final Result threshold;
public BuildTrigger(String childProjects, boolean evenIfUnstable) {
this(childProjects,evenIfUnstable ? Result.UNSTABLE : Result.SUCCESS);
}
@DataBoundConstructor
public BuildTrigger(String childProjects, String threshold) {
this(childProjects, Result.fromString(StringUtils.defaultString(threshold, Result.SUCCESS.toString())));
}
public BuildTrigger(String childProjects, Result threshold) {
if(childProjects==null)
throw new IllegalArgumentException();
this.childProjects = childProjects;
this.threshold = threshold;
}
public BuildTrigger(List<AbstractProject> childProjects, Result threshold) {
this((Collection<AbstractProject>)childProjects,threshold);
}
public BuildTrigger(Collection<? extends AbstractProject> childProjects, Result threshold) {
this(Items.toNameList(childProjects),threshold);
}
public String getChildProjectsValue() {
return childProjects;
}
public Result getThreshold() {
if(threshold==null)
return Result.SUCCESS;
else
return threshold;
}
/**
* @deprecated as of 1.406
* Use {@link #getChildProjects(ItemGroup)}
*/
public List<AbstractProject> getChildProjects() {
return getChildProjects(Jenkins.getInstance());
}
public List<AbstractProject> getChildProjects(AbstractProject owner) {
return getChildProjects(owner==null?null:owner.getParent());
}
public List<AbstractProject> getChildProjects(ItemGroup base) {
return Items.fromNameList(base,childProjects,AbstractProject.class);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/**
* Checks if this trigger has the exact same set of children as the given list.
*/
public boolean hasSame(AbstractProject owner, Collection<? extends AbstractProject> projects) {
List<AbstractProject> children = getChildProjects(owner);
return children.size()==projects.size() && children.containsAll(projects);
}
/**
* @deprecated as of 1.406
* Use {@link #hasSame(AbstractProject, Collection)}
*/
public boolean hasSame(Collection<? extends AbstractProject> projects) {
return hasSame(null,projects);
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
return true;
}
/**
* @deprecated since 1.341; use {@link #execute(AbstractBuild,BuildListener)}
*/
@Deprecated
public static boolean execute(AbstractBuild build, BuildListener listener, BuildTrigger trigger) {
return execute(build, listener);
}
/**
* Convenience method to trigger downstream builds.
*
* @param build
* The current build. Its downstreams will be triggered.
* @param listener
* Receives the progress report.
*/
public static boolean execute(AbstractBuild build, BuildListener listener) {
PrintStream logger = listener.getLogger();
// Check all downstream Project of the project, not just those defined by BuildTrigger
final DependencyGraph graph = Jenkins.getInstance().getDependencyGraph();
List<Dependency> downstreamProjects = new ArrayList<Dependency>(
graph.getDownstreamDependencies(build.getProject()));
// Sort topologically
Collections.sort(downstreamProjects, new Comparator<Dependency>() {
public int compare(Dependency lhs, Dependency rhs) {
// Swapping lhs/rhs to get reverse sort:
return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
}
});
for (Dependency dep : downstreamProjects) {
AbstractProject p = dep.getDownstreamProject();
if (p.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
continue;
}
List<Action> buildActions = new ArrayList<Action>();
if (dep.shouldTriggerBuild(build, listener, buildActions)) {
// this is not completely accurate, as a new build might be triggered
// between these calls
String name = ModelHyperlinkNote.encodeTo(p)+" #"+p.getNextBuildNumber();
if(p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build),
buildActions.toArray(new Action[buildActions.size()]))) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
}
}
return true;
}
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
for (AbstractProject p : getChildProjects(owner))
graph.addDependency(new Dependency(owner, p) {
@Override
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener,
List<Action> actions) {
return build.getResult().isBetterOrEqualTo(threshold);
}
});
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/**
* Called from {@link ItemListenerImpl} when a job is renamed.
*
* @return true if this {@link BuildTrigger} is changed and needs to be saved.
*/
public boolean onJobRenamed(String oldName, String newName) {
// quick test
if(!childProjects.contains(oldName))
return false;
boolean changed = false;
// we need to do this per string, since old Project object is already gone.
String[] projects = childProjects.split(",");
for( int i=0; i<projects.length; i++ ) {
if(projects[i].trim().equals(oldName)) {
projects[i] = newName;
changed = true;
}
}
if(changed) {
StringBuilder b = new StringBuilder();
for (String p : projects) {
if(b.length()>0) b.append(',');
b.append(p);
}
childProjects = b.toString();
}
return changed;
}
/**
* Correct broken data gracefully (#1537)
*/
private Object readResolve() {
if(childProjects==null)
return childProjects="";
return this;
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.BuildTrigger_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/downstream.html";
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String childProjectsString = formData.getString("childProjects").trim();
if (childProjectsString.endsWith(",")) {
childProjectsString = childProjectsString.substring(0, childProjectsString.length() - 1).trim();
}
return new BuildTrigger(
childProjectsString,
formData.optString("threshold", Result.SUCCESS.toString()));
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public boolean showEvenIfUnstableOption(@CheckForNull Class<? extends AbstractProject<?,?>> jobType) {
// UGLY: for promotion process, this option doesn't make sense.
return jobType == null || !jobType.getName().contains("PromotionProcess");
}
/**
* Form validation method.
*/
public FormValidation doCheck(@AncestorInPath Item project, @QueryParameter String value ) {
// Require CONFIGURE permission on this project
if(!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),",");
boolean hasProjects = false;
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.getInstance().getItem(projectName,project,Item.class);
if(item==null)
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName,
AbstractProject.findNearest(projectName,project.getParent()).getRelativeNameFrom(project)));
if(!(item instanceof AbstractProject))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteChildProjects(@QueryParameter String value, @AncestorInPath Item self, @AncestorInPath ItemGroup container) {
return AutoCompletionCandidates.ofJobNames(Job.class,value,self,container);
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onRenamed(Item item, String oldName, String newName) {
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for( Project<?,?> p : Jenkins.getInstance().getAllItems(Project.class) ) {
BuildTrigger t = p.getPublishersList().get(BuildTrigger.class);
if(t!=null) {
if(t.onJobRenamed(oldName,newName)) {
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from "+oldName+" to "+newName,e);
}
}
}
}
}
}
}
private static final Logger LOGGER = Logger.getLogger(BuildTrigger.class.getName());
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_5851_2
|
crossvul-java_data_good_4727_3
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import java.util.List;
/**
* @author Raymond Augé
*/
public class LiferayObjectConstructor implements TemplateMethodModelEx {
public Object exec(@SuppressWarnings("rawtypes") List arguments)
throws TemplateModelException {
if (arguments.isEmpty()) {
throw new TemplateModelException(
"This method must have at least one argument as the name of " +
"the class to instantiate");
}
Class<?> clazz = null;
try {
String className = String.valueOf(arguments.get(0));
clazz = Class.forName(
className, true, PACLClassLoaderUtil.getContextClassLoader());
}
catch (Exception e) {
throw new TemplateModelException(e.getMessage());
}
BeansWrapper beansWrapper = BeansWrapper.getDefaultInstance();
Object object = beansWrapper.newInstance(
clazz, arguments.subList(1, arguments.size()));
return beansWrapper.wrap(object);
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_3
|
crossvul-java_data_bad_2100_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.FilePath;
import hudson.Functions;
import jenkins.model.Jenkins;
import hudson.remoting.AsyncFutureImpl;
import hudson.remoting.Callable;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.VirtualChannel;
import hudson.security.AccessControlled;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* Various remoting operations related to diagnostics.
*
* <p>
* These code are useful wherever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc.
*
* @author Kohsuke Kawaguchi
* @since 1.175
*/
public final class RemotingDiagnostics {
public static Map<Object,Object> getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.<Object,Object>singletonMap("N/A","N/A");
return channel.call(new GetSystemProperties());
}
private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> {
public Map<Object,Object> call() {
return new TreeMap<Object,Object>(System.getProperties());
}
private static final long serialVersionUID = 1L;
}
public static Map<String,String> getThreadDump(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.singletonMap("N/A","N/A");
return channel.call(new GetThreadDump());
}
public static Future<Map<String,String>> getThreadDumpAsync(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return new AsyncFutureImpl<Map<String, String>>(Collections.singletonMap("N/A","offline"));
return channel.callAsync(new GetThreadDump());
}
private static final class GetThreadDump implements Callable<Map<String,String>,RuntimeException> {
public Map<String,String> call() {
Map<String,String> r = new LinkedHashMap<String,String>();
try {
ThreadInfo[] data = Functions.getThreadInfos();
Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data);
for (ThreadInfo ti : data)
r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti,map));
} catch (LinkageError _) {
// not in JDK6. fall back to JDK5
r.clear();
for (Map.Entry<Thread,StackTraceElement[]> t : Functions.dumpAllThreads().entrySet()) {
StringBuilder buf = new StringBuilder();
for (StackTraceElement e : t.getValue())
buf.append(e).append('\n');
r.put(t.getKey().getName(),buf.toString());
}
}
return r;
}
private static final long serialVersionUID = 1L;
}
/**
* Executes Groovy script remotely.
*/
public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException {
return channel.call(new Script(script));
}
private static final class Script implements DelegatingCallable<String,RuntimeException> {
private final String script;
private transient ClassLoader cl;
private Script(String script) {
this.script = script;
cl = getClassLoader();
}
public ClassLoader getClassLoader() {
return Jenkins.getInstance().getPluginManager().uberClassLoader;
}
public String call() throws RuntimeException {
// if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader.
if (cl==null) cl = Thread.currentThread().getContextClassLoader();
CompilerConfiguration cc = new CompilerConfiguration();
cc.addCompilationCustomizers(new ImportCustomizer().addStarImports(
"jenkins",
"jenkins.model",
"hudson",
"hudson.model"));
GroovyShell shell = new GroovyShell(cl,new Binding(),cc);
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
shell.setVariable("out", pw);
try {
Object output = shell.evaluate(script);
if(output!=null)
pw.println("Result: "+output);
} catch (Throwable t) {
t.printStackTrace(pw);
}
return out.toString();
}
}
/**
* Obtains the heap dump in an HPROF file.
*/
public static FilePath getHeapDump(VirtualChannel channel) throws IOException, InterruptedException {
return channel.call(new Callable<FilePath, IOException>() {
public FilePath call() throws IOException {
final File hprof = File.createTempFile("hudson-heapdump", "hprof");
hprof.delete();
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap",
new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()});
return new FilePath(hprof);
} catch (JMException e) {
throw new IOException2(e);
}
}
private static final long serialVersionUID = 1L;
});
}
/**
* Heap dump, exposable to URL via Stapler.
*
*/
public static class HeapDump {
private final AccessControlled owner;
private final VirtualChannel channel;
public HeapDump(AccessControlled owner, VirtualChannel channel) {
this.owner = owner;
this.channel = channel;
}
/**
* Obtains the heap dump.
*/
public void doIndex(StaplerResponse rsp) throws IOException {
rsp.sendRedirect("heapdump.hprof");
}
@WebMethod(name="heapdump.hprof")
public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {
owner.checkPermission(Jenkins.ADMINISTER);
rsp.setContentType("application/octet-stream");
FilePath dump = obtain();
try {
dump.copyTo(rsp.getCompressedOutputStream(req));
} finally {
dump.delete();
}
}
public FilePath obtain() throws IOException, InterruptedException {
return RemotingDiagnostics.getHeapDump(channel);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2100_0
|
crossvul-java_data_bad_5851_1
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.DescriptorExtensionList;
import hudson.PluginWrapper;
import hudson.RelativePath;
import hudson.XmlFile;
import hudson.BulkChange;
import hudson.Util;
import hudson.model.listeners.SaveableListener;
import hudson.util.FormApply;
import hudson.util.ReflectionUtils;
import hudson.util.ReflectionUtils.Parameter;
import hudson.views.ListViewColumn;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.jelly.JellyCompatibleFacet;
import org.kohsuke.stapler.lang.Klass;
import org.springframework.util.StringUtils;
import org.jvnet.tiger_types.Types;
import org.apache.commons.io.IOUtils;
import static hudson.Functions.*;
import static hudson.util.QuotedStringTokenizer.*;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Locale;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.beans.Introspector;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Metadata about a configurable instance.
*
* <p>
* {@link Descriptor} is an object that has metadata about a {@link Describable}
* object, and also serves as a factory (in a way this relationship is similar
* to {@link Object}/{@link Class} relationship.
*
* A {@link Descriptor}/{@link Describable}
* combination is used throughout in Hudson to implement a
* configuration/extensibility mechanism.
*
* <p>
* Take the list view support as an example, which is implemented
* in {@link ListView} class. Whenever a new view is created, a new
* {@link ListView} instance is created with the configuration
* information. This instance gets serialized to XML, and this instance
* will be called to render the view page. This is the job
* of {@link Describable} — each instance represents a specific
* configuration of a view (what projects are in it, regular expression, etc.)
*
* <p>
* For Hudson to create such configured {@link ListView} instance, Hudson
* needs another object that captures the metadata of {@link ListView},
* and that is what a {@link Descriptor} is for. {@link ListView} class
* has a singleton descriptor, and this descriptor helps render
* the configuration form, remember system-wide configuration, and works as a factory.
*
* <p>
* {@link Descriptor} also usually have its associated views.
*
*
* <h2>Persistence</h2>
* <p>
* {@link Descriptor} can persist data just by storing them in fields.
* However, it is the responsibility of the derived type to properly
* invoke {@link #save()} and {@link #load()}.
*
* <h2>Reflection Enhancement</h2>
* {@link Descriptor} defines addition to the standard Java reflection
* and provides reflective information about its corresponding {@link Describable}.
* These are primarily used by tag libraries to
* keep the Jelly scripts concise.
*
* @author Kohsuke Kawaguchi
* @see Describable
*/
public abstract class Descriptor<T extends Describable<T>> implements Saveable {
/**
* The class being described by this descriptor.
*/
public transient final Class<? extends T> clazz;
private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>();
/**
* Lazily computed list of properties on {@link #clazz} and on the descriptor itself.
*/
private transient volatile Map<String, PropertyType> propertyTypes,globalPropertyTypes;
/**
* Represents a readable property on {@link Describable}.
*/
public static final class PropertyType {
public final Class clazz;
public final Type type;
private volatile Class itemType;
public final String displayName;
PropertyType(Class clazz, Type type, String displayName) {
this.clazz = clazz;
this.type = type;
this.displayName = displayName;
}
PropertyType(Field f) {
this(f.getType(),f.getGenericType(),f.toString());
}
PropertyType(Method getter) {
this(getter.getReturnType(),getter.getGenericReturnType(),getter.toString());
}
public Enum[] getEnumConstants() {
return (Enum[])clazz.getEnumConstants();
}
/**
* If the property is a collection/array type, what is an item type?
*/
public Class getItemType() {
if(itemType==null)
itemType = computeItemType();
return itemType;
}
private Class computeItemType() {
if(clazz.isArray()) {
return clazz.getComponentType();
}
if(Collection.class.isAssignableFrom(clazz)) {
Type col = Types.getBaseClass(type, Collection.class);
if (col instanceof ParameterizedType)
return Types.erasure(Types.getTypeArgument(col,0));
else
return Object.class;
}
return null;
}
/**
* Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}.
*/
public Descriptor getItemTypeDescriptor() {
return Jenkins.getInstance().getDescriptor(getItemType());
}
public Descriptor getItemTypeDescriptorOrDie() {
Class it = getItemType();
if (it == null) {
throw new AssertionError(clazz + " is not an array/collection type in " + displayName + ". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor");
}
Descriptor d = Jenkins.getInstance().getDescriptor(it);
if (d==null)
throw new AssertionError(it +" is missing its descriptor in "+displayName+". See https://wiki.jenkins-ci.org/display/JENKINS/My+class+is+missing+descriptor");
return d;
}
/**
* Returns all the descriptors that produce types assignable to the property type.
*/
public List<? extends Descriptor> getApplicableDescriptors() {
return Jenkins.getInstance().getDescriptorList(clazz);
}
/**
* Returns all the descriptors that produce types assignable to the item type for a collection property.
*/
public List<? extends Descriptor> getApplicableItemDescriptors() {
return Jenkins.getInstance().getDescriptorList(getItemType());
}
}
/**
* Help file redirect, keyed by the field name to the path.
*
* @see #getHelpFile(String)
*/
private transient final Map<String,String> helpRedirect = new HashMap<String, String>();
/**
*
* @param clazz
* Pass in {@link #self()} to have the descriptor describe itself,
* (this hack is needed since derived types can't call "getClass()" to refer to itself.
*/
protected Descriptor(Class<? extends T> clazz) {
if (clazz==self())
clazz = (Class)getClass();
this.clazz = clazz;
// doing this turns out to be very error prone,
// as field initializers in derived types will override values.
// load();
}
/**
* Infers the type of the corresponding {@link Describable} from the outer class.
* This version works when you follow the common convention, where a descriptor
* is written as the static nested class of the describable class.
*
* @since 1.278
*/
protected Descriptor() {
this.clazz = (Class<T>)getClass().getEnclosingClass();
if(clazz==null)
throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly.");
// detect an type error
Type bt = Types.getBaseClass(getClass(), Descriptor.class);
if (bt instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) bt;
// this 't' is the closest approximation of T of Descriptor<T>.
Class t = Types.erasure(pt.getActualTypeArguments()[0]);
if(!t.isAssignableFrom(clazz))
throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?");
}
// detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up.
// this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html
try {
Method getd = clazz.getMethod("getDescriptor");
if(!getd.getReturnType().isAssignableFrom(getClass())) {
throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType());
}
} catch (NoSuchMethodException e) {
throw new AssertionError(getClass()+" is missing getDescriptor method.");
}
}
/**
* Human readable name of this kind of configurable object.
*/
public abstract String getDisplayName();
/**
* Uniquely identifies this {@link Descriptor} among all the other {@link Descriptor}s.
*
* <p>
* Historically {@link #clazz} is assumed to be unique, so this method uses that as the default,
* but if you are adding {@link Descriptor}s programmatically for the same type, you can change
* this to disambiguate them.
*
* <p>
* To look up {@link Descriptor} from ID, use {@link Jenkins#getDescriptor(String)}.
*
* @return
* Stick to valid Java identifier character, plus '.', which had to be allowed for historical reasons.
*
* @since 1.391
*/
public String getId() {
return clazz.getName();
}
/**
* Unlike {@link #clazz}, return the parameter type 'T', which determines
* the {@link DescriptorExtensionList} that this goes to.
*
* <p>
* In those situations where subtypes cannot provide the type parameter,
* this method can be overridden to provide it.
*/
public Class<T> getT() {
Type subTyping = Types.getBaseClass(getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
throw new IllegalStateException(getClass()+" doesn't extend Descriptor with a type parameter.");
}
return Types.erasure(Types.getTypeArgument(subTyping, 0));
}
/**
* Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}.
* Since {@link Jenkins} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request.
*/
public String getDescriptorUrl() {
return "descriptorByName/"+getId();
}
/**
* Gets the URL that this Descriptor is bound to, relative to the context path.
* @since 1.406
*/
public final String getDescriptorFullUrl() {
return getCurrentDescriptorByNameUrl()+'/'+getDescriptorUrl();
}
/**
* @since 1.402
*/
public static String getCurrentDescriptorByNameUrl() {
StaplerRequest req = Stapler.getCurrentRequest();
// this override allows RenderOnDemandClosure to preserve the proper value
Object url = req.getAttribute("currentDescriptorByNameUrl");
if (url!=null) return url.toString();
Ancestor a = req.findAncestor(DescriptorByNameOwner.class);
return a.getUrl();
}
/**
* If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method,
* return the form-field validation string. Otherwise null.
* <p>
* This method is used to hook up the form validation method to the corresponding HTML input element.
*/
public String getCheckUrl(String fieldName) {
String method = checkMethods.get(fieldName);
if(method==null) {
method = calcCheckUrl(fieldName);
checkMethods.put(fieldName,method);
}
if (method.equals(NONE)) // == would do, but it makes IDE flag a warning
return null;
// put this under the right contextual umbrella.
// a is always non-null because we already have Hudson as the sentinel
return '\'' + jsStringEscape(getCurrentDescriptorByNameUrl()) + "/'+" + method;
}
private String calcCheckUrl(String fieldName) {
String capitalizedFieldName = StringUtils.capitalize(fieldName);
Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName);
if(method==null)
return NONE;
return '\'' + getDescriptorUrl() + "/check" + capitalizedFieldName + '\'' + buildParameterList(method, new StringBuilder()).append(".toString()");
}
/**
* Builds query parameter line by figuring out what should be submitted
*/
private StringBuilder buildParameterList(Method method, StringBuilder query) {
for (Parameter p : ReflectionUtils.getParameters(method)) {
QueryParameter qp = p.annotation(QueryParameter.class);
if (qp!=null) {
String name = qp.value();
if (name.length()==0) name = p.name();
if (name==null || name.length()==0)
continue; // unknown parameter name. we'll report the error when the form is submitted.
RelativePath rp = p.annotation(RelativePath.class);
if (rp!=null)
name = rp.value()+'/'+name;
if (query.length()==0) query.append("+qs(this)");
if (name.equals("value")) {
// The special 'value' parameter binds to the the current field
query.append(".addThis()");
} else {
query.append(".nearBy('"+name+"')");
}
continue;
}
Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler");
if (m!=null) buildParameterList(m,query);
}
return query;
}
/**
* Computes the list of other form fields that the given field depends on, via the doFillXyzItems method,
* and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and
* sets that as the 'fillUrl' attribute.
*/
public void calcFillSettings(String field, Map<String,Object> attributes) {
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doFill" + capitalizedFieldName + "Items";
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName));
// build query parameter line by figuring out what should be submitted
List<String> depends = buildFillDependencies(method, new ArrayList<String>());
if (!depends.isEmpty())
attributes.put("fillDependsOn",Util.join(depends," "));
attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
}
private List<String> buildFillDependencies(Method method, List<String> depends) {
for (Parameter p : ReflectionUtils.getParameters(method)) {
QueryParameter qp = p.annotation(QueryParameter.class);
if (qp!=null) {
String name = qp.value();
if (name.length()==0) name = p.name();
if (name==null || name.length()==0)
continue; // unknown parameter name. we'll report the error when the form is submitted.
RelativePath rp = p.annotation(RelativePath.class);
if (rp!=null)
name = rp.value()+'/'+name;
depends.add(name);
continue;
}
Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler");
if (m!=null)
buildFillDependencies(m,depends);
}
return depends;
}
/**
* Computes the auto-completion setting
*/
public void calcAutoCompleteSettings(String field, Map<String,Object> attributes) {
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doAutoComplete" + capitalizedFieldName;
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
return; // no auto-completion
attributes.put("autoCompleteUrl", String.format("%s/%s/autoComplete%s", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
}
/**
* Used by Jelly to abstract away the handlign of global.jelly vs config.jelly databinding difference.
*/
public @CheckForNull PropertyType getPropertyType(@Nonnull Object instance, @Nonnull String field) {
// in global.jelly, instance==descriptor
return instance==this ? getGlobalPropertyType(field) : getPropertyType(field);
}
/**
* Akin to {@link #getPropertyType(Object,String) but never returns null.
* @throws AssertionError in case the field cannot be found
* @since 1.492
*/
public @Nonnull PropertyType getPropertyTypeOrDie(@Nonnull Object instance, @Nonnull String field) {
PropertyType propertyType = getPropertyType(instance, field);
if (propertyType != null) {
return propertyType;
} else if (instance == this) {
throw new AssertionError(getClass().getName() + " has no property " + field);
} else {
throw new AssertionError(clazz.getName() + " has no property " + field);
}
}
/**
* Obtains the property type of the given field of {@link #clazz}
*/
public PropertyType getPropertyType(String field) {
if(propertyTypes==null)
propertyTypes = buildPropertyTypes(clazz);
return propertyTypes.get(field);
}
/**
* Obtains the property type of the given field of this descriptor.
*/
public PropertyType getGlobalPropertyType(String field) {
if(globalPropertyTypes==null)
globalPropertyTypes = buildPropertyTypes(getClass());
return globalPropertyTypes.get(field);
}
/**
* Given the class, list up its {@link PropertyType}s from its public fields/getters.
*/
private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) {
Map<String, PropertyType> r = new HashMap<String, PropertyType>();
for (Field f : clazz.getFields())
r.put(f.getName(),new PropertyType(f));
for (Method m : clazz.getMethods())
if(m.getName().startsWith("get"))
r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m));
return r;
}
/**
* Gets the class name nicely escaped to be usable as a key in the structured form submission.
*/
public final String getJsonSafeClassName() {
return getId().replace('.','-');
}
/**
* @deprecated
* Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead.
* Deprecated as of 1.145.
*/
public T newInstance(StaplerRequest req) throws FormException {
throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)");
}
/**
* Creates a configured instance from the submitted form.
*
* <p>
* Hudson only invokes this method when the user wants an instance of <tt>T</tt>.
* So there's no need to check that in the implementation.
*
* <p>
* Starting 1.206, the default implementation of this method does the following:
* <pre>
* req.bindJSON(clazz,formData);
* </pre>
* <p>
* ... which performs the databinding on the constructor of {@link #clazz}.
*
* <p>
* For some types of {@link Describable}, such as {@link ListViewColumn}, this method
* can be invoked with null request object for historical reason. Such design is considered
* broken, but due to the compatibility reasons we cannot fix it. Because of this, the
* default implementation gracefully handles null request, but the contract of the method
* still is "request is always non-null." Extension points that need to define the "default instance"
* semantics should define a descriptor subtype and add the no-arg newInstance method.
*
* @param req
* Always non-null (see note above.) This object includes represents the entire submission.
* @param formData
* The JSON object that captures the configuration data for this {@link Descriptor}.
* See http://wiki.jenkins-ci.org/display/JENKINS/Structured+Form+Submission
* Always non-null.
*
* @throws FormException
* Signals a problem in the submitted form.
* @since 1.145
*/
public T newInstance(StaplerRequest req, JSONObject formData) throws FormException {
try {
Method m = getClass().getMethod("newInstance", StaplerRequest.class);
if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) {
// this class overrides newInstance(StaplerRequest).
// maintain the backward compatible behavior
return verifyNewInstance(newInstance(req));
} else {
if (req==null) {
// yes, req is supposed to be always non-null, but see the note above
return verifyNewInstance(clazz.newInstance());
}
// new behavior as of 1.206
return verifyNewInstance(req.bindJSON(clazz,formData));
}
} catch (NoSuchMethodException e) {
throw new AssertionError(e); // impossible
} catch (InstantiationException e) {
throw new Error("Failed to instantiate "+clazz+" from "+formData,e);
} catch (IllegalAccessException e) {
throw new Error("Failed to instantiate "+clazz+" from "+formData,e);
} catch (RuntimeException e) {
throw new RuntimeException("Failed to instantiate "+clazz+" from "+formData,e);
}
}
/**
* Look out for a typical error a plugin developer makes.
* See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html
*/
private T verifyNewInstance(T t) {
if (t!=null && t.getDescriptor()!=this) {
// TODO: should this be a fatal error?
LOGGER.warning("Father of "+ t+" and its getDescriptor() points to two different instances. Probably malplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html");
}
return t;
}
/**
* Returns the {@link Klass} object used for the purpose of loading resources from this descriptor.
*
* This hook enables other JVM languages to provide more integrated lookup.
*/
public Klass<?> getKlass() {
return Klass.java(clazz);
}
/**
* Returns the resource path to the help screen HTML, if any.
*
* <p>
* Starting 1.282, this method uses "convention over configuration" — you should
* just put the "help.html" (and its localized versions, if any) in the same directory
* you put your Jelly view files, and this method will automatically does the right thing.
*
* <p>
* This value is relative to the context root of Hudson, so normally
* the values are something like <tt>"/plugin/emma/help.html"</tt> to
* refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt>
* to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>.
*
* @return
* null to indicate that there's no help.
*/
public String getHelpFile() {
return getHelpFile(null);
}
/**
* Returns the path to the help screen HTML for the given field.
*
* <p>
* The help files are assumed to be at "help/FIELDNAME.html" with possible
* locale variations.
*/
public String getHelpFile(final String fieldName) {
return getHelpFile(getKlass(),fieldName);
}
public String getHelpFile(Klass<?> clazz, String fieldName) {
String v = helpRedirect.get(fieldName);
if (v!=null) return v;
for (Klass<?> c : clazz.getAncestors()) {
String page = "/descriptor/" + getId() + "/help";
String suffix;
if(fieldName==null) {
suffix="";
} else {
page += '/'+fieldName;
suffix='-'+fieldName;
}
try {
if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null)
return page;
} catch (IOException e) {
throw new Error(e);
}
if(getStaticHelpUrl(c, suffix) !=null) return page;
}
return null;
}
/**
* Tells Jenkins that the help file for the field 'fieldName' is defined in the help file for
* the 'fieldNameToRedirectTo' in the 'owner' class.
* @since 1.425
*/
protected void addHelpFileRedirect(String fieldName, Class<? extends Describable> owner, String fieldNameToRedirectTo) {
helpRedirect.put(fieldName,
Jenkins.getInstance().getDescriptor(owner).getHelpFile(fieldNameToRedirectTo));
}
/**
* Checks if the given object is created from this {@link Descriptor}.
*/
public final boolean isInstance( T instance ) {
return clazz.isInstance(instance);
}
/**
* Checks if the type represented by this descriptor is a subtype of the given type.
*/
public final boolean isSubTypeOf(Class type) {
return type.isAssignableFrom(clazz);
}
/**
* @deprecated
* As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}.
*/
public boolean configure( StaplerRequest req ) throws FormException {
return true;
}
/**
* Invoked when the global configuration page is submitted.
*
* Can be overriden to store descriptor-specific information.
*
* @param json
* The JSON object that captures the configuration data for this {@link Descriptor}.
* See http://wiki.jenkins-ci.org/display/JENKINS/Structured+Form+Submission
* @return false
* to keep the client in the same config page.
*/
public boolean configure( StaplerRequest req, JSONObject json ) throws FormException {
// compatibility
return configure(req);
}
public String getConfigPage() {
return getViewPage(clazz, getPossibleViewNames("config"), "config.jelly");
}
public String getGlobalConfigPage() {
return getViewPage(clazz, getPossibleViewNames("global"), null);
}
private String getViewPage(Class<?> clazz, String pageName, String defaultValue) {
return getViewPage(clazz,Collections.singleton(pageName),defaultValue);
}
private String getViewPage(Class<?> clazz, Collection<String> pageNames, String defaultValue) {
while(clazz!=Object.class && clazz!=null) {
for (String pageName : pageNames) {
String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName;
if(clazz.getClassLoader().getResource(name)!=null)
return '/'+name;
}
clazz = clazz.getSuperclass();
}
return defaultValue;
}
protected final String getViewPage(Class<?> clazz, String pageName) {
// We didn't find the configuration page.
// Either this is non-fatal, in which case it doesn't matter what string we return so long as
// it doesn't exist.
// Or this error is fatal, in which case we want the developer to see what page he's missing.
// so we put the page name.
return getViewPage(clazz,pageName,pageName);
}
protected List<String> getPossibleViewNames(String baseName) {
List<String> names = new ArrayList<String>();
for (Facet f : WebApp.get(Jenkins.getInstance().servletContext).facets) {
if (f instanceof JellyCompatibleFacet) {
JellyCompatibleFacet jcf = (JellyCompatibleFacet) f;
for (String ext : jcf.getScriptExtensions())
names.add(baseName +ext);
}
}
return names;
}
/**
* Saves the configuration info to the disk.
*/
public synchronized void save() {
if(BulkChange.contains(this)) return;
try {
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
}
}
/**
* Loads the data from the disk into this object.
*
* <p>
* The constructor of the derived class must call this method.
* (If we do that in the base class, the derived class won't
* get a chance to set default values.)
*/
public synchronized void load() {
XmlFile file = getConfigFile();
if(!file.exists())
return;
try {
file.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+file, e);
}
}
protected final XmlFile getConfigFile() {
return new XmlFile(new File(Jenkins.getInstance().getRootDir(),getId()+".xml"));
}
/**
* Returns the plugin in which this descriptor is defined.
*
* @return
* null to indicate that this descriptor came from the core.
*/
protected PluginWrapper getPlugin() {
return Jenkins.getInstance().getPluginManager().whichPlugin(clazz);
}
/**
* Serves <tt>help.html</tt> from the resource of {@link #clazz}.
*/
public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
if(path.contains("..")) throw new ServletException("Illegal path: "+path);
path = path.replace('/','-');
PluginWrapper pw = getPlugin();
if (pw!=null) {
rsp.setHeader("X-Plugin-Short-Name",pw.getShortName());
rsp.setHeader("X-Plugin-Long-Name",pw.getLongName());
rsp.setHeader("X-Plugin-From", Messages.Descriptor_From(
pw.getLongName().replace("Hudson","Jenkins").replace("hudson","jenkins"), pw.getUrl()));
}
for (Klass<?> c= getKlass(); c!=null; c=c.getSuperClass()) {
RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path);
if(rd!=null) {// template based help page
rd.forward(req,rsp);
return;
}
URL url = getStaticHelpUrl(c, path);
if(url!=null) {
// TODO: generalize macro expansion and perhaps even support JEXL
rsp.setContentType("text/html;charset=UTF-8");
InputStream in = url.openStream();
try {
String literal = IOUtils.toString(in,"UTF-8");
rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath())));
} finally {
IOUtils.closeQuietly(in);
}
return;
}
}
rsp.sendError(SC_NOT_FOUND);
}
private URL getStaticHelpUrl(Klass<?> c, String suffix) {
Locale locale = Stapler.getCurrentRequest().getLocale();
String base = "help"+suffix;
URL url;
url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html");
if(url!=null) return url;
url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html");
if(url!=null) return url;
url = c.getResource(base + '_' + locale.getLanguage() + ".html");
if(url!=null) return url;
// default
return c.getResource(base + ".html");
}
//
// static methods
//
// to work around warning when creating a generic array type
public static <T> T[] toArray( T... values ) {
return values;
}
public static <T> List<T> toList( T... values ) {
return new ArrayList<T>(Arrays.asList(values));
}
public static <T extends Describable<T>>
Map<Descriptor<T>,T> toMap(Iterable<T> describables) {
Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>();
for (T d : describables) {
m.put(d.getDescriptor(),d);
}
return m;
}
/**
* Used to build {@link Describable} instance list from <f:hetero-list> tag.
*
* @param req
* Request that represents the form submission.
* @param formData
* Structured form data that represents the contains data for the list of describables.
* @param key
* The JSON property name for 'formData' that represents the data for the list of describables.
* @param descriptors
* List of descriptors to create instances from.
* @return
* Can be empty but never null.
*/
public static <T extends Describable<T>>
List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
return newInstancesFromHeteroList(req,formData.get(key),descriptors);
}
public static <T extends Describable<T>>
List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
List<T> items = new ArrayList<T>();
if (formData!=null) {
for (Object o : JSONArray.fromObject(formData)) {
JSONObject jo = (JSONObject)o;
String kind = jo.getString("kind");
items.add(find(descriptors,kind).newInstance(req,jo));
}
}
return items;
}
/**
* Finds a descriptor from a collection by its class name.
*/
public static <T extends Descriptor> T find(Collection<? extends T> list, String className) {
for (T d : list) {
if(d.getClass().getName().equals(className))
return d;
}
// Since we introduced Descriptor.getId(), it is a preferred method of identifying descriptor by a string.
// To make that migration easier without breaking compatibility, let's also match up with the id.
for (T d : list) {
if(d.getId().equals(className))
return d;
}
return null;
}
public static Descriptor find(String className) {
return find(Jenkins.getInstance().getExtensionList(Descriptor.class),className);
}
public static final class FormException extends Exception implements HttpResponse {
private final String formField;
public FormException(String message, String formField) {
super(message);
this.formField = formField;
}
public FormException(String message, Throwable cause, String formField) {
super(message, cause);
this.formField = formField;
}
public FormException(Throwable cause, String formField) {
super(cause);
this.formField = formField;
}
/**
* Which form field contained an error?
*/
public String getFormField() {
return formField;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
if (FormApply.isApply(req)) {
FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.defaultOptions.ERROR)")
.generateResponse(req, rsp, node);
} else {
// for now, we can't really use the field name that caused the problem.
new Failure(getMessage()).generateResponse(req,rsp,node);
}
}
}
private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName());
/**
* Used in {@link #checkMethods} to indicate that there's no check method.
*/
private static final String NONE = "\u0000";
/**
* Special type indicating that {@link Descriptor} describes itself.
* @see Descriptor#Descriptor(Class)
*/
public static final class Self {}
protected static Class self() { return Self.class; }
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_5851_1
|
crossvul-java_data_bad_5851_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
* Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
* id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques
* Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.EnvVars;
import hudson.Functions;
import antlr.ANTLRException;
import hudson.AbortException;
import hudson.CopyOnWrite;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.SubTask;
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTaskContributor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.Permission;
import hudson.slaves.WorkspaceList;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import jenkins.util.TimeDuration;
import net.sf.json.JSONObject;
import org.apache.tools.ant.taskdefs.email.Mailer;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
*/
private volatile SCM scm = new NullSCM();
/**
* Controls how the checkout is done.
*/
private volatile SCMCheckoutStrategy scmCheckoutStrategy;
/**
* State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
*/
private volatile transient SCMRevisionState pollingBaseline = null;
/**
* All the builds keyed by their build number.
*
* External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
* {@link Run#getPreviousBuild()}
*/
@Restricted(NoExternalUse.class)
@SuppressWarnings("deprecation") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
protected transient RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
*/
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
*/
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when downstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenDownstreamBuilding = false;
/**
* True to keep builds of this project in queue when upstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenUpstreamBuilding = false;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
* are saved independently.
*
* @see Jenkins#getJDK(String)
*/
private volatile String jdk;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
private boolean concurrentBuild;
/**
* See {@link #setCustomWorkspace(String)}.
*
* @since 1.410
*/
private String customWorkspace;
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
if(!Jenkins.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public synchronized void save() throws IOException {
super.save();
updateTransientActions();
}
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
builds = createBuildRunMap();
// solicit initial contributions, especially from TransientProjectActionFactory
updateTransientActions();
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
RunMap<R> builds = createBuildRunMap();
if (this.builds!=null) {
// if we are reloading, keep all those that are still building intact
for (R r : this.builds.getLoadedBuilds().values()) {
if (r.isBuilding())
builds.put(r);
}
}
this.builds = builds;
for (Trigger t : triggers())
t.start(this, Items.updatingByXml.get());
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
}
private RunMap<R> createBuildRunMap() {
return new RunMap<R>(getBuildDir(), new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
}
private synchronized List<Trigger<?>> triggers() {
if (triggers == null) {
triggers = new Vector<Trigger<?>>();
}
return triggers;
}
@Override
public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(node, listener);
JDK jdk = getJDK();
if (jdk != null) {
if (node != null) { // just in case were not in a build
jdk = jdk.forNode(node, listener);
}
jdk.buildEnvVars(env);
}
return env;
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
@Exported
public boolean isConcurrentBuild() {
return concurrentBuild;
}
public void setConcurrentBuild(boolean b) throws IOException {
concurrentBuild = b;
save();
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Jenkins.getInstance().getSelfLabel();
return Jenkins.getInstance().getLabel(assignedNode);
}
/**
* Set of labels relevant to this job.
*
* This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.
* It does not affect the scheduling. This information is informational and the best-effort basis.
*
* @since 1.456
* @return
* Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element
* to correspond to the null return value from {@link #getAssignedLabel()}.
*/
public Set<Label> getRelevantLabels() {
return Collections.singleton(getAssignedLabel());
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (canRoam || assignedNode==null) return null;
try {
LabelExpression.parseExpression(assignedNode);
return assignedNode;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(assignedNode);
}
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getExpression();
}
save();
}
/**
* Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
*/
public void setAssignedNode(Node l) throws IOException {
setAssignedLabel(l.getSelfLabel());
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
}
/**
* Gets the human readable display name to be rendered in the "Build Now" link.
*
* @since 1.401
*/
public String getBuildNowText() {
return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
}
/**
* Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
*
* <p>
* Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs
* that acts as a single unit. This method can be used to find the top most dominating job that
* covers such a tree.
*
* @return never null.
* @see AbstractBuild#getRootBuild()
*/
public AbstractProject<?,?> getRootProject() {
if (this instanceof TopLevelItem) {
return this;
} else {
ItemGroup p = this.getParent();
if (p instanceof AbstractProject)
return ((AbstractProject) p).getRootProject();
return this;
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
}
/**
* Various deprecated methods in this class all need the 'current' build. This method returns
* the build suitable for that purpose.
*
* @return An AbstractBuild for deprecated methods to use.
*/
private AbstractBuild getBuildForDeprecatedMethods() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b;
}
}
R lb = getLastBuild();
if(lb!=null) return lb;
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
if (b!=null) return b.getWorkspace();
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
FilePath f = browser.getWorkspace(this);
if (f != null) return f;
}
return null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
}
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
}
public SCMCheckoutStrategy getScmCheckoutStrategy() {
return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
}
public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
this.scmCheckoutStrategy = scmCheckoutStrategy;
save();
}
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
}
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return quietPeriod!=null;
}
/**
* Sets the custom quiet period of this project, or revert to the global default if null is given.
*/
public void setQuietPeriod(Integer seconds) throws IOException {
this.quietPeriod = seconds;
save();
}
public boolean hasCustomScmCheckoutRetryCount(){
return scmCheckoutRetryCount != null;
}
@Override
public boolean isBuildable() {
return !isDisabled() && !isHoldOffBuildUntilSave();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenDownstreamBuilding() {
return blockBuildWhenDownstreamBuilding;
}
public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
blockBuildWhenDownstreamBuilding = b;
save();
}
public boolean blockBuildWhenUpstreamBuilding() {
return blockBuildWhenUpstreamBuilding;
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
blockBuildWhenUpstreamBuilding = b;
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Jenkins.getInstance().getQueue().cancel(this);
save();
}
/**
* Specifies whether this project may be disabled by the user.
* By default, it can be only if this is a {@link TopLevelItem};
* would be false for matrix configurations, etc.
* @return true if the GUI should allow {@link #doDisable} and the like
* @since 1.475
*/
public boolean supportsMakeDisabled() {
return this instanceof TopLevelItem;
}
public void disable() throws IOException {
makeDisabled(true);
}
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
/**
* effectively deprecated. Since using updateTransientActions correctly
* under concurrent environment requires a lock that can too easily cause deadlocks.
*
* <p>
* Override {@link #createTransientActions()} instead.
*/
protected void updateTransientActions() {
transientActions = createTransientActions();
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
for (JobProperty<? super P> p : Util.fixNull(properties))
ta.addAll(p.getJobActions((P)this));
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
return ta;
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
updateTransientActions();
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Jenkins.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects(p));
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(p,newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
}
}
// notify the queue as the project might be now tied to different node
Jenkins.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Jenkins.getInstance().rebuildDependencyGraph();
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this array can contain null, and those will be silently ignored.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this collection can contain null, and those will be silently ignored.
* @since 1.383
*/
@SuppressWarnings("unchecked")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
if (!isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (QueueTaskFuture)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
@SuppressWarnings("deprecation")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Jenkins.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Jenkins.getInstance().getQueue().getItem(this);
}
/**
* Gets the JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Jenkins.getInstance().getJDK(jdk);
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
this.jdk = jdk.getName();
save();
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
@Override
public RunMap<R> _getRuns() {
return builds;
}
@Override
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuild(String id) {
return builds.getById(id);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuildByNumber(int n) {
return builds.getByNumber(n);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getFirstBuild() {
return builds.oldestBuild();
}
@Override
public R getLastBuild() {
return builds.newestBuild();
}
@Override
public R getNearestBuild(int n) {
return builds.search(n, Direction.ASC);
}
@Override
public R getNearestOldBuild(int n) {
return builds.search(n, Direction.DESC);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public synchronized List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
public Object getSameNodeConstraint() {
return this; // in this way, any member that wants to run with the main guy can nominate the project itself
}
public final Task getOwnerTask() {
return this;
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the downstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
// Block builds until they are done with post-production
if (isLogUpdated() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenDownstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingDownstream();
if (bup!=null)
return new BecauseOfDownstreamBuildInProgress(bup);
}
if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the downstream project is either
* building, waiting, pending or buildable.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingDownstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveDownstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
/**
* Returns the project if any of the upstream project is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingUpstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveUpstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
for (JobProperty<? super P> p : properties)
r.addAll(p.getSubTasks());
return r;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
if (r) {
// Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations
// won't reach this line anyway, as they throw AbortExceptions on checkout failure.
calcPollingBaseline(build, launcher, listener);
}
return r;
}
/**
* Pushes the baseline up to the newly checked out revision.
*/
private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
if (baseline==null) {
try {
baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
} catch (AbstractMethodError e) {
baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
}
if (baseline!=null)
build.addAction(baseline);
}
pollingBaseline = baseline;
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The implementation is responsible for ensuring mutual exclusion between polling and builds
* if necessary.
*
* @since 1.345
*/
public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (!isBuildable()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
SCMPollListener.fireBeforePolling(this, listener);
PollingResult r = _poll(listener, scm, lb);
SCMPollListener.firePollingSuccess(this,listener, r);
return r;
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (RuntimeException e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
} catch (Error e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
}
}
/**
* {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
*/
private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
if ( workspaceOfflineReason != null ) {
// workspace offline
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
ws = browser.getWorkspace(this);
if (ws != null) {
return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
}
}
// build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().print(Messages.AbstractProject_NoWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return BUILD_NOW;
}
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
return pollWithWorkspace(listener, scm, lb, ws, l);
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
}
private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
enum WorkspaceOfflineReason {
nonexisting_workspace,
builton_node_gone,
builton_node_no_executors
}
private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {
FilePath ws = build.getWorkspace();
if (ws==null || !ws.exists()) {
return WorkspaceOfflineReason.nonexisting_workspace;
}
Node builtOn = build.getBuiltOn();
if (builtOn == null) { // node built-on doesn't exist anymore
return WorkspaceOfflineReason.builton_node_gone;
}
if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
return WorkspaceOfflineReason.builton_node_no_executors;
}
return null;
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
@Exported
public SCM getScm() {
return scm;
}
public void setScm(SCM scm) throws IOException {
this.scm = scm;
save();
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
public void addTrigger(Trigger<?> trigger) throws IOException {
addToList(trigger,triggers());
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
removeFromList(trigger,triggers());
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i,item);
save();
return;
}
}
// add
collection.add(item);
save();
updateTransientActions();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
updateTransientActions();
return;
}
}
}
@SuppressWarnings("unchecked")
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(triggers());
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : triggers()) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects(ap).contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {
if (delay==null) delay=new TimeDuration(getQuietPeriod());
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
if (pp != null) {
pp._doBuild(req,rsp,delay);
return;
}
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));
rsp.sendRedirect(".");
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
/*package*/ CauseAction getBuildCause(StaplerRequest req) {
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserIdCause();
}
return new CauseAction(cause);
}
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*
* @deprecated as of 1.488
* Inject {@link TimeDuration}.
*/
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
return Integer.parseInt(delay);
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp,delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.sendRedirect(".");
}
/**
* Cancels a scheduled build.
*/
@RequirePOST
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ABORT);
Jenkins.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
/**
* Deletes this project.
*/
@Override
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
delete();
if (req == null || rsp == null)
return;
View view = req.findAncestorObject(View.class);
if (view == null)
rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());
else
rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
makeDisabled(req.getParameter("disable")!=null);
jdk = req.getParameter("jdk");
if(req.getParameter("hasCustomQuietPeriod")!=null) {
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
} else {
quietPeriod = null;
}
if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
} else {
scmCheckoutRetryCount = null;
}
blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;
if(req.hasParameter("customWorkspace")) {
customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
} else {
customWorkspace = null;
}
if (json.has("scmCheckoutStrategy"))
scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,
json.getJSONObject("scmCheckoutStrategy"));
else
scmCheckoutStrategy = null;
if(req.getParameter("hasSlaveAffinity")!=null) {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
} else {
assignedNode = null;
}
canRoam = assignedNode==null;
concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
for (Trigger t : triggers())
t.stop();
triggers = buildDescribable(req, Trigger.for_(this));
for (Trigger t : triggers)
t.start(this,true);
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
T instance = d.newInstance(req, data.getJSONObject(safeName));
r.add(instance);
}
}
return r;
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
// Would be good if when asked for *plain*, do something else!
// (E.g. return 404, or send empty doc.)
// Not critical; client can just check if content type is not text/plain,
// which also serves to detect old versions of Hudson.
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b!=null ? b.getWorkspace() : null;
if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
for (WorkspaceListener wl : WorkspaceListener.all()) {
wl.afterDelete(this);
}
return new HttpRedirect(".");
} else {
// If we get here, that means the SCM blocked the workspace deletion.
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
@CLIMethod(name="disable-job")
@RequirePOST
public HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
@RequirePOST
public HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return JenkinsLocationConfiguration.get().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
if (Util.fixEmpty(value)==null)
return FormValidation.ok(); // nothing typed yet
try {
Label.parseExpression(value);
} catch (ANTLRException e) {
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
Label l = Jenkins.getInstance().getLabel(value);
if (l.isEmpty()) {
for (LabelAtom a : l.listAtoms()) {
if (a.isEmpty()) {
LabelAtom nearest = LabelAtom.findNearest(a.getName());
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));
}
}
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
}
return FormValidation.ok();
}
public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
if(Util.fixEmptyAndTrim(customWorkspace)==null)
return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
else
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
AutoCompletionCandidates candidates = new AutoCompletionCandidates();
List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
for (Job job: jobs) {
if (job.getFullName().startsWith(value)) {
if (job.hasPermission(Item.READ)) {
candidates.add(job.getFullName());
}
}
}
return candidates;
}
public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
AutoCompletionCandidates c = new AutoCompletionCandidates();
Set<Label> labels = Jenkins.getInstance().getLabels();
List<String> queries = new AutoCompleteSeeder(value).getSeeds();
for (String term : queries) {
for (Label l : labels) {
if (l.getName().startsWith(term)) {
c.add(l.getName());
}
}
}
return c;
}
public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
return SCMCheckoutStrategyDescriptor._for(p);
}
/**
* Utility class for taking the current input value and computing a list
* of potential terms to match against the list of defined labels.
*/
static class AutoCompleteSeeder {
private String source;
AutoCompleteSeeder(String source) {
this.source = source;
}
List<String> getSeeds() {
ArrayList<String> terms = new ArrayList<String>();
boolean trailingQuote = source.endsWith("\"");
boolean leadingQuote = source.startsWith("\"");
boolean trailingSpace = source.endsWith(" ");
if (trailingQuote || (trailingSpace && !leadingQuote)) {
terms.add("");
} else {
if (leadingQuote) {
int quote = source.lastIndexOf('"');
if (quote == 0) {
terms.add(source.substring(1));
} else {
terms.add("");
}
} else {
int space = source.lastIndexOf(' ');
if (space > -1) {
terms.add(source.substring(space+1));
} else {
terms.add(source);
}
}
}
return terms;
}
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
return findNearest(name,Hudson.getInstance());
}
/**
* Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
*
* @since 1.419
*/
public static AbstractProject findNearest(String name, ItemGroup context) {
List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getRelativeNameFrom(context);
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build
*/
public static final Permission ABORT = CANCEL;
/**
* Replaceable "Build Now" text.
*/
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();
/**
* Used for CLI binding.
*/
@CLIResolver
public static AbstractProject resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
if (item==null)
throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
return item;
}
public String getCustomWorkspace() {
return customWorkspace;
}
/**
* User-specified workspace directory, or null if it's up to Jenkins.
*
* <p>
* Normally a project uses the workspace location assigned by its parent container,
* but sometimes people have builds that have hard-coded paths.
*
* <p>
* This is not {@link File} because it may have to hold a path representation on another OS.
*
* <p>
* If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace
* is prepared.
*
* @since 1.410
*/
public void setCustomWorkspace(String customWorkspace) throws IOException {
this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
save();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_5851_0
|
crossvul-java_data_good_4727_5
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.kernel.template.TemplateException;
import com.liferay.portal.security.lang.PortalSecurityManagerThreadLocal;
import com.liferay.portal.security.pacl.PACLPolicy;
import com.liferay.portal.template.TemplateContextHelper;
import freemarker.template.Configuration;
import java.io.Writer;
import java.util.Map;
/**
* @author Raymond Augé
*/
public class PACLFreeMarkerTemplate extends FreeMarkerTemplate {
public PACLFreeMarkerTemplate(
String templateId, String templateContent, String errorTemplateId,
String errorTemplateContent, Map<String, Object> context,
Configuration configuration,
TemplateContextHelper templateContextHelper,
StringTemplateLoader stringTemplateLoader, PACLPolicy paclPolicy) {
super(
templateId, templateContent, errorTemplateId, errorTemplateContent,
context, configuration, templateContextHelper,
stringTemplateLoader);
_paclPolicy = paclPolicy;
}
@Override
public boolean processTemplate(Writer writer) throws TemplateException {
PACLPolicy initialPolicy =
PortalSecurityManagerThreadLocal.getPACLPolicy();
try {
PortalSecurityManagerThreadLocal.setPACLPolicy(_paclPolicy);
return super.processTemplate(writer);
}
finally {
PortalSecurityManagerThreadLocal.setPACLPolicy(initialPolicy);
}
}
private PACLPolicy _paclPolicy;
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_5
|
crossvul-java_data_bad_4727_1
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.kernel.cache.PortalCache;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.template.Template;
import com.liferay.portal.kernel.template.TemplateContextType;
import com.liferay.portal.kernel.template.TemplateException;
import com.liferay.portal.kernel.template.TemplateManager;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.template.RestrictedTemplate;
import com.liferay.portal.template.TemplateContextHelper;
import com.liferay.portal.util.PropsValues;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import java.io.IOException;
import java.util.Map;
/**
* @author Mika Koivisto
* @author Tina Tina
*/
public class FreeMarkerManager implements TemplateManager {
public void clearCache() {
_stringTemplateLoader.removeTemplates();
PortalCache portalCache = LiferayCacheStorage.getPortalCache();
portalCache.removeAll();
}
public void clearCache(String templateId) {
_stringTemplateLoader.removeTemplate(templateId);
PortalCache portalCache = LiferayCacheStorage.getPortalCache();
portalCache.remove(templateId);
}
public void destroy() {
if (_configuration == null) {
return;
}
_configuration.clearEncodingMap();
_configuration.clearSharedVariables();
_configuration.clearTemplateCache();
_configuration = null;
_restrictedHelperUtilities.clear();
_restrictedHelperUtilities = null;
_standardHelperUtilities.clear();
_standardHelperUtilities = null;
_stringTemplateLoader.removeTemplates();
_stringTemplateLoader = null;
_templateContextHelper = null;
}
public Template getTemplate(
String templateId, String templateContent, String errorTemplateId,
String errorTemplateContent, TemplateContextType templateContextType) {
if (templateContextType.equals(TemplateContextType.EMPTY)) {
return new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, null, _configuration,
_templateContextHelper, _stringTemplateLoader);
}
else if (templateContextType.equals(TemplateContextType.RESTRICTED)) {
return new RestrictedTemplate(
new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, _restrictedHelperUtilities,
_configuration, _templateContextHelper,
_stringTemplateLoader),
_templateContextHelper.getRestrictedVariables());
}
else if (templateContextType.equals(TemplateContextType.STANDARD)) {
return new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, _standardHelperUtilities, _configuration,
_templateContextHelper, _stringTemplateLoader);
}
return null;
}
public Template getTemplate(
String templateId, String templateContent, String errorTemplateId,
TemplateContextType templateContextType) {
return getTemplate(
templateId, templateContent, errorTemplateId, null,
templateContextType);
}
public Template getTemplate(
String templateId, String templateContent,
TemplateContextType templateContextType) {
return getTemplate(
templateId, templateContent, null, null, templateContextType);
}
public Template getTemplate(
String templateId, TemplateContextType templateContextType) {
return getTemplate(templateId, null, null, null, templateContextType);
}
public String getTemplateManagerName() {
return TemplateManager.FREEMARKER;
}
public boolean hasTemplate(String templateId) {
try {
freemarker.template.Template template = _configuration.getTemplate(
templateId);
if (template != null) {
return true;
}
else {
return false;
}
}
catch (IOException ioe) {
if (_log.isWarnEnabled()) {
_log.warn(ioe, ioe);
}
return false;
}
}
public void init() throws TemplateException {
if (_configuration != null) {
return;
}
LiferayTemplateLoader liferayTemplateLoader =
new LiferayTemplateLoader();
liferayTemplateLoader.setTemplateLoaders(
PropsValues.FREEMARKER_ENGINE_TEMPLATE_LOADERS);
_stringTemplateLoader = new StringTemplateLoader();
MultiTemplateLoader multiTemplateLoader =
new MultiTemplateLoader(
new TemplateLoader[] {
new ClassTemplateLoader(getClass(), StringPool.SLASH),
_stringTemplateLoader, liferayTemplateLoader
});
_configuration = new Configuration();
_configuration.setDefaultEncoding(StringPool.UTF8);
_configuration.setLocalizedLookup(
PropsValues.FREEMARKER_ENGINE_LOCALIZED_LOOKUP);
_configuration.setObjectWrapper(new LiferayObjectWrapper());
_configuration.setTemplateLoader(multiTemplateLoader);
_configuration.setTemplateUpdateDelay(
PropsValues.FREEMARKER_ENGINE_MODIFICATION_CHECK_INTERVAL);
try {
_configuration.setSetting(
"auto_import", PropsValues.FREEMARKER_ENGINE_MACRO_LIBRARY);
_configuration.setSetting(
"cache_storage", PropsValues.FREEMARKER_ENGINE_CACHE_STORAGE);
_configuration.setSetting(
"template_exception_handler",
PropsValues.FREEMARKER_ENGINE_TEMPLATE_EXCEPTION_HANDLER);
}
catch (Exception e) {
throw new TemplateException("Unable to init freemarker manager", e);
}
_standardHelperUtilities = _templateContextHelper.getHelperUtilities();
_restrictedHelperUtilities =
_templateContextHelper.getRestrictedHelperUtilities();
}
public void setTemplateContextHelper(
TemplateContextHelper templateContextHelper) {
_templateContextHelper = templateContextHelper;
}
private static Log _log = LogFactoryUtil.getLog(FreeMarkerManager.class);
private Configuration _configuration;
private Map<String, Object> _restrictedHelperUtilities;
private Map<String, Object> _standardHelperUtilities;
private StringTemplateLoader _stringTemplateLoader;
private TemplateContextHelper _templateContextHelper;
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_1
|
crossvul-java_data_good_2293_2
|
package org.uberfire.io.regex;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uberfire.io.CommonIOServiceDotFileTest;
import org.uberfire.io.IOService;
import org.uberfire.io.impl.IOServiceDotFileImpl;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.Paths;
import static org.uberfire.io.regex.AntPathMatcher.*;
public class AntPathMatcherTest {
final static IOService ioService = new IOServiceDotFileImpl();
private static File path = null;
@BeforeClass
public static void setup() throws IOException {
path = CommonIOServiceDotFileTest.createTempDirectory();
System.setProperty( "org.uberfire.nio.git.dir", path.getAbsolutePath() );
System.out.println( ".niogit: " + path.getAbsolutePath() );
final URI newRepo = URI.create( "git://antpathmatcher" );
ioService.newFileSystem( newRepo, new HashMap<String, Object>() );
}
@AfterClass
@BeforeClass
public static void cleanup() {
if ( path != null ) {
FileUtils.deleteQuietly( path );
}
}
@Test
public void testIncludes() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "git://**" );
add( "**/repo/**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertFalse( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertTrue( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher" ) );
Assert.assertTrue( includes( patterns, path ) );
}
}
@Test
public void testIncludesMid() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "default://**" );
add( "**/repo/**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertTrue( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertFalse( includes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher/repo/sss" ) );
Assert.assertTrue( includes( patterns, path ) );
}
}
@Test
public void testExcludes() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "git://**" );
add( "**/repo/**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertFalse( excludes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertTrue( excludes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher" ) );
Assert.assertTrue( excludes( patterns, path ) );
}
}
@Test
public void testExcludesMid() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "default://**" );
add( "**/repo/**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertTrue( excludes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertFalse( excludes( patterns, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher/repo/sss" ) );
Assert.assertTrue( excludes( patterns, path ) );
}
}
@Test
public void testFilter() {
final Collection<String> includes = new ArrayList<String>() {{
add( "git://**" );
}};
final Collection<String> excludes = new ArrayList<String>() {{
add( "default://**" );
}};
{
final Path path = Paths.get( URI.create( "file:///Users/home" ) );
Assert.assertFalse( filter( includes, excludes, path ) );
}
{
final Path path = Paths.get( URI.create( "git://antpathmatcher" ) );
Assert.assertTrue( filter( includes, excludes, path ) );
}
{
final Path path = Paths.get( URI.create( "git://master@antpathmatcher/repo/sss" ) );
Assert.assertTrue( filter( includes, excludes, path ) );
}
Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), Paths.get( URI.create( "git://master@antpathmatcher/repo/sss" ) ) ) );
Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), Paths.get( URI.create( "git://antpathmatcher" ) ) ) );
}
@Test
public void testIncludesUri() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "git://**" );
add( "**/repo/**" );
}};
Assert.assertFalse( includes( patterns, URI.create( "file:///Users/home" ) ) );
Assert.assertTrue( includes( patterns, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( includes( patterns, URI.create( "git://master@antpathmatcher" ) ) );
}
@Test
public void testIncludesMidUri() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "file://**" );
add( "**/repo/**" );
}};
Assert.assertTrue( includes( patterns, URI.create( "file:///Users/home" ) ) );
Assert.assertFalse( includes( patterns, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( includes( patterns, URI.create( "git://master@antpathmatcher/repo/sss" ) ) );
}
@Test
public void testExcludesUri() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "git://**" );
add( "**/repo/**" );
}};
Assert.assertFalse( excludes( patterns, URI.create( "file:///Users/home" ) ) );
Assert.assertTrue( excludes( patterns, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( excludes( patterns, URI.create( "git://master@antpathmatcher" ) ) );
}
@Test
public void testExcludesMidUri() {
final Collection<String> patterns = new ArrayList<String>() {{
add( "file://**" );
add( "**/repo/**" );
}};
Assert.assertTrue( excludes( patterns, URI.create( "file:///Users/home" ) ) );
Assert.assertFalse( excludes( patterns, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( excludes( patterns, URI.create( "git://master@antpathmatcher/repo/sss" ) ) );
}
@Test
public void testFilterUri() {
final Collection<String> includes = new ArrayList<String>() {{
add( "git://**" );
}};
final Collection<String> excludes = new ArrayList<String>() {{
add( "file://**" );
}};
Assert.assertFalse( filter( includes, excludes, URI.create( "file:///Users/home" ) ) );
Assert.assertTrue( filter( includes, excludes, URI.create( "git://antpathmatcher" ) ) );
Assert.assertTrue( filter( includes, excludes, URI.create( "git://master@antpathmatcher/repo/sss" ) ) );
Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), URI.create( "file:///Users/home" ) ) );
Assert.assertTrue( filter( Collections.<String>emptyList(), Collections.<String>emptyList(), URI.create( "git://master@antpathmatcher/repo/sss" ) ) );
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_2293_2
|
crossvul-java_data_good_5851_0
|
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
* Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
* id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques
* Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.EnvVars;
import hudson.Functions;
import antlr.ANTLRException;
import hudson.AbortException;
import hudson.CopyOnWrite;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.queue.SubTask;
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTaskContributor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.Permission;
import hudson.slaves.WorkspaceList;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import jenkins.util.TimeDuration;
import net.sf.json.JSONObject;
import org.apache.tools.ant.taskdefs.email.Mailer;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
*/
private volatile SCM scm = new NullSCM();
/**
* Controls how the checkout is done.
*/
private volatile SCMCheckoutStrategy scmCheckoutStrategy;
/**
* State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
*/
private volatile transient SCMRevisionState pollingBaseline = null;
/**
* All the builds keyed by their build number.
*
* External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via
* {@link Run#getPreviousBuild()}
*/
@Restricted(NoExternalUse.class)
@SuppressWarnings("deprecation") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called
protected transient RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
*/
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
*/
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when downstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenDownstreamBuilding = false;
/**
* True to keep builds of this project in queue when upstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenUpstreamBuilding = false;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}
* are saved independently.
*
* @see Jenkins#getJDK(String)
*/
private volatile String jdk;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
private boolean concurrentBuild;
/**
* See {@link #setCustomWorkspace(String)}.
*
* @since 1.410
*/
private String customWorkspace;
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
if(!Jenkins.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public synchronized void save() throws IOException {
super.save();
updateTransientActions();
}
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
builds = createBuildRunMap();
// solicit initial contributions, especially from TransientProjectActionFactory
updateTransientActions();
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
RunMap<R> builds = createBuildRunMap();
if (this.builds!=null) {
// if we are reloading, keep all those that are still building intact
for (R r : this.builds.getLoadedBuilds().values()) {
if (r.isBuilding())
builds.put(r);
}
}
this.builds = builds;
for (Trigger t : triggers())
t.start(this, Items.updatingByXml.get());
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
}
private RunMap<R> createBuildRunMap() {
return new RunMap<R>(getBuildDir(), new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
}
private synchronized List<Trigger<?>> triggers() {
if (triggers == null) {
triggers = new Vector<Trigger<?>>();
}
return triggers;
}
@Override
public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(node, listener);
JDK jdk = getJDK();
if (jdk != null) {
if (node != null) { // just in case were not in a build
jdk = jdk.forNode(node, listener);
}
jdk.buildEnvVars(env);
}
return env;
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
@Exported
public boolean isConcurrentBuild() {
return concurrentBuild;
}
public void setConcurrentBuild(boolean b) throws IOException {
concurrentBuild = b;
save();
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Jenkins.getInstance().getSelfLabel();
return Jenkins.getInstance().getLabel(assignedNode);
}
/**
* Set of labels relevant to this job.
*
* This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.
* It does not affect the scheduling. This information is informational and the best-effort basis.
*
* @since 1.456
* @return
* Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element
* to correspond to the null return value from {@link #getAssignedLabel()}.
*/
public Set<Label> getRelevantLabels() {
return Collections.singleton(getAssignedLabel());
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (canRoam || assignedNode==null) return null;
try {
LabelExpression.parseExpression(assignedNode);
return assignedNode;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(assignedNode);
}
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getExpression();
}
save();
}
/**
* Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
*/
public void setAssignedNode(Node l) throws IOException {
setAssignedLabel(l.getSelfLabel());
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
}
/**
* Gets the human readable display name to be rendered in the "Build Now" link.
*
* @since 1.401
*/
public String getBuildNowText() {
return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
}
/**
* Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.
*
* <p>
* Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs
* that acts as a single unit. This method can be used to find the top most dominating job that
* covers such a tree.
*
* @return never null.
* @see AbstractBuild#getRootBuild()
*/
public AbstractProject<?,?> getRootProject() {
if (this instanceof TopLevelItem) {
return this;
} else {
ItemGroup p = this.getParent();
if (p instanceof AbstractProject)
return ((AbstractProject) p).getRootProject();
return this;
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
}
/**
* Various deprecated methods in this class all need the 'current' build. This method returns
* the build suitable for that purpose.
*
* @return An AbstractBuild for deprecated methods to use.
*/
private AbstractBuild getBuildForDeprecatedMethods() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b;
}
}
R lb = getLastBuild();
if(lb!=null) return lb;
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
if (b!=null) return b.getWorkspace();
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
FilePath f = browser.getWorkspace(this);
if (f != null) return f;
}
return null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
}
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();
}
public SCMCheckoutStrategy getScmCheckoutStrategy() {
return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;
}
public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {
this.scmCheckoutStrategy = scmCheckoutStrategy;
save();
}
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();
}
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return quietPeriod!=null;
}
/**
* Sets the custom quiet period of this project, or revert to the global default if null is given.
*/
public void setQuietPeriod(Integer seconds) throws IOException {
this.quietPeriod = seconds;
save();
}
public boolean hasCustomScmCheckoutRetryCount(){
return scmCheckoutRetryCount != null;
}
@Override
public boolean isBuildable() {
return !isDisabled() && !isHoldOffBuildUntilSave();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenDownstreamBuilding() {
return blockBuildWhenDownstreamBuilding;
}
public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
blockBuildWhenDownstreamBuilding = b;
save();
}
public boolean blockBuildWhenUpstreamBuilding() {
return blockBuildWhenUpstreamBuilding;
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
blockBuildWhenUpstreamBuilding = b;
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Jenkins.getInstance().getQueue().cancel(this);
save();
}
/**
* Specifies whether this project may be disabled by the user.
* By default, it can be only if this is a {@link TopLevelItem};
* would be false for matrix configurations, etc.
* @return true if the GUI should allow {@link #doDisable} and the like
* @since 1.475
*/
public boolean supportsMakeDisabled() {
return this instanceof TopLevelItem;
}
public void disable() throws IOException {
makeDisabled(true);
}
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
/**
* effectively deprecated. Since using updateTransientActions correctly
* under concurrent environment requires a lock that can too easily cause deadlocks.
*
* <p>
* Override {@link #createTransientActions()} instead.
*/
protected void updateTransientActions() {
transientActions = createTransientActions();
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
for (JobProperty<? super P> p : Util.fixNull(properties))
ta.addAll(p.getJobActions((P)this));
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
return ta;
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
updateTransientActions();
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Jenkins.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects(p));
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(p,newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
}
}
// notify the queue as the project might be now tied to different node
Jenkins.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Jenkins.getInstance().rebuildDependencyGraph();
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this array can contain null, and those will be silently ignored.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this collection can contain null, and those will be silently ignored.
* @since 1.383
*/
@SuppressWarnings("unchecked")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
if (!isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (QueueTaskFuture)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
@SuppressWarnings("deprecation")
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Jenkins.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Jenkins.getInstance().getQueue().getItem(this);
}
/**
* Gets the JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Jenkins.getInstance().getJDK(jdk);
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
this.jdk = jdk.getName();
save();
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
@Override
public RunMap<R> _getRuns() {
return builds;
}
@Override
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuild(String id) {
return builds.getById(id);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getBuildByNumber(int n) {
return builds.getByNumber(n);
}
/**
* {@inheritDoc}
*
* More efficient implementation.
*/
@Override
public R getFirstBuild() {
return builds.oldestBuild();
}
@Override
public R getLastBuild() {
return builds.newestBuild();
}
@Override
public R getNearestBuild(int n) {
return builds.search(n, Direction.ASC);
}
@Override
public R getNearestOldBuild(int n) {
return builds.search(n, Direction.DESC);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public synchronized List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
public Object getSameNodeConstraint() {
return this; // in this way, any member that wants to run with the main guy can nominate the project itself
}
public final Task getOwnerTask() {
return this;
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the downstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
// Block builds until they are done with post-production
if (isLogUpdated() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenDownstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingDownstream();
if (bup!=null)
return new BecauseOfDownstreamBuildInProgress(bup);
}
if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the downstream project is either
* building, waiting, pending or buildable.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingDownstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveDownstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
/**
* Returns the project if any of the upstream project is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
public AbstractProject getBuildingUpstream() {
Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();
for (AbstractProject tup : getTransitiveUpstreamProjects()) {
if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
return tup;
}
return null;
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
for (JobProperty<? super P> p : properties)
r.addAll(p.getSubTasks());
return r;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
if (r) {
// Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations
// won't reach this line anyway, as they throw AbortExceptions on checkout failure.
calcPollingBaseline(build, launcher, listener);
}
return r;
}
/**
* Pushes the baseline up to the newly checked out revision.
*/
private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
if (baseline==null) {
try {
baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
} catch (AbstractMethodError e) {
baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
}
if (baseline!=null)
build.addAction(baseline);
}
pollingBaseline = baseline;
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The implementation is responsible for ensuring mutual exclusion between polling and builds
* if necessary.
*
* @since 1.345
*/
public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (!isBuildable()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
SCMPollListener.fireBeforePolling(this, listener);
PollingResult r = _poll(listener, scm, lb);
SCMPollListener.firePollingSuccess(this,listener, r);
return r;
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
SCMPollListener.firePollingFailed(this, listener,e);
return NO_CHANGES;
} catch (RuntimeException e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
} catch (Error e) {
SCMPollListener.firePollingFailed(this, listener,e);
throw e;
}
}
/**
* {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
*/
private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
if ( workspaceOfflineReason != null ) {
// workspace offline
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
ws = browser.getWorkspace(this);
if (ws != null) {
return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
}
}
// build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().print(Messages.AbstractProject_NoWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());
listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")");
return BUILD_NOW;
}
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
return pollWithWorkspace(listener, scm, lb, ws, l);
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
}
private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
enum WorkspaceOfflineReason {
nonexisting_workspace,
builton_node_gone,
builton_node_no_executors
}
private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {
FilePath ws = build.getWorkspace();
if (ws==null || !ws.exists()) {
return WorkspaceOfflineReason.nonexisting_workspace;
}
Node builtOn = build.getBuiltOn();
if (builtOn == null) { // node built-on doesn't exist anymore
return WorkspaceOfflineReason.builton_node_gone;
}
if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.
return WorkspaceOfflineReason.builton_node_no_executors;
}
return null;
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
@Exported
public SCM getScm() {
return scm;
}
public void setScm(SCM scm) throws IOException {
this.scm = scm;
save();
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
public void addTrigger(Trigger<?> trigger) throws IOException {
addToList(trigger,triggers());
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
removeFromList(trigger,triggers());
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i,item);
save();
return;
}
}
// add
collection.add(item);
save();
updateTransientActions();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
updateTransientActions();
return;
}
}
}
@SuppressWarnings("unchecked")
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(triggers());
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : triggers()) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects(ap).contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Jenkins.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {
if (delay==null) delay=new TimeDuration(getQuietPeriod());
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
if (pp != null) {
pp._doBuild(req,rsp,delay);
return;
}
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));
rsp.sendRedirect(".");
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
/*package*/ CauseAction getBuildCause(StaplerRequest req) {
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserIdCause();
}
return new CauseAction(cause);
}
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*
* @deprecated as of 1.488
* Inject {@link TimeDuration}.
*/
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
return Integer.parseInt(delay);
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp,delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.sendRedirect(".");
}
/**
* Cancels a scheduled build.
*/
@RequirePOST
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ABORT);
Jenkins.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
/**
* Deletes this project.
*/
@Override
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
delete();
if (req == null || rsp == null)
return;
View view = req.findAncestorObject(View.class);
if (view == null)
rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());
else
rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
makeDisabled(req.getParameter("disable")!=null);
jdk = req.getParameter("jdk");
if(req.getParameter("hasCustomQuietPeriod")!=null) {
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
} else {
quietPeriod = null;
}
if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
} else {
scmCheckoutRetryCount = null;
}
blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;
if(req.hasParameter("customWorkspace")) {
customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory"));
} else {
customWorkspace = null;
}
if (json.has("scmCheckoutStrategy"))
scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,
json.getJSONObject("scmCheckoutStrategy"));
else
scmCheckoutStrategy = null;
if(req.getParameter("hasSlaveAffinity")!=null) {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
} else {
assignedNode = null;
}
canRoam = assignedNode==null;
concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
for (Trigger t : triggers())
t.stop();
triggers = buildDescribable(req, Trigger.for_(this));
for (Trigger t : triggers)
t.start(this,true);
for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
BuildTrigger t = (BuildTrigger) _t;
for (AbstractProject downstream : t.getChildProjects(this)) {
downstream.checkPermission(BUILD);
}
}
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
T instance = d.newInstance(req, data.getJSONObject(safeName));
r.add(instance);
}
}
return r;
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
// Would be good if when asked for *plain*, do something else!
// (E.g. return 404, or send empty doc.)
// Not critical; client can just check if content type is not text/plain,
// which also serves to detect old versions of Hudson.
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b!=null ? b.getWorkspace() : null;
if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
for (WorkspaceListener wl : WorkspaceListener.all()) {
wl.afterDelete(this);
}
return new HttpRedirect(".");
} else {
// If we get here, that means the SCM blocked the workspace deletion.
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
@CLIMethod(name="disable-job")
@RequirePOST
public HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
@RequirePOST
public HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return JenkinsLocationConfiguration.get().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
if (Util.fixEmpty(value)==null)
return FormValidation.ok(); // nothing typed yet
try {
Label.parseExpression(value);
} catch (ANTLRException e) {
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
Label l = Jenkins.getInstance().getLabel(value);
if (l.isEmpty()) {
for (LabelAtom a : l.listAtoms()) {
if (a.isEmpty()) {
LabelAtom nearest = LabelAtom.findNearest(a.getName());
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));
}
}
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
}
return FormValidation.ok();
}
public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
if(Util.fixEmptyAndTrim(customWorkspace)==null)
return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());
else
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {
AutoCompletionCandidates candidates = new AutoCompletionCandidates();
List<Job> jobs = Jenkins.getInstance().getItems(Job.class);
for (Job job: jobs) {
if (job.getFullName().startsWith(value)) {
if (job.hasPermission(Item.READ)) {
candidates.add(job.getFullName());
}
}
}
return candidates;
}
public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
AutoCompletionCandidates c = new AutoCompletionCandidates();
Set<Label> labels = Jenkins.getInstance().getLabels();
List<String> queries = new AutoCompleteSeeder(value).getSeeds();
for (String term : queries) {
for (Label l : labels) {
if (l.getName().startsWith(term)) {
c.add(l.getName());
}
}
}
return c;
}
public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {
return SCMCheckoutStrategyDescriptor._for(p);
}
/**
* Utility class for taking the current input value and computing a list
* of potential terms to match against the list of defined labels.
*/
static class AutoCompleteSeeder {
private String source;
AutoCompleteSeeder(String source) {
this.source = source;
}
List<String> getSeeds() {
ArrayList<String> terms = new ArrayList<String>();
boolean trailingQuote = source.endsWith("\"");
boolean leadingQuote = source.startsWith("\"");
boolean trailingSpace = source.endsWith(" ");
if (trailingQuote || (trailingSpace && !leadingQuote)) {
terms.add("");
} else {
if (leadingQuote) {
int quote = source.lastIndexOf('"');
if (quote == 0) {
terms.add(source.substring(1));
} else {
terms.add("");
}
} else {
int space = source.lastIndexOf(' ');
if (space > -1) {
terms.add(source.substring(space+1));
} else {
terms.add(source);
}
}
}
return terms;
}
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
return findNearest(name,Hudson.getInstance());
}
/**
* Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
*
* @since 1.419
*/
public static AbstractProject findNearest(String name, ItemGroup context) {
List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getRelativeNameFrom(context);
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build
*/
public static final Permission ABORT = CANCEL;
/**
* Replaceable "Build Now" text.
*/
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();
/**
* Used for CLI binding.
*/
@CLIResolver
public static AbstractProject resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);
if (item==null)
throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
return item;
}
public String getCustomWorkspace() {
return customWorkspace;
}
/**
* User-specified workspace directory, or null if it's up to Jenkins.
*
* <p>
* Normally a project uses the workspace location assigned by its parent container,
* but sometimes people have builds that have hard-coded paths.
*
* <p>
* This is not {@link File} because it may have to hold a path representation on another OS.
*
* <p>
* If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace
* is prepared.
*
* @since 1.410
*/
public void setCustomWorkspace(String customWorkspace) throws IOException {
this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);
save();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_5851_0
|
crossvul-java_data_good_4727_1
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.kernel.cache.PortalCache;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.template.Template;
import com.liferay.portal.kernel.template.TemplateContextType;
import com.liferay.portal.kernel.template.TemplateException;
import com.liferay.portal.kernel.template.TemplateManager;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.security.lang.PortalSecurityManagerThreadLocal;
import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
import com.liferay.portal.security.pacl.PACLPolicy;
import com.liferay.portal.security.pacl.PACLPolicyManager;
import com.liferay.portal.template.RestrictedTemplate;
import com.liferay.portal.template.TemplateContextHelper;
import com.liferay.portal.util.PropsValues;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Mika Koivisto
* @author Tina Tina
*/
public class FreeMarkerManager implements TemplateManager {
public void clearCache() {
_stringTemplateLoader.removeTemplates();
PortalCache portalCache = LiferayCacheStorage.getPortalCache();
portalCache.removeAll();
}
public void clearCache(String templateId) {
_stringTemplateLoader.removeTemplate(templateId);
PortalCache portalCache = LiferayCacheStorage.getPortalCache();
portalCache.remove(templateId);
}
public void destroy() {
if (_configuration == null) {
return;
}
_classLoaderHelperUtilities.clear();
_classLoaderHelperUtilities = null;
_configuration.clearEncodingMap();
_configuration.clearSharedVariables();
_configuration.clearTemplateCache();
_configuration = null;
_restrictedHelperUtilities.clear();
_restrictedHelperUtilities = null;
_standardHelperUtilities.clear();
_standardHelperUtilities = null;
_stringTemplateLoader.removeTemplates();
_stringTemplateLoader = null;
_templateContextHelper = null;
}
public void destroy(ClassLoader classLoader) {
_classLoaderHelperUtilities.remove(classLoader);
}
public Template getTemplate(
String templateId, String templateContent, String errorTemplateId,
String errorTemplateContent, TemplateContextType templateContextType) {
if (templateContextType.equals(TemplateContextType.CLASS_LOADER)) {
// This template will have all of its utilities initialized within
// the class loader of the current thread
ClassLoader contextClassLoader =
PACLClassLoaderUtil.getContextClassLoader();
PACLPolicy threadLocalPACLPolicy =
PortalSecurityManagerThreadLocal.getPACLPolicy();
PACLPolicy contextClassLoaderPACLPolicy =
PACLPolicyManager.getPACLPolicy(contextClassLoader);
try {
PortalSecurityManagerThreadLocal.setPACLPolicy(
contextClassLoaderPACLPolicy);
Map<String, Object> helperUtilities =
_classLoaderHelperUtilities.get(contextClassLoader);
if (helperUtilities == null) {
helperUtilities =
_templateContextHelper.getHelperUtilities();
_classLoaderHelperUtilities.put(
contextClassLoader, helperUtilities);
}
return new PACLFreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, helperUtilities, _configuration,
_templateContextHelper, _stringTemplateLoader,
contextClassLoaderPACLPolicy);
}
finally {
PortalSecurityManagerThreadLocal.setPACLPolicy(
threadLocalPACLPolicy);
}
}
else if (templateContextType.equals(TemplateContextType.EMPTY)) {
return new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, null, _configuration,
_templateContextHelper, _stringTemplateLoader);
}
else if (templateContextType.equals(TemplateContextType.RESTRICTED)) {
return new RestrictedTemplate(
new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, _restrictedHelperUtilities,
_configuration, _templateContextHelper,
_stringTemplateLoader),
_templateContextHelper.getRestrictedVariables());
}
else if (templateContextType.equals(TemplateContextType.STANDARD)) {
return new FreeMarkerTemplate(
templateId, templateContent, errorTemplateId,
errorTemplateContent, _standardHelperUtilities, _configuration,
_templateContextHelper, _stringTemplateLoader);
}
return null;
}
public Template getTemplate(
String templateId, String templateContent, String errorTemplateId,
TemplateContextType templateContextType) {
return getTemplate(
templateId, templateContent, errorTemplateId, null,
templateContextType);
}
public Template getTemplate(
String templateId, String templateContent,
TemplateContextType templateContextType) {
return getTemplate(
templateId, templateContent, null, null, templateContextType);
}
public Template getTemplate(
String templateId, TemplateContextType templateContextType) {
return getTemplate(templateId, null, null, null, templateContextType);
}
public String getTemplateManagerName() {
return TemplateManager.FREEMARKER;
}
public boolean hasTemplate(String templateId) {
try {
freemarker.template.Template template = _configuration.getTemplate(
templateId);
if (template != null) {
return true;
}
else {
return false;
}
}
catch (IOException ioe) {
if (_log.isWarnEnabled()) {
_log.warn(ioe, ioe);
}
return false;
}
}
public void init() throws TemplateException {
if (_configuration != null) {
return;
}
LiferayTemplateLoader liferayTemplateLoader =
new LiferayTemplateLoader();
liferayTemplateLoader.setTemplateLoaders(
PropsValues.FREEMARKER_ENGINE_TEMPLATE_LOADERS);
_stringTemplateLoader = new StringTemplateLoader();
MultiTemplateLoader multiTemplateLoader =
new MultiTemplateLoader(
new TemplateLoader[] {
new ClassTemplateLoader(getClass(), StringPool.SLASH),
_stringTemplateLoader, liferayTemplateLoader
});
_configuration = new Configuration();
_configuration.setDefaultEncoding(StringPool.UTF8);
_configuration.setLocalizedLookup(
PropsValues.FREEMARKER_ENGINE_LOCALIZED_LOOKUP);
_configuration.setNewBuiltinClassResolver(
new LiferayTemplateClassResolver());
_configuration.setObjectWrapper(new LiferayObjectWrapper());
_configuration.setTemplateLoader(multiTemplateLoader);
_configuration.setTemplateUpdateDelay(
PropsValues.FREEMARKER_ENGINE_MODIFICATION_CHECK_INTERVAL);
try {
_configuration.setSetting(
"auto_import", PropsValues.FREEMARKER_ENGINE_MACRO_LIBRARY);
_configuration.setSetting(
"cache_storage", PropsValues.FREEMARKER_ENGINE_CACHE_STORAGE);
_configuration.setSetting(
"template_exception_handler",
PropsValues.FREEMARKER_ENGINE_TEMPLATE_EXCEPTION_HANDLER);
}
catch (Exception e) {
throw new TemplateException("Unable to init freemarker manager", e);
}
_standardHelperUtilities = _templateContextHelper.getHelperUtilities();
_restrictedHelperUtilities =
_templateContextHelper.getRestrictedHelperUtilities();
}
public void setTemplateContextHelper(
TemplateContextHelper templateContextHelper) {
_templateContextHelper = templateContextHelper;
}
private static Log _log = LogFactoryUtil.getLog(FreeMarkerManager.class);
private Map<ClassLoader, Map<String, Object>> _classLoaderHelperUtilities =
new ConcurrentHashMap<ClassLoader, Map<String, Object>>();
private Configuration _configuration;
private Map<String, Object> _restrictedHelperUtilities;
private Map<String, Object> _standardHelperUtilities;
private StringTemplateLoader _stringTemplateLoader;
private TemplateContextHelper _templateContextHelper;
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_1
|
crossvul-java_data_bad_4727_4
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_4727_4
|
crossvul-java_data_bad_2293_0
|
404: Not Found
|
./CrossVul/dataset_final_sorted/CWE-264/java/bad_2293_0
|
crossvul-java_data_good_4727_2
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portal.freemarker;
import com.liferay.portal.kernel.templateparser.TemplateContext;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Theme;
import com.liferay.portal.template.TemplateContextHelper;
import com.liferay.portal.template.TemplatePortletPreferences;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PropsValues;
import com.liferay.portal.util.WebKeys;
import freemarker.ext.beans.BeansWrapper;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/**
* @author Mika Koivisto
* @author Raymond Augé
*/
public class FreeMarkerTemplateContextHelper extends TemplateContextHelper {
@Override
public Map<String, Object> getHelperUtilities() {
Map<String, Object> helperUtilities = super.getHelperUtilities();
// Enum util
helperUtilities.put(
"enumUtil", BeansWrapper.getDefaultInstance().getEnumModels());
// Object util
helperUtilities.put("objectUtil", new LiferayObjectConstructor());
// Portlet preferences
helperUtilities.put(
"freeMarkerPortletPreferences", new TemplatePortletPreferences());
// Static class util
helperUtilities.put(
"staticUtil", BeansWrapper.getDefaultInstance().getStaticModels());
return helperUtilities;
}
@Override
public Set<String> getRestrictedVariables() {
return SetUtil.fromArray(
PropsValues.JOURNAL_TEMPLATE_FREEMARKER_RESTRICTED_VARIABLES);
}
@Override
public void prepare(
TemplateContext templateContext, HttpServletRequest request) {
super.prepare(templateContext, request);
// Theme display
ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
WebKeys.THEME_DISPLAY);
if (themeDisplay != null) {
Theme theme = themeDisplay.getTheme();
// Full css and templates path
String servletContextName = GetterUtil.getString(
theme.getServletContextName());
templateContext.put(
"fullCssPath",
StringPool.SLASH + servletContextName +
theme.getFreeMarkerTemplateLoader() + theme.getCssPath());
templateContext.put(
"fullTemplatesPath",
StringPool.SLASH + servletContextName +
theme.getFreeMarkerTemplateLoader() +
theme.getTemplatesPath());
// Init
templateContext.put(
"init",
StringPool.SLASH + themeDisplay.getPathContext() +
FreeMarkerTemplateLoader.SERVLET_SEPARATOR +
"/html/themes/_unstyled/templates/init.ftl");
}
// Insert custom ftl variables
Map<String, Object> ftlVariables =
(Map<String, Object>)request.getAttribute(WebKeys.FTL_VARIABLES);
if (ftlVariables != null) {
for (Map.Entry<String, Object> entry : ftlVariables.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (Validator.isNotNull(key)) {
templateContext.put(key, value);
}
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_4727_2
|
crossvul-java_data_good_3820_4
|
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.sync;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.candlepin.config.CandlepinCommonTestConfig;
import org.candlepin.config.Config;
import org.candlepin.config.ConfigProperties;
import org.candlepin.model.ExporterMetadata;
import org.candlepin.model.ExporterMetadataCurator;
import org.candlepin.model.Owner;
import org.candlepin.pki.PKIUtility;
import org.candlepin.sync.Importer.ImportFile;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* ImporterTest
*/
public class ImporterTest {
private ObjectMapper mapper;
private I18n i18n;
private static final String MOCK_JS_PATH = "/tmp/empty.js";
private CandlepinCommonTestConfig config;
@Before
public void init() throws FileNotFoundException, URISyntaxException {
mapper = SyncUtils.getObjectMapper(new Config(new HashMap<String, String>()));
i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
config = new CandlepinCommonTestConfig();
config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp");
PrintStream ps = new PrintStream(new File(this.getClass()
.getClassLoader().getResource("candlepin_info.properties").toURI()));
ps.println("version=0.0.3");
ps.println("release=1");
ps.close();
}
@Test
public void validateMetaJson() throws Exception {
/* read file
* read in version
* read in created date
* make sure created date is XYZ
* make sure version is > ABC
*/
Date now = new Date();
File file = createFile("/tmp/meta", "0.0.3", now,
"test_user", "prefix");
File actual = createFile("/tmp/meta.json", "0.0.3", now,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
ExporterMetadata em = new ExporterMetadata();
Date daybefore = getDateBeforeDays(1);
em.setExported(daybefore);
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actual,
new ConflictOverrides());
Meta fileMeta = mapper.readValue(file, Meta.class);
Meta actualMeta = mapper.readValue(actual, Meta.class);
assertEquals(fileMeta.getPrincipalName(), actualMeta.getPrincipalName());
assertEquals(fileMeta.getCreated().getTime(), actualMeta.getCreated().getTime());
assertEquals(fileMeta.getWebAppPrefix(), actualMeta.getWebAppPrefix());
assertTrue(file.delete());
assertTrue(actual.delete());
assertTrue(daybefore.compareTo(em.getExported()) < 0);
}
@Test
public void firstRun() throws Exception {
File f = createFile("/tmp/meta", "0.0.3", new Date(),
"test_user", "prefix");
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
assertTrue(f.delete());
assertTrue(actualmeta.delete());
verify(emc).create(any(ExporterMetadata.class));
}
@Test
public void oldImport() throws Exception {
// actualmeta is the mock for the import itself
File actualmeta = createFile("/tmp/meta.json", "0.0.3", getDateBeforeDays(10),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// emc is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(getDateBeforeDays(3));
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
try {
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
fail();
}
catch (ImportConflictException e) {
assertFalse(e.message().getConflicts().isEmpty());
assertEquals(1, e.message().getConflicts().size());
assertTrue(e.message().getConflicts().contains(
Importer.Conflict.MANIFEST_OLD));
}
}
@Test
public void sameImport() throws Exception {
// actualmeta is the mock for the import itself
Date date = getDateBeforeDays(10);
File actualmeta = createFile("/tmp/meta.json", "0.0.3", date,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// emc is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(date); // exact same date = assumed same manifest
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
try {
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
fail();
}
catch (ImportConflictException e) {
assertFalse(e.message().getConflicts().isEmpty());
assertEquals(1, e.message().getConflicts().size());
assertTrue(e.message().getConflicts().contains(
Importer.Conflict.MANIFEST_SAME));
}
}
@Test
public void mergeConflicts() {
ImportConflictException e2 = new ImportConflictException("testing",
Importer.Conflict.DISTRIBUTOR_CONFLICT);
ImportConflictException e3 = new ImportConflictException("testing2",
Importer.Conflict.MANIFEST_OLD);
List<ImportConflictException> exceptions =
new LinkedList<ImportConflictException>();
exceptions.add(e2);
exceptions.add(e3);
ImportConflictException e1 = new ImportConflictException(exceptions);
assertEquals("testing\ntesting2", e1.message().getDisplayMessage());
assertEquals(2, e1.message().getConflicts().size());
assertTrue(e1.message().getConflicts().contains(
Importer.Conflict.DISTRIBUTOR_CONFLICT));
assertTrue(e1.message().getConflicts().contains(Importer.Conflict.MANIFEST_OLD));
}
@Test
public void newerImport() throws Exception {
// this tests bz #790751
Date importDate = getDateBeforeDays(10);
// actualmeta is the mock for the import itself
File actualmeta = createFile("/tmp/meta.json", "0.0.3", importDate,
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
// em is the mock for lastrun (i.e., the most recent import in CP)
ExporterMetadata em = new ExporterMetadata();
em.setExported(getDateBeforeDays(30));
em.setId("42");
em.setType(ExporterMetadata.TYPE_SYSTEM);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(em);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
assertEquals(importDate, em.getExported());
}
@Test
public void newerVersionImport() throws Exception {
// if we do are importing candlepin 0.0.10 data into candlepin 0.0.3,
// import the rules.
String version = "0.0.10";
File actualmeta = createFile("/tmp/meta.json", version, new Date(),
"test_user", "prefix");
File[] jsArray = createMockJsFile(MOCK_JS_PATH);
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
RulesImporter ri = mock(RulesImporter.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, null, emc, null, null, i18n);
i.importRules(jsArray, actualmeta);
//verify that rules were imported
verify(ri).importObject(any(Reader.class), eq(version));
}
@Test
public void olderVersionImport() throws Exception {
// if we are importing candlepin 0.0.1 data into
// candlepin 0.0.3, do not import the rules
File actualmeta = createFile("/tmp/meta.json", "0.0.1", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
RulesImporter ri = mock(RulesImporter.class);
when(emc.lookupByType(ExporterMetadata.TYPE_SYSTEM)).thenReturn(null);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, null, emc, null, null, i18n);
i.validateMetadata(ExporterMetadata.TYPE_SYSTEM, null, actualmeta,
new ConflictOverrides());
//verify that rules were not imported
verify(ri, never()).importObject(any(Reader.class), any(String.class));
}
@Test(expected = ImporterException.class)
public void nullType() throws ImporterException, IOException {
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
try {
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, null, null, null, i18n);
// null Type should cause exception
i.validateMetadata(null, null, actualmeta, new ConflictOverrides());
}
finally {
assertTrue(actualmeta.delete());
}
}
@Test(expected = ImporterException.class)
public void expectOwner() throws ImporterException, IOException {
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
ExporterMetadataCurator emc = mock(ExporterMetadataCurator.class);
when(emc.lookupByTypeAndOwner(ExporterMetadata.TYPE_PER_USER, null))
.thenReturn(null);
Importer i = new Importer(null, null, null, null, null, null, null,
null, null, emc, null, null, i18n);
// null Type should cause exception
i.validateMetadata(ExporterMetadata.TYPE_PER_USER, null, actualmeta,
new ConflictOverrides());
verify(emc, never()).create(any(ExporterMetadata.class));
}
@Test
public void testImportWithNonZipArchive()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/non_zip_file.zip");
FileWriter fw = new FileWriter(archive);
fw.write("Just a flat file");
fw.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The archive {0} is " +
"not a properly compressed file or is empty", "non_zip_file.zip"));
return;
}
assertTrue(false);
}
@Test
public void testImportZipArchiveNoContent()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("This is just a zip file with no content"));
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not " +
"contain the required signature file"));
return;
}
assertTrue(false);
}
@Test(expected = ImportConflictException.class)
public void testImportBadSignature()
throws IOException, ImporterException {
PKIUtility pki = mock(PKIUtility.class);
Importer i = new Importer(null, null, null, null, null, null, null,
pki, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
FileOutputStream fos = new FileOutputStream(ceArchive);
fos.write("This is just a flat file".getBytes());
fos.close();
addFileToArchive(out, ceArchive);
out.close();
i.loadExport(owner, archive, co);
}
@Test
public void testImportBadConsumerZip() throws Exception {
PKIUtility pki = mock(PKIUtility.class);
Importer i = new Importer(null, null, null, null, null, null, null,
pki, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
// Mock a passed signature check:
when(pki.verifySHA256WithRSAHashWithUpstreamCACert(any(InputStream.class),
any(byte [].class))).thenReturn(true);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
FileOutputStream fos = new FileOutputStream(ceArchive);
fos.write("This is just a flat file".getBytes());
fos.close();
addFileToArchive(out, ceArchive);
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
System.out.println(e.getMessage());
assertTrue(e.getMessage().contains(
"not a properly compressed file or is empty"));
return;
}
fail();
}
@Test
public void testImportZipSigAndEmptyConsumerZip()
throws Exception {
PKIUtility pki = mock(PKIUtility.class);
Importer i = new Importer(null, null, null, null, null, null, null,
pki, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
// Mock a passed signature check:
when(pki.verifySHA256WithRSAHashWithUpstreamCACert(any(InputStream.class),
any(byte [].class))).thenReturn(true);
File archive = new File("/tmp/file.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive));
out.putNextEntry(new ZipEntry("signature"));
out.write("This is the placeholder for the signature file".getBytes());
File ceArchive = new File("/tmp/consumer_export.zip");
ZipOutputStream cezip = new ZipOutputStream(new FileOutputStream(ceArchive));
cezip.putNextEntry(new ZipEntry("This is just a zip file with no content"));
cezip.close();
addFileToArchive(out, ceArchive);
out.close();
try {
i.loadExport(owner, archive, co);
}
catch (ImportExtractionException e) {
assertTrue(e.getMessage().contains("consumer_export archive has no contents"));
return;
}
fail();
}
@Test
public void testImportNoMeta()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), null);
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required meta.json file"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoRulesDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), null);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required rules directory"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoRulesFile()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
when(ruleDir.listFiles()).thenReturn(new File[0]);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required rules file(s)"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoConsumerTypesDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), null);
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required consumer_types directory"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoConsumer()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), null);
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), mock(File.class));
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required consumer.json file"));
return;
}
assertTrue(false);
}
@Test
public void testImportNoProductDir()
throws IOException, ImporterException {
RulesImporter ri = mock(RulesImporter.class);
Importer i = new Importer(null, null, ri, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = createMockJsFile(MOCK_JS_PATH);
when(ruleDir.listFiles()).thenReturn(rulesFiles);
File actualmeta = createFile("/tmp/meta.json", "0.0.3", new Date(),
"test_user", "prefix");
// this is the hook to stop testing. we confirm that the archive component tests
// are passed and then jump out instead of trying to fake the actual file
// processing.
when(ri.importObject(any(Reader.class), any(String.class))).thenThrow(
new RuntimeException("Done with the test"));
importFiles.put(ImportFile.META.fileName(), actualmeta);
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), null);
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), null);
try {
i.importObjects(owner, importFiles, co);
}
catch (RuntimeException e) {
assertEquals(e.getMessage(), "Done with the test");
return;
}
assertTrue(false);
}
@Test
public void testImportProductNoEntitlementDir()
throws IOException, ImporterException {
Importer i = new Importer(null, null, null, null, null, null, null,
null, config, null, null, null, i18n);
Owner owner = mock(Owner.class);
ConflictOverrides co = mock(ConflictOverrides.class);
Map<String, File> importFiles = new HashMap<String, File>();
File ruleDir = mock(File.class);
File[] rulesFiles = new File[]{mock(File.class)};
when(ruleDir.listFiles()).thenReturn(rulesFiles);
importFiles.put(ImportFile.META.fileName(), mock(File.class));
importFiles.put(ImportFile.RULES.fileName(), ruleDir);
importFiles.put(ImportFile.CONSUMER_TYPE.fileName(), mock(File.class));
importFiles.put(ImportFile.CONSUMER.fileName(), mock(File.class));
importFiles.put(ImportFile.PRODUCTS.fileName(), mock(File.class));
importFiles.put(ImportFile.ENTITLEMENTS.fileName(), null);
try {
i.importObjects(owner, importFiles, co);
}
catch (ImporterException e) {
assertEquals(e.getMessage(), i18n.tr("The archive does not contain the " +
"required entitlements directory"));
return;
}
assertTrue(false);
}
@After
public void tearDown() throws Exception {
PrintStream ps = new PrintStream(new File(this.getClass()
.getClassLoader().getResource("candlepin_info.properties").toURI()));
ps.println("version=${version}");
ps.println("release=${release}");
ps.close();
File mockJs = new File(MOCK_JS_PATH);
mockJs.delete();
}
private File createFile(String filename, String version, Date date,
String username, String prefix)
throws JsonGenerationException, JsonMappingException, IOException {
File f = new File(filename);
Meta meta = new Meta(version, date, username, prefix);
mapper.writeValue(f, meta);
return f;
}
private File[] createMockJsFile(String filename)
throws IOException {
FileWriter f = new FileWriter(filename);
f.write("// nothing to see here");
f.close();
File[] fileArray = new File[1];
fileArray[0] = new File(filename);
return fileArray;
}
private Date getDateBeforeDays(int days) {
long daysinmillis = 24 * 60 * 60 * 1000;
long ms = System.currentTimeMillis() - (days * daysinmillis);
Date backDate = new Date();
backDate.setTime(ms);
return backDate;
}
private void addFileToArchive(ZipOutputStream out, File file)
throws IOException, FileNotFoundException {
out.putNextEntry(new ZipEntry(file.getName()));
FileInputStream in = new FileInputStream(file);
byte [] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
}
|
./CrossVul/dataset_final_sorted/CWE-264/java/good_3820_4
|
crossvul-java_data_good_2476_0
|
/*
* Copyright 2017-2019 original authors
*
* Licensed 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 io.micronaut.http.netty;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.http.MutableHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.
*
* @author Graeme Rocher
* @since 1.0
*/
@Internal
public class NettyHttpHeaders implements MutableHttpHeaders {
io.netty.handler.codec.http.HttpHeaders nettyHeaders;
final ConversionService<?> conversionService;
/**
* @param nettyHeaders The Netty Http headers
* @param conversionService The conversion service
*/
public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {
this.nettyHeaders = nettyHeaders;
this.conversionService = conversionService;
}
/**
* Default constructor.
*/
public NettyHttpHeaders() {
this.nettyHeaders = new DefaultHttpHeaders();
this.conversionService = ConversionService.SHARED;
}
/**
* @return The underlying Netty headers.
*/
public io.netty.handler.codec.http.HttpHeaders getNettyHeaders() {
return nettyHeaders;
}
/**
* Sets the underlying netty headers.
*
* @param headers The Netty http headers
*/
void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) {
this.nettyHeaders = headers;
}
@Override
public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) {
List<String> values = nettyHeaders.getAll(name);
if (values.size() > 0) {
if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) {
return conversionService.convert(values.get(0), conversionContext);
} else {
return conversionService.convert(values, conversionContext);
}
}
return Optional.empty();
}
private boolean isCollectionOrArray(Class<?> clazz) {
return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
}
@Override
public List<String> getAll(CharSequence name) {
return nettyHeaders.getAll(name);
}
@Override
public Set<String> names() {
return nettyHeaders.names();
}
@Override
public Collection<List<String>> values() {
Set<String> names = names();
List<List<String>> values = new ArrayList<>();
for (String name : names) {
values.add(getAll(name));
}
return Collections.unmodifiableList(values);
}
@Override
public String get(CharSequence name) {
return nettyHeaders.get(name);
}
@Override
public MutableHttpHeaders add(CharSequence header, CharSequence value) {
nettyHeaders.add(header, value);
return this;
}
@Override
public MutableHttpHeaders remove(CharSequence header) {
nettyHeaders.remove(header);
return this;
}
}
|
./CrossVul/dataset_final_sorted/CWE-444/java/good_2476_0
|
crossvul-java_data_bad_2476_0
|
/*
* Copyright 2017-2019 original authors
*
* Licensed 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 io.micronaut.http.netty;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.http.MutableHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}.
*
* @author Graeme Rocher
* @since 1.0
*/
@Internal
public class NettyHttpHeaders implements MutableHttpHeaders {
io.netty.handler.codec.http.HttpHeaders nettyHeaders;
final ConversionService<?> conversionService;
/**
* @param nettyHeaders The Netty Http headers
* @param conversionService The conversion service
*/
public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) {
this.nettyHeaders = nettyHeaders;
this.conversionService = conversionService;
}
/**
* Default constructor.
*/
public NettyHttpHeaders() {
this.nettyHeaders = new DefaultHttpHeaders(false);
this.conversionService = ConversionService.SHARED;
}
/**
* @return The underlying Netty headers.
*/
public io.netty.handler.codec.http.HttpHeaders getNettyHeaders() {
return nettyHeaders;
}
/**
* Sets the underlying netty headers.
*
* @param headers The Netty http headers
*/
void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) {
this.nettyHeaders = headers;
}
@Override
public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) {
List<String> values = nettyHeaders.getAll(name);
if (values.size() > 0) {
if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) {
return conversionService.convert(values.get(0), conversionContext);
} else {
return conversionService.convert(values, conversionContext);
}
}
return Optional.empty();
}
private boolean isCollectionOrArray(Class<?> clazz) {
return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
}
@Override
public List<String> getAll(CharSequence name) {
return nettyHeaders.getAll(name);
}
@Override
public Set<String> names() {
return nettyHeaders.names();
}
@Override
public Collection<List<String>> values() {
Set<String> names = names();
List<List<String>> values = new ArrayList<>();
for (String name : names) {
values.add(getAll(name));
}
return Collections.unmodifiableList(values);
}
@Override
public String get(CharSequence name) {
return nettyHeaders.get(name);
}
@Override
public MutableHttpHeaders add(CharSequence header, CharSequence value) {
nettyHeaders.add(header, value);
return this;
}
@Override
public MutableHttpHeaders remove(CharSequence header) {
nettyHeaders.remove(header);
return this;
}
}
|
./CrossVul/dataset_final_sorted/CWE-444/java/bad_2476_0
|
crossvul-java_data_bad_1900_0
|
package io.onedev.server.migration;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.emitter.Emitter;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.resolver.Resolver;
import org.yaml.snakeyaml.serializer.Serializer;
import com.google.common.collect.Lists;
import io.onedev.commons.utils.StringUtils;
public class XmlBuildSpecMigrator {
private static Node migrateParamSpec(Element paramSpecElement) {
String classTag = getClassTag(paramSpecElement.getName());
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "allowEmpty"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("allowEmpty").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "allowMultiple"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("allowMultiple").trim())));
Element patternElement = paramSpecElement.element("pattern");
if (patternElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "pattern"),
new ScalarNode(Tag.STR, patternElement.getText().trim())));
}
Element descriptionElement = paramSpecElement.element("description");
if (descriptionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "description"),
new ScalarNode(Tag.STR, descriptionElement.getText().trim())));
}
Element minValueElement = paramSpecElement.element("minValue");
if (minValueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "minValue"),
new ScalarNode(Tag.STR, minValueElement.getText().trim())));
}
Element maxValueElement = paramSpecElement.element("maxValue");
if (maxValueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "maxValue"),
new ScalarNode(Tag.STR, maxValueElement.getText().trim())));
}
Element showConditionElement = paramSpecElement.element("showCondition");
if (showConditionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "showCondition"),
migrateShowCondition(showConditionElement)));
}
Element defaultValueProviderElement = paramSpecElement.element("defaultValueProvider");
if (defaultValueProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultValueProvider"),
migrateDefaultValueProvider(defaultValueProviderElement)));
}
Element defaultMultiValueProviderElement = paramSpecElement.element("defaultMultiValueProvider");
if (defaultMultiValueProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultMultiValueProvider"),
migrateDefaultMultiValueProvider(defaultMultiValueProviderElement)));
}
Element choiceProviderElement = paramSpecElement.element("choiceProvider");
if (choiceProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "choiceProvider"),
migrateChoiceProvider(choiceProviderElement)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static String getClassTag(String className) {
return "!" + StringUtils.substringAfterLast(className, ".");
}
private static Node migrateChoiceProvider(Element choiceProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(choiceProviderElement.attributeValue("class"));
Element scriptNameElement = choiceProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element choicesElement = choiceProviderElement.element("choices");
if (choicesElement != null) {
List<Node> choiceNodes = new ArrayList<>();
for (Element choiceElement: choicesElement.elements()) {
List<NodeTuple> choiceTuples = new ArrayList<>();
choiceTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, choiceElement.elementText("value").trim())));
choiceTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "color"),
new ScalarNode(Tag.STR, choiceElement.elementText("color").trim())));
choiceNodes.add(new MappingNode(Tag.MAP, choiceTuples, FlowStyle.BLOCK));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "choices"),
new SequenceNode(Tag.SEQ, choiceNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateDefaultMultiValueProvider(Element defaultMultiValueProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(defaultMultiValueProviderElement.attributeValue("class"));
Element scriptNameElement = defaultMultiValueProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = defaultMultiValueProviderElement.element("value");
if (valueElement != null) {
List<Node> valueItemNodes = new ArrayList<>();
for (Element valueItemElement: valueElement.elements())
valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateDefaultValueProvider(Element defaultValueProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(defaultValueProviderElement.attributeValue("class"));
Element scriptNameElement = defaultValueProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = defaultValueProviderElement.element("value");
if (valueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, valueElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateShowCondition(Element showConditionElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "inputName"),
new ScalarNode(Tag.STR, showConditionElement.elementText("inputName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valueMatcher"),
migrateValueMatcher(showConditionElement.element("valueMatcher"))));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateValueMatcher(Element valueMatcherElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(valueMatcherElement.attributeValue("class"));
Element valuesElement = valueMatcherElement.element("values");
if (valuesElement != null) {
List<Node> valueNodes = new ArrayList<>();
for (Element valueElement: valuesElement.elements())
valueNodes.add(new ScalarNode(Tag.STR, valueElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "values"),
new SequenceNode(Tag.SEQ, valueNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateJob(Element jobElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, jobElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "image"),
new ScalarNode(Tag.STR, jobElement.elementText("image").trim())));
List<Node> commandNodes = new ArrayList<>();
for (Element commandElement: jobElement.element("commands").elements())
commandNodes.add(new ScalarNode(Tag.STR, commandElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "commands"),
new SequenceNode(Tag.SEQ, commandNodes, FlowStyle.BLOCK)));
List<Node> paramSpecNodes = new ArrayList<>();
for (Element paramSpecElement: jobElement.element("paramSpecs").elements())
paramSpecNodes.add(migrateParamSpec(paramSpecElement));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "paramSpecs"),
new SequenceNode(Tag.SEQ, paramSpecNodes, FlowStyle.BLOCK)));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retrieveSource"),
new ScalarNode(Tag.STR, jobElement.elementText("retrieveSource").trim())));
Element cloneDepthElement = jobElement.element("cloneDepth");
if (cloneDepthElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cloneDepth"),
new ScalarNode(Tag.STR, cloneDepthElement.getText().trim())));
}
List<Node> submoduleCredentialNodes = new ArrayList<>();
for (Element submoduleCredentialElement: jobElement.element("submoduleCredentials").elements()) {
List<NodeTuple> submoduleCredentialTuples = new ArrayList<>();
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "url"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("url").trim())));
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "userName"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("userName").trim())));
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "passwordSecret"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("passwordSecret").trim())));
submoduleCredentialNodes.add(new MappingNode(Tag.MAP, submoduleCredentialTuples, FlowStyle.BLOCK));
}
if (!submoduleCredentialNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "submoduleCredentials"),
new SequenceNode(Tag.SEQ, submoduleCredentialNodes, FlowStyle.BLOCK)));
}
List<Node> jobDependencyNodes = new ArrayList<>();
for (Element jobDependencyElement: jobElement.element("jobDependencies").elements())
jobDependencyNodes.add(migrateJobDependency(jobDependencyElement));
if (!jobDependencyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobDependencies"),
new SequenceNode(Tag.SEQ, jobDependencyNodes, FlowStyle.BLOCK)));
}
List<Node> projectDependencyNodes = new ArrayList<>();
for (Element projectDependencyElement: jobElement.element("projectDependencies").elements())
projectDependencyNodes.add(migrateProjectDependency(projectDependencyElement));
if (!projectDependencyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "projectDependencies"),
new SequenceNode(Tag.SEQ, projectDependencyNodes, FlowStyle.BLOCK)));
}
List<Node> serviceNodes = new ArrayList<>();
for (Element serviceElement: jobElement.element("services").elements())
serviceNodes.add(migrateService(serviceElement));
if (!serviceNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "services"),
new SequenceNode(Tag.SEQ, serviceNodes, FlowStyle.BLOCK)));
}
Element artifactsElement = jobElement.element("artifacts");
if (artifactsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, artifactsElement.getText().trim())));
}
List<Node> reportNodes = new ArrayList<>();
for (Element reportElement: jobElement.element("reports").elements())
reportNodes.add(migrateReport(reportElement));
if (!reportNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "reports"),
new SequenceNode(Tag.SEQ, reportNodes, FlowStyle.BLOCK)));
}
List<Node> triggerNodes = new ArrayList<>();
for (Element triggerElement: jobElement.element("triggers").elements())
triggerNodes.add(migrateTrigger(triggerElement));
if (!triggerNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "triggers"),
new SequenceNode(Tag.SEQ, triggerNodes, FlowStyle.BLOCK)));
}
List<Node> cacheNodes = new ArrayList<>();
for (Element cacheElement: jobElement.element("caches").elements())
cacheNodes.add(migrateCache(cacheElement));
if (!cacheNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "caches"),
new SequenceNode(Tag.SEQ, cacheNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cpuRequirement"),
new ScalarNode(Tag.STR, jobElement.elementText("cpuRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "memoryRequirement"),
new ScalarNode(Tag.STR, jobElement.elementText("memoryRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "timeout"),
new ScalarNode(Tag.STR, jobElement.elementText("timeout").trim())));
List<Node> postBuildActionNodes = new ArrayList<>();
for (Element postBuildActionElement: jobElement.element("postBuildActions").elements())
postBuildActionNodes.add(migratePostBuildAction(postBuildActionElement));
if (!postBuildActionNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "postBuildActions"),
new SequenceNode(Tag.SEQ, postBuildActionNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retryCondition"),
new ScalarNode(Tag.STR, jobElement.elementText("retryCondition").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "maxRetries"),
new ScalarNode(Tag.STR, jobElement.elementText("maxRetries").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retryDelay"),
new ScalarNode(Tag.STR, jobElement.elementText("retryDelay").trim())));
Element defaultFixedIssuesFilterElement = jobElement.element("defaultFixedIssuesFilter");
if (defaultFixedIssuesFilterElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultFixedIssuesFilter"),
new ScalarNode(Tag.STR, defaultFixedIssuesFilterElement.getText().trim())));
}
MappingNode jobNode = new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
return jobNode;
}
private static Node migratePostBuildAction(Element postBuildActionElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(postBuildActionElement.getName());
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "condition"),
new ScalarNode(Tag.STR, postBuildActionElement.elementText("condition").trim())));
Element milestoneNameElement = postBuildActionElement.element("milestoneName");
if (milestoneNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "milestoneName"),
new ScalarNode(Tag.STR, milestoneNameElement.getText().trim())));
}
Element issueTitleElement = postBuildActionElement.element("issueTitle");
if (issueTitleElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueTitle"),
new ScalarNode(Tag.STR, issueTitleElement.getText().trim())));
}
Element issueDescriptionElement = postBuildActionElement.element("issueDescription");
if (issueDescriptionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueDescription"),
new ScalarNode(Tag.STR, issueDescriptionElement.getText().trim())));
}
Element issueFieldsElement = postBuildActionElement.element("issueFields");
if (issueFieldsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueFields"),
new SequenceNode(Tag.SEQ, migrateFieldSupplies(issueFieldsElement.elements()), FlowStyle.BLOCK)));
}
Element tagNameElement = postBuildActionElement.element("tagName");
if (tagNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tagName"),
new ScalarNode(Tag.STR, tagNameElement.getText().trim())));
}
Element tagMessageElement = postBuildActionElement.element("tagMessage");
if (tagMessageElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tagMessage"),
new ScalarNode(Tag.STR, tagMessageElement.getText().trim())));
}
Element jobNameElement = postBuildActionElement.element("jobName");
if (jobNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobName"),
new ScalarNode(Tag.STR, jobNameElement.getText().trim())));
}
Element jobParamsElement = postBuildActionElement.element("jobParams");
if (jobParamsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobParams"),
new SequenceNode(Tag.SEQ, migrateParamSupplies(jobParamsElement.elements()), FlowStyle.BLOCK)));
}
Element receiversElement = postBuildActionElement.element("receivers");
if (receiversElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "receivers"),
new ScalarNode(Tag.STR, receiversElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateCache(Element cacheElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "key"),
new ScalarNode(Tag.STR, cacheElement.elementText("key").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "path"),
new ScalarNode(Tag.STR, cacheElement.elementText("path").trim())));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateTrigger(Element triggerElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(triggerElement.getName());
List<Node> paramSupplyNodes = migrateParamSupplies(triggerElement.element("params").elements());
if (!paramSupplyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "params"),
new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
}
Element branchesElement = triggerElement.element("branches");
if (branchesElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "branches"),
new ScalarNode(Tag.STR, branchesElement.getText().trim())));
}
Element pathsElement = triggerElement.element("paths");
if (pathsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "paths"),
new ScalarNode(Tag.STR, pathsElement.getText().trim())));
}
Element tagsElement = triggerElement.element("tags");
if (tagsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tags"),
new ScalarNode(Tag.STR, tagsElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateReport(Element reportElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(reportElement.getName());
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "filePatterns"),
new ScalarNode(Tag.STR, reportElement.elementText("filePatterns").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "reportName"),
new ScalarNode(Tag.STR, reportElement.elementText("reportName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "startPage"),
new ScalarNode(Tag.STR, reportElement.elementText("startPage").trim())));
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateService(Element serviceElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, serviceElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "image"),
new ScalarNode(Tag.STR, serviceElement.elementText("image").trim())));
Element argumentsElement = serviceElement.element("arguments");
if (argumentsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "arguments"),
new ScalarNode(Tag.STR, argumentsElement.getText().trim())));
}
List<Node> envVarNodes = new ArrayList<>();
for (Element envVarElement: serviceElement.element("envVars").elements()) {
List<NodeTuple> envVarTuples = new ArrayList<>();
envVarTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, envVarElement.elementText("name").trim())));
envVarTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, envVarElement.elementText("value").trim())));
envVarNodes.add(new MappingNode(Tag.MAP, envVarTuples, FlowStyle.BLOCK));
}
if (!envVarNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "envVars"),
new SequenceNode(Tag.SEQ, envVarNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "readinessCheckCommand"),
new ScalarNode(Tag.STR, serviceElement.elementText("readinessCheckCommand").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cpuRequirement"),
new ScalarNode(Tag.STR, serviceElement.elementText("cpuRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "memoryRequirement"),
new ScalarNode(Tag.STR, serviceElement.elementText("memoryRequirement").trim())));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateProjectDependency(Element projectDependencyElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "projectName"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("projectName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "buildNumber"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("buildNumber").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("artifacts").trim())));
Element authenticationElement = projectDependencyElement.element("authentication");
if (authenticationElement != null) {
List<NodeTuple> authenticationTuples = new ArrayList<>();
authenticationTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "userName"),
new ScalarNode(Tag.STR, authenticationElement.elementText("userName").trim())));
authenticationTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "passwordSecret"),
new ScalarNode(Tag.STR, authenticationElement.elementText("passwordSecret").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "authentication"),
new MappingNode(Tag.MAP, authenticationTuples, FlowStyle.BLOCK)));
}
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateJobDependency(Element jobDependencyElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobName"),
new ScalarNode(Tag.STR, jobDependencyElement.elementText("jobName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "requireSuccessful"),
new ScalarNode(Tag.STR, jobDependencyElement.elementText("requireSuccessful").trim())));
Element artifactsElement = jobDependencyElement.element("artifacts");
if (artifactsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, artifactsElement.getText().trim())));
}
List<Node> paramSupplyNodes = migrateParamSupplies(jobDependencyElement.element("jobParams").elements());
if (!paramSupplyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobParams"),
new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
}
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static List<Node> migrateParamSupplies(List<Element> paramSupplyElements) {
List<Node> paramSupplyNodes = new ArrayList<>();
for (Element paramSupplyElement: paramSupplyElements) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, paramSupplyElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "secret"),
new ScalarNode(Tag.STR, paramSupplyElement.elementText("secret").trim())));
Element valuesProviderElement = paramSupplyElement.element("valuesProvider");
String classTag = getClassTag(valuesProviderElement.attributeValue("class"));
List<NodeTuple> valuesProviderTuples = new ArrayList<>();
Element scriptNameElement = valuesProviderElement.element("scriptName");
if (scriptNameElement != null) {
valuesProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valuesElement = valuesProviderElement.element("values");
if (valuesElement != null) {
List<Node> listNodes = new ArrayList<>();
for (Element listElement: valuesElement.elements()) {
List<Node> listItemNodes = new ArrayList<>();
for (Element listItemElement: listElement.elements())
listItemNodes.add(new ScalarNode(Tag.STR, listItemElement.getText().trim()));
listNodes.add(new SequenceNode(Tag.SEQ, listItemNodes, FlowStyle.BLOCK));
}
valuesProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "values"),
new SequenceNode(Tag.SEQ, listNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valuesProvider"),
new MappingNode(new Tag(classTag), valuesProviderTuples, FlowStyle.BLOCK)));
paramSupplyNodes.add(new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK));
}
return paramSupplyNodes;
}
private static List<Node> migrateFieldSupplies(List<Element> fieldSupplyElements) {
List<Node> fieldSupplyNodes = new ArrayList<>();
for (Element fieldSupplyElement: fieldSupplyElements) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, fieldSupplyElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "secret"),
new ScalarNode(Tag.STR, fieldSupplyElement.elementText("secret").trim())));
Element valueProviderElement = fieldSupplyElement.element("valueProvider");
String classTag = getClassTag(valueProviderElement.attributeValue("class"));
List<NodeTuple> valueProviderTuples = new ArrayList<>();
Element scriptNameElement = valueProviderElement.element("scriptName");
if (scriptNameElement != null) {
valueProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = valueProviderElement.element("value");
if (valueElement != null) {
List<Node> valueItemNodes = new ArrayList<>();
for (Element valueItemElement: valueElement.elements())
valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
valueProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valueProvider"),
new MappingNode(new Tag(classTag), valueProviderTuples, FlowStyle.BLOCK)));
fieldSupplyNodes.add(new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK));
}
return fieldSupplyNodes;
}
public static String migrate(String xml) {
Document xmlDoc;
try {
xmlDoc = new SAXReader().read(new StringReader(xml));
} catch (DocumentException e) {
throw new RuntimeException(e);
}
List<NodeTuple> tuples = new ArrayList<>();
Node keyNode = new ScalarNode(Tag.STR, "version");
Node valueNode = new ScalarNode(Tag.INT, "0");
tuples.add(new NodeTuple(keyNode, valueNode));
List<Node> jobNodes = new ArrayList<>();
for (Element jobElement: xmlDoc.getRootElement().element("jobs").elements())
jobNodes.add(migrateJob(jobElement));
if (!jobNodes.isEmpty()) {
keyNode = new ScalarNode(Tag.STR, "jobs");
tuples.add(new NodeTuple(keyNode, new SequenceNode(Tag.SEQ, jobNodes, FlowStyle.BLOCK)));
}
List<Node> propertyNodes = new ArrayList<>();
Element propertiesElement = xmlDoc.getRootElement().element("properties");
if (propertiesElement != null) {
for (Element propertyElement: propertiesElement.elements()) {
Node nameNode = new ScalarNode(Tag.STR, propertyElement.elementText("name").trim());
valueNode = new ScalarNode(Tag.STR, propertyElement.elementText("value").trim());
List<NodeTuple> propertyTuples = Lists.newArrayList(
new NodeTuple(new ScalarNode(Tag.STR, "name"), nameNode),
new NodeTuple(new ScalarNode(Tag.STR, "value"), valueNode));
propertyNodes.add(new MappingNode(Tag.MAP, propertyTuples, FlowStyle.BLOCK));
}
}
if(!propertyNodes.isEmpty()) {
keyNode = new ScalarNode(Tag.STR, "properties");
tuples.add(new NodeTuple(keyNode, new SequenceNode(Tag.SEQ, propertyNodes, FlowStyle.BLOCK)));
}
MappingNode rootNode = new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
StringWriter writer = new StringWriter();
DumperOptions dumperOptions = new DumperOptions();
Serializer serializer = new Serializer(new Emitter(writer, dumperOptions),
new Resolver(), dumperOptions, Tag.MAP);
try {
serializer.open();
serializer.serialize(rootNode);
serializer.close();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-538/java/bad_1900_0
|
crossvul-java_data_good_1900_0
|
package io.onedev.server.migration;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.emitter.Emitter;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.resolver.Resolver;
import org.yaml.snakeyaml.serializer.Serializer;
import com.google.common.collect.Lists;
import io.onedev.commons.utils.StringUtils;
public class XmlBuildSpecMigrator {
private static Node migrateParamSpec(Element paramSpecElement) {
String classTag = getClassTag(paramSpecElement.getName());
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "allowEmpty"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("allowEmpty").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "allowMultiple"),
new ScalarNode(Tag.STR, paramSpecElement.elementText("allowMultiple").trim())));
Element patternElement = paramSpecElement.element("pattern");
if (patternElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "pattern"),
new ScalarNode(Tag.STR, patternElement.getText().trim())));
}
Element descriptionElement = paramSpecElement.element("description");
if (descriptionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "description"),
new ScalarNode(Tag.STR, descriptionElement.getText().trim())));
}
Element minValueElement = paramSpecElement.element("minValue");
if (minValueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "minValue"),
new ScalarNode(Tag.STR, minValueElement.getText().trim())));
}
Element maxValueElement = paramSpecElement.element("maxValue");
if (maxValueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "maxValue"),
new ScalarNode(Tag.STR, maxValueElement.getText().trim())));
}
Element showConditionElement = paramSpecElement.element("showCondition");
if (showConditionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "showCondition"),
migrateShowCondition(showConditionElement)));
}
Element defaultValueProviderElement = paramSpecElement.element("defaultValueProvider");
if (defaultValueProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultValueProvider"),
migrateDefaultValueProvider(defaultValueProviderElement)));
}
Element defaultMultiValueProviderElement = paramSpecElement.element("defaultMultiValueProvider");
if (defaultMultiValueProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultMultiValueProvider"),
migrateDefaultMultiValueProvider(defaultMultiValueProviderElement)));
}
Element choiceProviderElement = paramSpecElement.element("choiceProvider");
if (choiceProviderElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "choiceProvider"),
migrateChoiceProvider(choiceProviderElement)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static String getClassTag(String className) {
return "!" + StringUtils.substringAfterLast(className, ".");
}
private static Node migrateChoiceProvider(Element choiceProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(choiceProviderElement.attributeValue("class"));
Element scriptNameElement = choiceProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element choicesElement = choiceProviderElement.element("choices");
if (choicesElement != null) {
List<Node> choiceNodes = new ArrayList<>();
for (Element choiceElement: choicesElement.elements()) {
List<NodeTuple> choiceTuples = new ArrayList<>();
choiceTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, choiceElement.elementText("value").trim())));
choiceTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "color"),
new ScalarNode(Tag.STR, choiceElement.elementText("color").trim())));
choiceNodes.add(new MappingNode(Tag.MAP, choiceTuples, FlowStyle.BLOCK));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "choices"),
new SequenceNode(Tag.SEQ, choiceNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateDefaultMultiValueProvider(Element defaultMultiValueProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(defaultMultiValueProviderElement.attributeValue("class"));
Element scriptNameElement = defaultMultiValueProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = defaultMultiValueProviderElement.element("value");
if (valueElement != null) {
List<Node> valueItemNodes = new ArrayList<>();
for (Element valueItemElement: valueElement.elements())
valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateDefaultValueProvider(Element defaultValueProviderElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(defaultValueProviderElement.attributeValue("class"));
Element scriptNameElement = defaultValueProviderElement.element("scriptName");
if (scriptNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = defaultValueProviderElement.element("value");
if (valueElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, valueElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateShowCondition(Element showConditionElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "inputName"),
new ScalarNode(Tag.STR, showConditionElement.elementText("inputName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valueMatcher"),
migrateValueMatcher(showConditionElement.element("valueMatcher"))));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateValueMatcher(Element valueMatcherElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(valueMatcherElement.attributeValue("class"));
Element valuesElement = valueMatcherElement.element("values");
if (valuesElement != null) {
List<Node> valueNodes = new ArrayList<>();
for (Element valueElement: valuesElement.elements())
valueNodes.add(new ScalarNode(Tag.STR, valueElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "values"),
new SequenceNode(Tag.SEQ, valueNodes, FlowStyle.BLOCK)));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateJob(Element jobElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, jobElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "image"),
new ScalarNode(Tag.STR, jobElement.elementText("image").trim())));
List<Node> commandNodes = new ArrayList<>();
for (Element commandElement: jobElement.element("commands").elements())
commandNodes.add(new ScalarNode(Tag.STR, commandElement.getText().trim()));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "commands"),
new SequenceNode(Tag.SEQ, commandNodes, FlowStyle.BLOCK)));
List<Node> paramSpecNodes = new ArrayList<>();
for (Element paramSpecElement: jobElement.element("paramSpecs").elements())
paramSpecNodes.add(migrateParamSpec(paramSpecElement));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "paramSpecs"),
new SequenceNode(Tag.SEQ, paramSpecNodes, FlowStyle.BLOCK)));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retrieveSource"),
new ScalarNode(Tag.STR, jobElement.elementText("retrieveSource").trim())));
Element cloneDepthElement = jobElement.element("cloneDepth");
if (cloneDepthElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cloneDepth"),
new ScalarNode(Tag.STR, cloneDepthElement.getText().trim())));
}
List<Node> submoduleCredentialNodes = new ArrayList<>();
for (Element submoduleCredentialElement: jobElement.element("submoduleCredentials").elements()) {
List<NodeTuple> submoduleCredentialTuples = new ArrayList<>();
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "url"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("url").trim())));
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "userName"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("userName").trim())));
submoduleCredentialTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "passwordSecret"),
new ScalarNode(Tag.STR, submoduleCredentialElement.elementText("passwordSecret").trim())));
submoduleCredentialNodes.add(new MappingNode(Tag.MAP, submoduleCredentialTuples, FlowStyle.BLOCK));
}
if (!submoduleCredentialNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "submoduleCredentials"),
new SequenceNode(Tag.SEQ, submoduleCredentialNodes, FlowStyle.BLOCK)));
}
List<Node> jobDependencyNodes = new ArrayList<>();
for (Element jobDependencyElement: jobElement.element("jobDependencies").elements())
jobDependencyNodes.add(migrateJobDependency(jobDependencyElement));
if (!jobDependencyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobDependencies"),
new SequenceNode(Tag.SEQ, jobDependencyNodes, FlowStyle.BLOCK)));
}
List<Node> projectDependencyNodes = new ArrayList<>();
for (Element projectDependencyElement: jobElement.element("projectDependencies").elements())
projectDependencyNodes.add(migrateProjectDependency(projectDependencyElement));
if (!projectDependencyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "projectDependencies"),
new SequenceNode(Tag.SEQ, projectDependencyNodes, FlowStyle.BLOCK)));
}
List<Node> serviceNodes = new ArrayList<>();
for (Element serviceElement: jobElement.element("services").elements())
serviceNodes.add(migrateService(serviceElement));
if (!serviceNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "services"),
new SequenceNode(Tag.SEQ, serviceNodes, FlowStyle.BLOCK)));
}
Element artifactsElement = jobElement.element("artifacts");
if (artifactsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, artifactsElement.getText().trim())));
}
List<Node> reportNodes = new ArrayList<>();
for (Element reportElement: jobElement.element("reports").elements())
reportNodes.add(migrateReport(reportElement));
if (!reportNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "reports"),
new SequenceNode(Tag.SEQ, reportNodes, FlowStyle.BLOCK)));
}
List<Node> triggerNodes = new ArrayList<>();
for (Element triggerElement: jobElement.element("triggers").elements())
triggerNodes.add(migrateTrigger(triggerElement));
if (!triggerNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "triggers"),
new SequenceNode(Tag.SEQ, triggerNodes, FlowStyle.BLOCK)));
}
List<Node> cacheNodes = new ArrayList<>();
for (Element cacheElement: jobElement.element("caches").elements())
cacheNodes.add(migrateCache(cacheElement));
if (!cacheNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "caches"),
new SequenceNode(Tag.SEQ, cacheNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cpuRequirement"),
new ScalarNode(Tag.STR, jobElement.elementText("cpuRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "memoryRequirement"),
new ScalarNode(Tag.STR, jobElement.elementText("memoryRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "timeout"),
new ScalarNode(Tag.STR, jobElement.elementText("timeout").trim())));
List<Node> postBuildActionNodes = new ArrayList<>();
for (Element postBuildActionElement: jobElement.element("postBuildActions").elements())
postBuildActionNodes.add(migratePostBuildAction(postBuildActionElement));
if (!postBuildActionNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "postBuildActions"),
new SequenceNode(Tag.SEQ, postBuildActionNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retryCondition"),
new ScalarNode(Tag.STR, jobElement.elementText("retryCondition").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "maxRetries"),
new ScalarNode(Tag.STR, jobElement.elementText("maxRetries").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "retryDelay"),
new ScalarNode(Tag.STR, jobElement.elementText("retryDelay").trim())));
Element defaultFixedIssuesFilterElement = jobElement.element("defaultFixedIssuesFilter");
if (defaultFixedIssuesFilterElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "defaultFixedIssuesFilter"),
new ScalarNode(Tag.STR, defaultFixedIssuesFilterElement.getText().trim())));
}
MappingNode jobNode = new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
return jobNode;
}
private static Node migratePostBuildAction(Element postBuildActionElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(postBuildActionElement.getName());
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "condition"),
new ScalarNode(Tag.STR, postBuildActionElement.elementText("condition").trim())));
Element milestoneNameElement = postBuildActionElement.element("milestoneName");
if (milestoneNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "milestoneName"),
new ScalarNode(Tag.STR, milestoneNameElement.getText().trim())));
}
Element issueTitleElement = postBuildActionElement.element("issueTitle");
if (issueTitleElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueTitle"),
new ScalarNode(Tag.STR, issueTitleElement.getText().trim())));
}
Element issueDescriptionElement = postBuildActionElement.element("issueDescription");
if (issueDescriptionElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueDescription"),
new ScalarNode(Tag.STR, issueDescriptionElement.getText().trim())));
}
Element issueFieldsElement = postBuildActionElement.element("issueFields");
if (issueFieldsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "issueFields"),
new SequenceNode(Tag.SEQ, migrateFieldSupplies(issueFieldsElement.elements()), FlowStyle.BLOCK)));
}
Element tagNameElement = postBuildActionElement.element("tagName");
if (tagNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tagName"),
new ScalarNode(Tag.STR, tagNameElement.getText().trim())));
}
Element tagMessageElement = postBuildActionElement.element("tagMessage");
if (tagMessageElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tagMessage"),
new ScalarNode(Tag.STR, tagMessageElement.getText().trim())));
}
Element jobNameElement = postBuildActionElement.element("jobName");
if (jobNameElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobName"),
new ScalarNode(Tag.STR, jobNameElement.getText().trim())));
}
Element jobParamsElement = postBuildActionElement.element("jobParams");
if (jobParamsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobParams"),
new SequenceNode(Tag.SEQ, migrateParamSupplies(jobParamsElement.elements()), FlowStyle.BLOCK)));
}
Element receiversElement = postBuildActionElement.element("receivers");
if (receiversElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "receivers"),
new ScalarNode(Tag.STR, receiversElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateCache(Element cacheElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "key"),
new ScalarNode(Tag.STR, cacheElement.elementText("key").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "path"),
new ScalarNode(Tag.STR, cacheElement.elementText("path").trim())));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateTrigger(Element triggerElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(triggerElement.getName());
List<Node> paramSupplyNodes = migrateParamSupplies(triggerElement.element("params").elements());
if (!paramSupplyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "params"),
new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
}
Element branchesElement = triggerElement.element("branches");
if (branchesElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "branches"),
new ScalarNode(Tag.STR, branchesElement.getText().trim())));
}
Element pathsElement = triggerElement.element("paths");
if (pathsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "paths"),
new ScalarNode(Tag.STR, pathsElement.getText().trim())));
}
Element tagsElement = triggerElement.element("tags");
if (tagsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "tags"),
new ScalarNode(Tag.STR, tagsElement.getText().trim())));
}
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateReport(Element reportElement) {
List<NodeTuple> tuples = new ArrayList<>();
String classTag = getClassTag(reportElement.getName());
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "filePatterns"),
new ScalarNode(Tag.STR, reportElement.elementText("filePatterns").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "reportName"),
new ScalarNode(Tag.STR, reportElement.elementText("reportName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "startPage"),
new ScalarNode(Tag.STR, reportElement.elementText("startPage").trim())));
return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
private static Node migrateService(Element serviceElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, serviceElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "image"),
new ScalarNode(Tag.STR, serviceElement.elementText("image").trim())));
Element argumentsElement = serviceElement.element("arguments");
if (argumentsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "arguments"),
new ScalarNode(Tag.STR, argumentsElement.getText().trim())));
}
List<Node> envVarNodes = new ArrayList<>();
for (Element envVarElement: serviceElement.element("envVars").elements()) {
List<NodeTuple> envVarTuples = new ArrayList<>();
envVarTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, envVarElement.elementText("name").trim())));
envVarTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new ScalarNode(Tag.STR, envVarElement.elementText("value").trim())));
envVarNodes.add(new MappingNode(Tag.MAP, envVarTuples, FlowStyle.BLOCK));
}
if (!envVarNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "envVars"),
new SequenceNode(Tag.SEQ, envVarNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "readinessCheckCommand"),
new ScalarNode(Tag.STR, serviceElement.elementText("readinessCheckCommand").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "cpuRequirement"),
new ScalarNode(Tag.STR, serviceElement.elementText("cpuRequirement").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "memoryRequirement"),
new ScalarNode(Tag.STR, serviceElement.elementText("memoryRequirement").trim())));
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateProjectDependency(Element projectDependencyElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "projectName"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("projectName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "buildNumber"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("buildNumber").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, projectDependencyElement.elementText("artifacts").trim())));
Element authenticationElement = projectDependencyElement.element("authentication");
if (authenticationElement != null) {
List<NodeTuple> authenticationTuples = new ArrayList<>();
authenticationTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "userName"),
new ScalarNode(Tag.STR, authenticationElement.elementText("userName").trim())));
authenticationTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "passwordSecret"),
new ScalarNode(Tag.STR, authenticationElement.elementText("passwordSecret").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "authentication"),
new MappingNode(Tag.MAP, authenticationTuples, FlowStyle.BLOCK)));
}
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static Node migrateJobDependency(Element jobDependencyElement) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobName"),
new ScalarNode(Tag.STR, jobDependencyElement.elementText("jobName").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "requireSuccessful"),
new ScalarNode(Tag.STR, jobDependencyElement.elementText("requireSuccessful").trim())));
Element artifactsElement = jobDependencyElement.element("artifacts");
if (artifactsElement != null) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "artifacts"),
new ScalarNode(Tag.STR, artifactsElement.getText().trim())));
}
List<Node> paramSupplyNodes = migrateParamSupplies(jobDependencyElement.element("jobParams").elements());
if (!paramSupplyNodes.isEmpty()) {
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "jobParams"),
new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
}
return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
private static List<Node> migrateParamSupplies(List<Element> paramSupplyElements) {
List<Node> paramSupplyNodes = new ArrayList<>();
for (Element paramSupplyElement: paramSupplyElements) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, paramSupplyElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "secret"),
new ScalarNode(Tag.STR, paramSupplyElement.elementText("secret").trim())));
Element valuesProviderElement = paramSupplyElement.element("valuesProvider");
String classTag = getClassTag(valuesProviderElement.attributeValue("class"));
List<NodeTuple> valuesProviderTuples = new ArrayList<>();
Element scriptNameElement = valuesProviderElement.element("scriptName");
if (scriptNameElement != null) {
valuesProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valuesElement = valuesProviderElement.element("values");
if (valuesElement != null) {
List<Node> listNodes = new ArrayList<>();
for (Element listElement: valuesElement.elements()) {
List<Node> listItemNodes = new ArrayList<>();
for (Element listItemElement: listElement.elements())
listItemNodes.add(new ScalarNode(Tag.STR, listItemElement.getText().trim()));
listNodes.add(new SequenceNode(Tag.SEQ, listItemNodes, FlowStyle.BLOCK));
}
valuesProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "values"),
new SequenceNode(Tag.SEQ, listNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valuesProvider"),
new MappingNode(new Tag(classTag), valuesProviderTuples, FlowStyle.BLOCK)));
paramSupplyNodes.add(new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK));
}
return paramSupplyNodes;
}
private static List<Node> migrateFieldSupplies(List<Element> fieldSupplyElements) {
List<Node> fieldSupplyNodes = new ArrayList<>();
for (Element fieldSupplyElement: fieldSupplyElements) {
List<NodeTuple> tuples = new ArrayList<>();
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "name"),
new ScalarNode(Tag.STR, fieldSupplyElement.elementText("name").trim())));
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "secret"),
new ScalarNode(Tag.STR, fieldSupplyElement.elementText("secret").trim())));
Element valueProviderElement = fieldSupplyElement.element("valueProvider");
String classTag = getClassTag(valueProviderElement.attributeValue("class"));
List<NodeTuple> valueProviderTuples = new ArrayList<>();
Element scriptNameElement = valueProviderElement.element("scriptName");
if (scriptNameElement != null) {
valueProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "scriptName"),
new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
}
Element valueElement = valueProviderElement.element("value");
if (valueElement != null) {
List<Node> valueItemNodes = new ArrayList<>();
for (Element valueItemElement: valueElement.elements())
valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
valueProviderTuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "value"),
new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
}
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, "valueProvider"),
new MappingNode(new Tag(classTag), valueProviderTuples, FlowStyle.BLOCK)));
fieldSupplyNodes.add(new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK));
}
return fieldSupplyNodes;
}
public static String migrate(String xml) {
Document xmlDoc;
try {
SAXReader reader = new SAXReader();
// Prevent XXE attack as the xml might be provided by malicious users
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
xmlDoc = reader.read(new StringReader(xml));
} catch (DocumentException | SAXException e) {
throw new RuntimeException(e);
}
List<NodeTuple> tuples = new ArrayList<>();
Node keyNode = new ScalarNode(Tag.STR, "version");
Node valueNode = new ScalarNode(Tag.INT, "0");
tuples.add(new NodeTuple(keyNode, valueNode));
List<Node> jobNodes = new ArrayList<>();
for (Element jobElement: xmlDoc.getRootElement().element("jobs").elements())
jobNodes.add(migrateJob(jobElement));
if (!jobNodes.isEmpty()) {
keyNode = new ScalarNode(Tag.STR, "jobs");
tuples.add(new NodeTuple(keyNode, new SequenceNode(Tag.SEQ, jobNodes, FlowStyle.BLOCK)));
}
List<Node> propertyNodes = new ArrayList<>();
Element propertiesElement = xmlDoc.getRootElement().element("properties");
if (propertiesElement != null) {
for (Element propertyElement: propertiesElement.elements()) {
Node nameNode = new ScalarNode(Tag.STR, propertyElement.elementText("name").trim());
valueNode = new ScalarNode(Tag.STR, propertyElement.elementText("value").trim());
List<NodeTuple> propertyTuples = Lists.newArrayList(
new NodeTuple(new ScalarNode(Tag.STR, "name"), nameNode),
new NodeTuple(new ScalarNode(Tag.STR, "value"), valueNode));
propertyNodes.add(new MappingNode(Tag.MAP, propertyTuples, FlowStyle.BLOCK));
}
}
if(!propertyNodes.isEmpty()) {
keyNode = new ScalarNode(Tag.STR, "properties");
tuples.add(new NodeTuple(keyNode, new SequenceNode(Tag.SEQ, propertyNodes, FlowStyle.BLOCK)));
}
MappingNode rootNode = new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
StringWriter writer = new StringWriter();
DumperOptions dumperOptions = new DumperOptions();
Serializer serializer = new Serializer(new Emitter(writer, dumperOptions),
new Resolver(), dumperOptions, Tag.MAP);
try {
serializer.open();
serializer.serialize(rootNode);
serializer.close();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-538/java/good_1900_0
|
crossvul-java_data_good_1929_0
|
/*
* Copyright 2018 - 2020 Anton Tananaev (anton@traccar.org)
*
* Licensed 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.traccar;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.Winsvc;
import com.sun.jna.platform.win32.Winsvc.HandlerEx;
import com.sun.jna.platform.win32.Winsvc.SC_HANDLE;
import com.sun.jna.platform.win32.Winsvc.SERVICE_DESCRIPTION;
import com.sun.jna.platform.win32.Winsvc.SERVICE_MAIN_FUNCTION;
import com.sun.jna.platform.win32.Winsvc.SERVICE_STATUS;
import com.sun.jna.platform.win32.Winsvc.SERVICE_STATUS_HANDLE;
import com.sun.jna.platform.win32.Winsvc.SERVICE_TABLE_ENTRY;
import jnr.posix.POSIXFactory;
import java.io.File;
import java.net.URISyntaxException;
public abstract class WindowsService {
private static final Advapi32 ADVAPI_32 = Advapi32.INSTANCE;
private final Object waitObject = new Object();
private final String serviceName;
private SERVICE_STATUS_HANDLE serviceStatusHandle;
public WindowsService(String serviceName) {
this.serviceName = serviceName;
}
public void install(
String displayName, String description, String[] dependencies,
String account, String password, String config) throws URISyntaxException {
String javaHome = System.getProperty("java.home");
String javaBinary = "\"" + javaHome + "\\bin\\java.exe\"";
File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI());
String command = javaBinary
+ " -Duser.dir=\"" + jar.getParentFile().getAbsolutePath() + "\""
+ " -jar \"" + jar.getAbsolutePath() + "\""
+ " --service \"" + config + "\"";
StringBuilder dep = new StringBuilder();
if (dependencies != null) {
for (String s : dependencies) {
dep.append(s);
dep.append("\0");
}
}
dep.append("\0");
SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION();
desc.lpDescription = description;
SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName,
Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START,
WinNT.SERVICE_ERROR_NORMAL,
command,
null, null, dep.toString(), account, password);
if (service != null) {
ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
}
public void uninstall() {
SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, Winsvc.SERVICE_ALL_ACCESS);
if (service != null) {
ADVAPI_32.DeleteService(service);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
}
public boolean start() {
boolean success = false;
SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE);
if (service != null) {
success = ADVAPI_32.StartService(service, 0, null);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
return success;
}
public boolean stop() {
boolean success = false;
SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE);
if (serviceManager != null) {
SC_HANDLE service = Advapi32.INSTANCE.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE);
if (service != null) {
SERVICE_STATUS serviceStatus = new SERVICE_STATUS();
success = Advapi32.INSTANCE.ControlService(service, Winsvc.SERVICE_CONTROL_STOP, serviceStatus);
Advapi32.INSTANCE.CloseServiceHandle(service);
}
Advapi32.INSTANCE.CloseServiceHandle(serviceManager);
}
return success;
}
public void init() throws URISyntaxException {
String path = new File(
WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
POSIXFactory.getPOSIX().chdir(path);
ServiceMain serviceMain = new ServiceMain();
SERVICE_TABLE_ENTRY entry = new SERVICE_TABLE_ENTRY();
entry.lpServiceName = serviceName;
entry.lpServiceProc = serviceMain;
Advapi32.INSTANCE.StartServiceCtrlDispatcher((SERVICE_TABLE_ENTRY[]) entry.toArray(2));
}
private SC_HANDLE openServiceControlManager(String machine, int access) {
return ADVAPI_32.OpenSCManager(machine, null, access);
}
private void reportStatus(int status, int win32ExitCode, int waitHint) {
SERVICE_STATUS serviceStatus = new SERVICE_STATUS();
serviceStatus.dwServiceType = WinNT.SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwControlsAccepted = Winsvc.SERVICE_ACCEPT_STOP | Winsvc.SERVICE_ACCEPT_SHUTDOWN;
serviceStatus.dwWin32ExitCode = win32ExitCode;
serviceStatus.dwWaitHint = waitHint;
serviceStatus.dwCurrentState = status;
ADVAPI_32.SetServiceStatus(serviceStatusHandle, serviceStatus);
}
public abstract void run();
private class ServiceMain implements SERVICE_MAIN_FUNCTION {
public void callback(int dwArgc, Pointer lpszArgv) {
ServiceControl serviceControl = new ServiceControl();
serviceStatusHandle = ADVAPI_32.RegisterServiceCtrlHandlerEx(serviceName, serviceControl, null);
reportStatus(Winsvc.SERVICE_START_PENDING, WinError.NO_ERROR, 3000);
reportStatus(Winsvc.SERVICE_RUNNING, WinError.NO_ERROR, 0);
Thread.currentThread().setContextClassLoader(WindowsService.class.getClassLoader());
run();
try {
synchronized (waitObject) {
waitObject.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
reportStatus(Winsvc.SERVICE_STOPPED, WinError.NO_ERROR, 0);
// Avoid returning from ServiceMain, which will cause a crash
// See http://support.microsoft.com/kb/201349, which recommends
// having init() wait for this thread.
// Waiting on this thread in init() won't fix the crash, though.
System.exit(0);
}
}
private class ServiceControl implements HandlerEx {
public int callback(int dwControl, int dwEventType, Pointer lpEventData, Pointer lpContext) {
switch (dwControl) {
case Winsvc.SERVICE_CONTROL_STOP:
case Winsvc.SERVICE_CONTROL_SHUTDOWN:
reportStatus(Winsvc.SERVICE_STOP_PENDING, WinError.NO_ERROR, 5000);
synchronized (waitObject) {
waitObject.notifyAll();
}
break;
default:
break;
}
return WinError.NO_ERROR;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-428/java/good_1929_0
|
crossvul-java_data_bad_1929_0
|
/*
* Copyright 2018 Anton Tananaev (anton@traccar.org)
*
* Licensed 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.traccar;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.Winsvc;
import com.sun.jna.platform.win32.Winsvc.HandlerEx;
import com.sun.jna.platform.win32.Winsvc.SC_HANDLE;
import com.sun.jna.platform.win32.Winsvc.SERVICE_DESCRIPTION;
import com.sun.jna.platform.win32.Winsvc.SERVICE_MAIN_FUNCTION;
import com.sun.jna.platform.win32.Winsvc.SERVICE_STATUS;
import com.sun.jna.platform.win32.Winsvc.SERVICE_STATUS_HANDLE;
import com.sun.jna.platform.win32.Winsvc.SERVICE_TABLE_ENTRY;
import jnr.posix.POSIXFactory;
import java.io.File;
import java.net.URISyntaxException;
public abstract class WindowsService {
private static final Advapi32 ADVAPI_32 = Advapi32.INSTANCE;
private final Object waitObject = new Object();
private final String serviceName;
private SERVICE_STATUS_HANDLE serviceStatusHandle;
public WindowsService(String serviceName) {
this.serviceName = serviceName;
}
public void install(
String displayName, String description, String[] dependencies,
String account, String password, String config) throws URISyntaxException {
String javaHome = System.getProperty("java.home");
String javaBinary = javaHome + "\\bin\\java.exe";
File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI());
String command = javaBinary
+ " -Duser.dir=\"" + jar.getParentFile().getAbsolutePath() + "\""
+ " -jar \"" + jar.getAbsolutePath() + "\""
+ " --service \"" + config + "\"";
StringBuilder dep = new StringBuilder();
if (dependencies != null) {
for (String s : dependencies) {
dep.append(s);
dep.append("\0");
}
}
dep.append("\0");
SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION();
desc.lpDescription = description;
SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName,
Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START,
WinNT.SERVICE_ERROR_NORMAL,
command,
null, null, dep.toString(), account, password);
if (service != null) {
ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
}
public void uninstall() {
SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, Winsvc.SERVICE_ALL_ACCESS);
if (service != null) {
ADVAPI_32.DeleteService(service);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
}
public boolean start() {
boolean success = false;
SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE);
if (service != null) {
success = ADVAPI_32.StartService(service, 0, null);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
return success;
}
public boolean stop() {
boolean success = false;
SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE);
if (serviceManager != null) {
SC_HANDLE service = Advapi32.INSTANCE.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE);
if (service != null) {
SERVICE_STATUS serviceStatus = new SERVICE_STATUS();
success = Advapi32.INSTANCE.ControlService(service, Winsvc.SERVICE_CONTROL_STOP, serviceStatus);
Advapi32.INSTANCE.CloseServiceHandle(service);
}
Advapi32.INSTANCE.CloseServiceHandle(serviceManager);
}
return success;
}
public void init() throws URISyntaxException {
String path = new File(
WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
POSIXFactory.getPOSIX().chdir(path);
ServiceMain serviceMain = new ServiceMain();
SERVICE_TABLE_ENTRY entry = new SERVICE_TABLE_ENTRY();
entry.lpServiceName = serviceName;
entry.lpServiceProc = serviceMain;
Advapi32.INSTANCE.StartServiceCtrlDispatcher((SERVICE_TABLE_ENTRY[]) entry.toArray(2));
}
private SC_HANDLE openServiceControlManager(String machine, int access) {
return ADVAPI_32.OpenSCManager(machine, null, access);
}
private void reportStatus(int status, int win32ExitCode, int waitHint) {
SERVICE_STATUS serviceStatus = new SERVICE_STATUS();
serviceStatus.dwServiceType = WinNT.SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwControlsAccepted = Winsvc.SERVICE_ACCEPT_STOP | Winsvc.SERVICE_ACCEPT_SHUTDOWN;
serviceStatus.dwWin32ExitCode = win32ExitCode;
serviceStatus.dwWaitHint = waitHint;
serviceStatus.dwCurrentState = status;
ADVAPI_32.SetServiceStatus(serviceStatusHandle, serviceStatus);
}
public abstract void run();
private class ServiceMain implements SERVICE_MAIN_FUNCTION {
public void callback(int dwArgc, Pointer lpszArgv) {
ServiceControl serviceControl = new ServiceControl();
serviceStatusHandle = ADVAPI_32.RegisterServiceCtrlHandlerEx(serviceName, serviceControl, null);
reportStatus(Winsvc.SERVICE_START_PENDING, WinError.NO_ERROR, 3000);
reportStatus(Winsvc.SERVICE_RUNNING, WinError.NO_ERROR, 0);
Thread.currentThread().setContextClassLoader(WindowsService.class.getClassLoader());
run();
try {
synchronized (waitObject) {
waitObject.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
reportStatus(Winsvc.SERVICE_STOPPED, WinError.NO_ERROR, 0);
// Avoid returning from ServiceMain, which will cause a crash
// See http://support.microsoft.com/kb/201349, which recommends
// having init() wait for this thread.
// Waiting on this thread in init() won't fix the crash, though.
System.exit(0);
}
}
private class ServiceControl implements HandlerEx {
public int callback(int dwControl, int dwEventType, Pointer lpEventData, Pointer lpContext) {
switch (dwControl) {
case Winsvc.SERVICE_CONTROL_STOP:
case Winsvc.SERVICE_CONTROL_SHUTDOWN:
reportStatus(Winsvc.SERVICE_STOP_PENDING, WinError.NO_ERROR, 5000);
synchronized (waitObject) {
waitObject.notifyAll();
}
break;
default:
break;
}
return WinError.NO_ERROR;
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-428/java/bad_1929_0
|
crossvul-java_data_good_3077_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_4
|
crossvul-java_data_bad_3077_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_4
|
crossvul-java_data_bad_3075_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
return createRoles(target, email, true);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email, boolean createUserGroupByEmail) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
String userGroupLink = null;
// Create user group
if (createUserGroupByEmail) {
userGroupLink = createUserGroup(target, getUserGroupName(email), Builder.create()
.addFieldClause(
"email",
email)
.build());
} else {
String groupName = getUserGroupName(email);
userGroupLink = createUserGroup(target, groupName, Builder.create()
.addFieldClause(
QuerySpecification
.buildCollectionItemName(UserState.FIELD_NAME_USER_GROUP_LINKS),
UriUtils.buildUriPath(UserGroupService.FACTORY_LINK, groupName))
.build());
}
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = new UserGroupState();
userGroupState.documentSelfLink = selfLink;
userGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.documentSelfLink = selfLink;
resourceGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = new RoleState();
roleState.documentSelfLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink);
roleState.userGroupLink = userGroupLink;
roleState.resourceGroupLink = resourceGroupLink;
roleState.verbs = verbs;
roleState.policy = Policy.ALLOW;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_5
|
crossvul-java_data_good_3081_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_5
|
crossvul-java_data_bad_3076_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_2
|
crossvul-java_data_good_3083_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_0
|
crossvul-java_data_bad_3079_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
return createRoles(target, email, true);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email, boolean createUserGroupByEmail) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
String userGroupLink = null;
// Create user group
if (createUserGroupByEmail) {
userGroupLink = createUserGroup(target, getUserGroupName(email), Builder.create()
.addFieldClause(
"email",
email)
.build());
} else {
String groupName = getUserGroupName(email);
userGroupLink = createUserGroup(target, groupName, Builder.create()
.addFieldClause(
QuerySpecification
.buildCollectionItemName(UserState.FIELD_NAME_USER_GROUP_LINKS),
UriUtils.buildUriPath(UserGroupService.FACTORY_LINK, groupName))
.build());
}
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = new UserGroupState();
userGroupState.documentSelfLink = selfLink;
userGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.documentSelfLink = selfLink;
resourceGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = new RoleState();
roleState.documentSelfLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink);
roleState.userGroupLink = userGroupLink;
roleState.resourceGroupLink = resourceGroupLink;
roleState.verbs = verbs;
roleState.policy = Policy.ALLOW;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_5
|
crossvul-java_data_bad_3077_6
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_6
|
crossvul-java_data_good_3077_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_3
|
crossvul-java_data_bad_3079_7
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.services.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.AuthorizationSetupHelper;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.FactoryService;
import com.vmware.xenon.common.NodeSelectorService.SelectAndForwardRequest;
import com.vmware.xenon.common.NodeSelectorService.SelectOwnerResponse;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationJoin;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceHost.HttpScheme;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.StatefulService;
import com.vmware.xenon.common.SynchronizationTaskService;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.RoundRobinIterator;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleTaskService.ExampleTaskServiceState;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupBroadcastResult.PeerNodeResult;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceErrorResponse;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceState;
import com.vmware.xenon.services.common.ResourceGroupService.PatchQueryRequest;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestNodeGroupService {
public static class PeriodicExampleFactoryService extends FactoryService {
public static final String SELF_LINK = "test/examples-periodic";
public PeriodicExampleFactoryService() {
super(ExampleServiceState.class);
}
@Override
public Service createServiceInstance() throws Throwable {
ExampleService s = new ExampleService();
s.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
return s;
}
}
public static class ExampleServiceWithCustomSelector extends StatefulService {
public ExampleServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.REPLICATION, true);
super.toggleOption(ServiceOption.OWNER_SELECTION, true);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ExampleFactoryServiceWithCustomSelector extends FactoryService {
public ExampleFactoryServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.setPeerNodeSelectorPath(CUSTOM_GROUP_NODE_SELECTOR);
}
@Override
public Service createServiceInstance() throws Throwable {
return new ExampleServiceWithCustomSelector();
}
}
private static final String CUSTOM_EXAMPLE_SERVICE_KIND = "xenon:examplestate";
private static final String CUSTOM_NODE_GROUP_NAME = "custom";
private static final String CUSTOM_NODE_GROUP = UriUtils.buildUriPath(
ServiceUriPaths.NODE_GROUP_FACTORY,
CUSTOM_NODE_GROUP_NAME);
private static final String CUSTOM_GROUP_NODE_SELECTOR = UriUtils.buildUriPath(
ServiceUriPaths.NODE_SELECTOR_PREFIX,
CUSTOM_NODE_GROUP_NAME);
public static final long DEFAULT_MAINT_INTERVAL_MICROS = TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
private VerificationHost host;
/**
* Command line argument specifying number of times to run the same test method.
*/
public int testIterationCount = 1;
/**
* Command line argument specifying default number of in process service hosts
*/
public int nodeCount = 3;
/**
* Command line argument specifying request count
*/
public int updateCount = 10;
/**
* Command line argument specifying service instance count
*/
public int serviceCount = 10;
/**
* Command line argument specifying test duration
*/
public long testDurationSeconds;
/**
* Command line argument specifying iterations per test method
*/
public long iterationCount = 1;
/**
* Command line argument used by replication long running tests
*/
public long totalOperationLimit = Long.MAX_VALUE;
private NodeGroupConfig nodeGroupConfig = new NodeGroupConfig();
private EnumSet<ServiceOption> postCreationServiceOptions = EnumSet.noneOf(ServiceOption.class);
private boolean expectFailure;
private long expectedFailureStartTimeMicros;
private List<URI> expectedFailedHosts = new ArrayList<>();
private String replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
private String replicationNodeSelector = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
private long replicationFactor;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
if (!this.host.isRemotePeerTest() &&
!CUSTOM_EXAMPLE_SERVICE_KIND.equals(current.documentKind)) {
return false;
}
return current.name.equals(initial.name);
};
private Function<ExampleServiceState, Void> exampleStateUpdateBodySetter = (
ExampleServiceState state) -> {
state.name = Utils.getNowMicrosUtc() + "";
return null;
};
private boolean isPeerSynchronizationEnabled = true;
private boolean isAuthorizationEnabled = false;
private HttpScheme replicationUriScheme;
private boolean skipAvailabilityChecks = false;
private boolean isMultiLocationTest = false;
private void setUp(int localHostCount) throws Throwable {
if (this.host != null) {
return;
}
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
this.host.setAuthorizationEnabled(this.isAuthorizationEnabled);
VerificationHost.createAndAttachSSLClient(this.host);
if (this.replicationUriScheme == HttpScheme.HTTPS_ONLY) {
// disable HTTP, forcing host.getPublicUri() to return a HTTPS schemed URI. This in
// turn forces the node group to use HTTPS for join, replication, etc
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// the default is disable (-1) so we must set port to 0, to enable SSL and make the
// runtime pick a random HTTPS port
this.host.setSecurePort(0);
}
if (this.testDurationSeconds > 0) {
// for long running tests use the default interval to match production code
this.host.maintenanceIntervalMillis = TimeUnit.MICROSECONDS.toMillis(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
}
this.host.start();
if (this.host.isAuthorizationEnabled()) {
this.host.setSystemAuthorizationContext();
}
CommandLineArgumentParser.parseFromProperties(this.host);
this.host.setStressTest(this.host.isStressTest);
this.host.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
this.host.setMultiLocationTest(this.isMultiLocationTest);
this.host.setUpPeerHosts(localHostCount);
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
setUpPeerHostWithAdditionalServices(h1);
}
// If the peer hosts are remote, then we undo CUSTOM_EXAMPLE_SERVICE_KIND
// from the KINDS cache and use the real documentKind of ExampleService.
if (this.host.isRemotePeerTest()) {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
}
}
private void setUpPeerHostWithAdditionalServices(VerificationHost h1) throws Throwable {
h1.setStressTest(this.host.isStressTest);
h1.waitForServiceAvailable(ExampleService.FACTORY_LINK);
Replication1xExampleFactoryService exampleFactory1x = new Replication1xExampleFactoryService();
h1.startServiceAndWait(exampleFactory1x,
Replication1xExampleFactoryService.SELF_LINK,
null);
Replication3xExampleFactoryService exampleFactory3x = new Replication3xExampleFactoryService();
h1.startServiceAndWait(exampleFactory3x,
Replication3xExampleFactoryService.SELF_LINK,
null);
// start the replication test factory service with OWNER_SELECTION
ReplicationFactoryTestService ownerSelRplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(ownerSelRplFactory,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK,
null);
// start the replication test factory service with STRICT update checking
ReplicationFactoryTestService strictReplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(strictReplFactory,
ReplicationFactoryTestService.STRICT_SELF_LINK, null);
// start the replication test factory service with simple replication, no owner selection
ReplicationFactoryTestService replFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(replFactory,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK, null);
}
private Map<URI, URI> getFactoriesPerNodeGroup(String factoryLink) {
Map<URI, URI> map = this.host.getNodeGroupToFactoryMap(factoryLink);
for (URI h : this.expectedFailedHosts) {
URI e = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
// do not send messages through hosts that will be stopped: this allows all messages to
// end the node group and the succeed or fail based on the test goals. If we let messages
// route through a host that we will abruptly stop, the message might timeout, which is
// OK for the expected failure case when quorum is not met, but will prevent is from confirming
// in the non eager consistency case, that all updates were written to at least one host
map.remove(e);
}
return map;
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
Utils.registerKind(ExampleServiceState.class, CUSTOM_EXAMPLE_SERVICE_KIND);
}
private void setUpOnDemandLoad() throws Throwable {
setUp();
// we need at least 5 nodes, because we're going to stop 2
// nodes and we need majority quorum
this.nodeCount = Math.max(5, this.nodeCount);
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
// create node group, join nodes and set majority quorum
setUp(this.nodeCount);
toggleOnDemandLoad();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.host.getPeerCount() / 2 + 1);
}
private void toggleOnDemandLoad() {
for (URI nodeUri : this.host.getNodeGroupMap().keySet()) {
URI factoryUri = UriUtils.buildUri(nodeUri, ExampleService.FACTORY_LINK);
this.host.toggleServiceOptions(factoryUri, EnumSet.of(ServiceOption.ON_DEMAND_LOAD),
null);
}
}
@After
public void tearDown() throws InterruptedException {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
if (this.host == null) {
return;
}
if (this.host.isRemotePeerTest()) {
try {
this.host.logNodeProcessLogs(this.host.getNodeGroupMap().keySet(),
ServiceUriPaths.PROCESS_LOG);
} catch (Throwable e) {
this.host.log("Failure retrieving process logs: %s", Utils.toString(e));
}
try {
this.host.logNodeManagementState(this.host.getNodeGroupMap().keySet());
} catch (Throwable e) {
this.host.log("Failure retrieving management state: %s", Utils.toString(e));
}
}
this.host.tearDownInProcessPeers();
this.host.toggleNegativeTestMode(false);
this.host.tearDown();
this.host = null;
System.clearProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS);
}
@Test
public void synchronizationCollisionWithPosts() throws Throwable {
// POST requests go through the FactoryService
// and do not get queued with Synchronization
// requests, so if synchronization was running
// while POSTs were happening for the same factory
// service, we could run into collisions. This test
// verifies that xenon handles such collisions and
// POST requests are always successful.
// Join the nodes with full quorum and wait for nodes to
// converge and synchronization to complete.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// Find the owner node for /core/examples. We will
// use it to start on-demand synchronization for
// this factory
URI factoryUri = UriUtils.buildUri(this.host.getPeerHost(), ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(factoryUri, this.replicationNodeSelector);
String taskPath = UriUtils.buildUriPath(
SynchronizationTaskService.FACTORY_LINK,
UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
VerificationHost owner = null;
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
if (peer.isOwner(ExampleService.FACTORY_LINK, ServiceUriPaths.DEFAULT_NODE_SELECTOR)) {
owner = peer;
break;
}
}
this.host.log(Level.INFO, "Owner of synch-task is %s", owner.getId());
// Get the membershipUpdateTimeMicros so that we can
// kick-off the synch-task on-demand.
URI taskUri = UriUtils.buildUri(owner, taskPath);
SynchronizationTaskService.State taskState = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
long membershipUpdateTimeMicros = taskState.membershipUpdateTimeMicros;
// Start posting and in the middle also start
// synchronization. All POSTs should succeed!
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
TestContext ctx = this.host.testCreate((this.serviceCount * 10) + 1);
for (int i = 0; i < this.serviceCount * 10; i++) {
if (i == 5) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK);
task.factorySelfLink = ExampleService.FACTORY_LINK;
task.factoryStateKind = Utils.buildKind(ExampleService.ExampleServiceState.class);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros + 1;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
Operation post = Operation
.createPost(owner, SynchronizationTaskService.FACTORY_LINK)
.setBody(task)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
Operation post = Operation
.createPost(factoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void commandLineJoinRetries() throws Throwable {
this.host = VerificationHost.create(0);
this.host.start();
ExampleServiceHost nodeA = null;
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
this.setUp(1);
try {
// start a node, supplying a bogus peer. Verify we retry, up to expiration which is
// the operation timeout
nodeA = new ExampleServiceHost();
String id = "nodeA-" + VerificationHost.hostNumber.incrementAndGet();
int bogusPort = 1;
String[] args = {
"--port=0",
"--id=" + id,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolderA.getRoot().getAbsolutePath(),
"--peerNodes=" + "http://127.0.0.1:" + bogusPort
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
// verify we see a specific retry stat
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI statsUri = UriUtils.buildStatsUri(nodeGroupUri);
this.host.waitFor("expected stat did not converge", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsUri);
ServiceStat st = stats.entries.get(NodeGroupService.STAT_NAME_JOIN_RETRY_COUNT);
if (st == null || st.latestValue < 1) {
return false;
}
return true;
});
} finally {
if (nodeA != null) {
nodeA.stop();
tmpFolderA.delete();
}
}
}
@Test
public void synchronizationOnDemandLoad() throws Throwable {
// Setup peer nodes
setUp(this.nodeCount);
long intervalMicros = TimeUnit.MILLISECONDS.toMicros(200);
// Start the ODL Factory service on all the peers.
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
// Reduce cache clear delay to short duration
// to cause ODL service stops.
h.setServiceCacheClearDelayMicros(h.getMaintenanceIntervalMicros());
// create an on demand load factory and services
OnDemandLoadFactoryService.create(h);
}
// join the nodes and set full quorum.
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Create a few child-services.
VerificationHost h = this.host.getPeerHost();
Map<URI, ExampleServiceState> childServices = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = UUID.randomUUID().toString();
o.setBody(initialState);
},
UriUtils.buildFactoryUri(h, OnDemandLoadFactoryService.class));
// Verify that each peer host reports the correct value for ODL stop count.
for (VerificationHost vh : this.host.getInProcessHostMap().values()) {
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(vh, this.serviceCount));
}
// Add a new host to the cluster.
VerificationHost newHost = this.host.setUpLocalPeerHost(0, h.getMaintenanceIntervalMicros(),
null);
newHost.setServiceCacheClearDelayMicros(intervalMicros);
OnDemandLoadFactoryService.create(newHost);
this.host.joinNodesAndVerifyConvergence(this.nodeCount + 1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Do GETs on each previously created child services by calling the newly added host.
// This will trigger synchronization for the child services.
this.host.log(Level.INFO, "Verifying synchronization for ODL services");
for (Entry<URI, ExampleServiceState> childService : childServices.entrySet()) {
String childServicePath = childService.getKey().getPath();
ExampleServiceState state = this.host.getServiceState(null,
ExampleServiceState.class, UriUtils.buildUri(newHost, childServicePath));
assertNotNull(state);
}
// Verify that the new peer host reports the correct value for ODL stop count.
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(newHost, this.serviceCount));
}
private boolean checkOdlServiceStopCount(VerificationHost host, int serviceCount)
throws Throwable {
ServiceStat stopCount = host
.getServiceStats(host.getManagementServiceUri())
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
if (stopCount == null || stopCount.latestValue < serviceCount) {
this.host.log(Level.INFO,
"Current stopCount is %s",
(stopCount != null) ? String.valueOf(stopCount.latestValue) : "null");
return false;
}
return true;
}
@Test
public void customNodeGroupWithObservers() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
Logger.getAnonymousLogger().info("Iteration: " + i);
verifyCustomNodeGroupWithObservers();
tearDown();
}
}
private void verifyCustomNodeGroupWithObservers() throws Throwable {
setUp(this.nodeCount);
// on one of the hosts create the custom group but with self as an observer. That peer should
// never receive replicated or broadcast requests
URI observerHostUri = this.host.getPeerHostUri();
ServiceHostState observerHostState = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_MANAGEMENT));
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerHostState.id;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerHostUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
final String customFactoryLink = "custom-factory";
// start a node selector attached to the custom group
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
NodeSelectorState initialState = new NodeSelectorState();
initialState.nodeGroupLink = CUSTOM_NODE_GROUP;
h.startServiceAndWait(new ConsistentHashingNodeSelectorService(),
CUSTOM_GROUP_NODE_SELECTOR, initialState);
// start the factory that is attached to the custom group selector
h.startServiceAndWait(ExampleFactoryServiceWithCustomSelector.class, customFactoryLink);
}
URI customNodeGroupServiceOnObserver = UriUtils
.buildUri(observerHostUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
expectedOptionsPerNode.put(customNodeGroupServiceOnObserver,
observerSelfState.options);
this.host.joinNodesAndVerifyConvergence(CUSTOM_NODE_GROUP, this.nodeCount,
this.nodeCount, expectedOptionsPerNode);
// one of the nodes is observer, so we must set quorum to 2 explicitly
this.host.setNodeGroupQuorum(2, customNodeGroupServiceOnObserver);
this.host.waitForNodeSelectorQuorumConvergence(CUSTOM_GROUP_NODE_SELECTOR, 2);
this.host.waitForNodeGroupIsAvailableConvergence(CUSTOM_NODE_GROUP);
int restartCount = 0;
// verify that the observer node shows up as OBSERVER on all peers, including self
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI customNodeGroupUri = UriUtils.buildUri(hostUri, CUSTOM_NODE_GROUP);
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
customNodeGroupUri);
for (NodeState ns : ngs.nodes.values()) {
if (ns.id.equals(observerHostState.id)) {
assertTrue(ns.options.contains(NodeOption.OBSERVER));
} else {
assertTrue(ns.options.contains(NodeOption.PEER));
}
}
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(customNodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", restartCount, 0);
// join all the nodes through the default group, making sure another group still works
this.host.joinNodesAndVerifyConvergence(this.nodeCount, true);
URI observerFactoryUri = UriUtils.buildUri(observerHostUri, customFactoryLink);
waitForReplicatedFactoryServiceAvailable(observerFactoryUri, CUSTOM_GROUP_NODE_SELECTOR);
// create N services on the custom group, verify none of them got created on the observer.
// We actually post directly to the observer node, which should forward to the other nodes
Map<URI, ExampleServiceState> serviceStatesOnPost = this.host.doFactoryChildServiceStart(
null, this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = Utils.getNowMicrosUtc() + "";
o.setBody(body);
},
observerFactoryUri);
ServiceDocumentQueryResult r = this.host.getFactoryState(observerFactoryUri);
assertEquals(0, r.documentLinks.size());
// do a GET on each service and confirm the owner id is never that of the observer node
Map<URI, ExampleServiceState> serviceStatesFromGet = this.host.getServiceState(
null, ExampleServiceState.class, serviceStatesOnPost.keySet());
for (ExampleServiceState s : serviceStatesFromGet.values()) {
if (observerHostState.id.equals(s.documentOwner)) {
throw new IllegalStateException("Observer node reported state for service");
}
}
// create additional example services which are not associated with the custom node group
// and verify that they are always included in queries which target the custom node group
// (e.g. that the query is never executed on the OBSERVER node).
createExampleServices(observerHostUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI serviceUri = UriUtils.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
URI forwardQueryUri = UriUtils.buildForwardRequestUri(serviceUri, null,
CUSTOM_GROUP_NODE_SELECTOR);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(forwardQueryUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Forwarded query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
}
task.querySpec.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.BROADCAST);
task.nodeSelectorLink = CUSTOM_GROUP_NODE_SELECTOR;
URI queryPostUri = UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_QUERY_TASKS);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(queryPostUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Broadcast query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
URI existingNodeGroup = this.host.getPeerNodeGroupUri();
// start more nodes, insert them to existing group, but with no synchronization required
// start some additional nodes
Collection<VerificationHost> existingHosts = this.host.getInProcessHostMap().values();
int additionalHostCount = this.nodeCount;
this.host.setUpPeerHosts(additionalHostCount);
List<ServiceHost> newHosts = Collections.synchronizedList(new ArrayList<>());
newHosts.addAll(this.host.getInProcessHostMap().values());
newHosts.removeAll(existingHosts);
expectedOptionsPerNode.clear();
// join new nodes with existing node group.
TestContext testContext = this.host.testCreate(newHosts.size());
for (ServiceHost h : newHosts) {
URI newCustomNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
JoinPeerRequest joinBody = JoinPeerRequest.create(existingNodeGroup, null);
joinBody.localNodeOptions = EnumSet.of(NodeOption.PEER);
this.host.send(Operation.createPost(newCustomNodeGroupUri)
.setBody(joinBody)
.setCompletion(testContext.getCompletion()));
expectedOptionsPerNode.put(newCustomNodeGroupUri, joinBody.localNodeOptions);
}
testContext.await();
this.host.waitForNodeGroupConvergence(this.host.getNodeGroupMap().values(),
this.host.getNodeGroupMap().size(),
this.host.getNodeGroupMap().size(),
expectedOptionsPerNode, false);
restartCount = 0;
// do another restart check. None of the new nodes should have reported restarts
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI nodeGroupUri = UriUtils.buildUri(hostUri, ServiceUriPaths.DEFAULT_NODE_GROUP);
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(nodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", 0,
restartCount);
}
@Test
public void verifyGossipForObservers() throws Throwable {
setUp(this.nodeCount);
Iterator<Entry<URI, URI>> nodeGroupIterator = this.host.getNodeGroupMap().entrySet()
.iterator();
URI observerUri = nodeGroupIterator.next().getKey();
String observerId = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerUri, ServiceUriPaths.CORE_MANAGEMENT)).id;
// Create a custom node group. Mark one node as OBSERVER and rest as PEER
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerId;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
// Pick a PEER and join it to each node in the node-group
URI peerUri = nodeGroupIterator.next().getKey();
URI peerCustomUri = UriUtils.buildUri(peerUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
Set<URI> customNodeUris = new HashSet<>();
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI nodeCustomUri = UriUtils.buildUri(nodeUri, CUSTOM_NODE_GROUP);
JoinPeerRequest request = new JoinPeerRequest();
request.memberGroupReference = nodeCustomUri;
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(peerCustomUri)
.setBody(request)
.setReferer(this.host.getReferer())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
ctx.await();
expectedOptionsPerNode.put(nodeCustomUri,
EnumSet.of((nodeUri == observerUri)
? NodeOption.OBSERVER : NodeOption.PEER));
customNodeUris.add(nodeCustomUri);
}
// Verify that gossip will propagate the single OBSERVER and the PEER nodes
// to every node in the custom node-group.
this.host.waitForNodeGroupConvergence(
customNodeUris, this.nodeCount, this.nodeCount, expectedOptionsPerNode, false);
}
@Test
public void synchronizationOneByOneWithAbruptNodeShutdown() throws Throwable {
setUp(this.nodeCount);
this.replicationTargetFactoryLink = PeriodicExampleFactoryService.SELF_LINK;
// start the periodic example service factory on each node
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.startServiceAndWait(PeriodicExampleFactoryService.class,
PeriodicExampleFactoryService.SELF_LINK);
}
// On one host, add some services. They exist only on this host and we expect them to synchronize
// across all hosts once this one joins with the group
VerificationHost initialHost = this.host.getPeerHost();
URI hostUriWithInitialState = initialHost.getUri();
Map<String, ExampleServiceState> exampleStatesPerSelfLink = createExampleServices(
hostUriWithInitialState);
URI hostWithStateNodeGroup = UriUtils.buildUri(hostUriWithInitialState,
ServiceUriPaths.DEFAULT_NODE_GROUP);
// before start joins, verify isolated factory synchronization is done
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
// join a node, with no state, one by one, to the host with state.
// The steps are:
// 1) set quorum to node group size + 1
// 2) Join new empty node with existing node group
// 3) verify convergence of factory state
// 4) repeat
List<URI> joinedHosts = new ArrayList<>();
Map<URI, URI> factories = new HashMap<>();
factories.put(hostWithStateNodeGroup, UriUtils.buildUri(hostWithStateNodeGroup,
this.replicationTargetFactoryLink));
joinedHosts.add(hostWithStateNodeGroup);
int fullQuorum = 1;
for (URI nodeGroupUri : this.host.getNodeGroupMap().values()) {
// skip host with state
if (hostWithStateNodeGroup.equals(nodeGroupUri)) {
continue;
}
this.host.log("Setting quorum to %d, already joined: %d",
fullQuorum + 1, joinedHosts.size());
// set quorum to expected full node group size, for the setup hosts
this.host.setNodeGroupQuorum(++fullQuorum);
this.host.testStart(1);
// join empty node, with node with state
this.host.joinNodeGroup(hostWithStateNodeGroup, nodeGroupUri, fullQuorum);
this.host.testWait();
joinedHosts.add(nodeGroupUri);
factories.put(nodeGroupUri, UriUtils.buildUri(nodeGroupUri,
this.replicationTargetFactoryLink));
this.host.waitForNodeGroupConvergence(joinedHosts, fullQuorum, fullQuorum, true);
this.host.waitForNodeGroupIsAvailableConvergence(nodeGroupUri.getPath(), joinedHosts);
this.waitForReplicatedFactoryChildServiceConvergence(
factories,
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker, exampleStatesPerSelfLink.size(),
0);
// Do updates, which will verify that the services are converged in terms of ownership.
// Since we also synchronize on demand, if there was any discrepancy, after updates, the
// services will converge
doExampleServicePatch(exampleStatesPerSelfLink,
joinedHosts.get(0));
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink, initialHost, joinedHosts, 0, 1,
ownerIds.size() - 1);
}
doNodeStopWithUpdates(exampleStatesPerSelfLink);
}
private void doExampleServicePatch(Map<String, ExampleServiceState> states,
URI nodeGroupOnSomeHost) throws Throwable {
this.host.log("Starting PATCH to %d example services", states.size());
TestContext ctx = this.host
.testCreate(this.updateCount * states.size());
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
for (int i = 0; i < this.updateCount; i++) {
for (Entry<String, ExampleServiceState> e : states.entrySet()) {
ExampleServiceState st = Utils.clone(e.getValue());
st.counter = (long) i;
Operation patch = Operation
.createPatch(UriUtils.buildUri(nodeGroupOnSomeHost, e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
this.host.log("Done with PATCH to %d example services", states.size());
}
public void doNodeStopWithUpdates(Map<String, ExampleServiceState> exampleStatesPerSelfLink)
throws Throwable {
this.host.log("Starting to stop nodes and send updates");
VerificationHost remainingHost = this.host.getPeerHost();
Collection<VerificationHost> hostsToStop = new ArrayList<>(this.host.getInProcessHostMap()
.values());
hostsToStop.remove(remainingHost);
List<URI> targetServices = new ArrayList<>();
for (String link : exampleStatesPerSelfLink.keySet()) {
// build the URIs using the host we plan to keep, so the maps we use below to lookup
// stats from URIs, work before and after node stop
targetServices.add(UriUtils.buildUri(remainingHost, link));
}
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(this.host.getTimeoutSeconds() / 3);
}
// capture current stats from each service
Map<URI, ServiceStats> prevStats = verifyMaintStatsAfterSynchronization(targetServices,
null);
stopHostsAndVerifyQueuing(hostsToStop, remainingHost, targetServices);
// its important to verify document ownership before we do any updates on the services.
// This is because we verify, that even without any on demand synchronization,
// the factory driven synchronization set the services in the proper state
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
List<URI> remainingHosts = new ArrayList<>(this.host.getNodeGroupMap().keySet());
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink,
this.host.getInProcessHostMap().values().iterator().next(),
remainingHosts, 0, 1,
ownerIds.size() - 1);
// confirm maintenance is back up and running on all services
verifyMaintStatsAfterSynchronization(targetServices, prevStats);
// nodes are stopped, do updates again, quorum is relaxed, they should work
doExampleServicePatch(exampleStatesPerSelfLink, remainingHost.getUri());
this.host.log("Done with stop nodes and send updates");
}
private void verifyDynamicMaintOptionToggle(Map<String, ExampleServiceState> childStates) {
List<URI> targetServices = new ArrayList<>();
childStates.keySet().forEach((l) -> targetServices.add(this.host.getPeerServiceUri(l)));
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
Map<URI, ServiceConfiguration> configPerService = this.host.getServiceState(
null, ServiceConfiguration.class, targetServiceConfig);
for (ServiceConfiguration cfg : configPerService.values()) {
assertTrue(!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE));
}
for (URI child : targetServices) {
this.host.toggleServiceOptions(child,
EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE),
null);
}
verifyMaintStatsAfterSynchronization(targetServices, null);
}
private Map<URI, ServiceStats> verifyMaintStatsAfterSynchronization(List<URI> targetServices,
Map<URI, ServiceStats> statsPerService) {
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
if (statsPerService == null) {
statsPerService = new HashMap<>();
}
final Map<URI, ServiceStats> previousStatsPerService = statsPerService;
this.host.waitFor(
"maintenance not enabled",
() -> {
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, targetServiceStats);
for (Entry<URI, ServiceStats> currentEntry : stats.entrySet()) {
ServiceStats previousStats = previousStatsPerService.get(currentEntry
.getKey());
ServiceStats currentStats = currentEntry.getValue();
ServiceStat previousMaintStat = previousStats == null ? new ServiceStat()
: previousStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
double previousValue = previousMaintStat == null ? 0L
: previousMaintStat.latestValue;
ServiceStat maintStat = currentStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null || maintStat.latestValue <= previousValue) {
return false;
}
}
previousStatsPerService.putAll(stats);
return true;
});
return statsPerService;
}
private Map<String, ExampleServiceState> createExampleServices(URI hostUri) throws Throwable {
URI factoryUri = UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink);
this.host.log("POSTing children to %s", hostUri);
// add some services on one of the peers, so we can verify the get synchronized after they all join
Map<URI, ExampleServiceState> exampleStates = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
}, factoryUri);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
for (ExampleServiceState s : exampleStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
return exampleStatesPerSelfLink;
}
@Test
public void synchronizationWithPeerNodeListAndDuplicates()
throws Throwable {
ExampleServiceHost h = null;
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
setUp(this.nodeCount);
// the hosts are started, but not joined. We need to relax the quorum for any updates
// to go through
this.host.setNodeGroupQuorum(1);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
// add the *same* service instance, all *all* peers, so we force synchronization and epoch
// change on an instance that exists everywhere
int dupServiceCount = this.serviceCount;
AtomicInteger counter = new AtomicInteger();
Map<URI, ExampleServiceState> dupStates = new HashMap<>();
for (VerificationHost v : this.host.getInProcessHostMap().values()) {
counter.set(0);
URI factoryUri = UriUtils.buildFactoryUri(v,
ExampleService.class);
dupStates = this.host.doFactoryChildServiceStart(
null,
dupServiceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.documentSelfLink = "duplicateExampleInstance-"
+ counter.incrementAndGet();
s.name = s.documentSelfLink;
o.setBody(s);
}, factoryUri);
}
for (ExampleServiceState s : dupStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
// increment to account for link found on all nodes
this.serviceCount = exampleStatesPerSelfLink.size();
// create peer argument list, all the nodes join.
Collection<URI> peerNodeGroupUris = new ArrayList<>();
StringBuilder peerNodes = new StringBuilder();
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peerNodeGroupUris.add(UriUtils.buildUri(peer, ServiceUriPaths.DEFAULT_NODE_GROUP));
peerNodes.append(peer.getUri().toString()).append(",");
}
CountDownLatch notifications = new CountDownLatch(this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
this.host.subscribeForNodeGroupConvergence(nodeGroup, this.nodeCount + 1,
(o, e) -> {
if (e != null) {
this.host.log("Error in notificaiton: %s", Utils.toString(e));
return;
}
notifications.countDown();
});
}
// now start a new Host and supply the already created peer, then observe the automatic
// join
h = new ExampleServiceHost();
int quorum = this.host.getPeerCount() + 1;
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--port=0",
"--id=" + mainHostId,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + peerNodes.toString()
};
h.initialize(args);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
h.start();
URI mainHostNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
int totalCount = this.nodeCount + 1;
peerNodeGroupUris.add(mainHostNodeGroupUri);
this.host.waitForNodeGroupIsAvailableConvergence();
this.host.waitForNodeGroupConvergence(peerNodeGroupUris, totalCount,
totalCount, true);
this.host.setNodeGroupQuorum(quorum, mainHostNodeGroupUri);
this.host.setNodeGroupQuorum(quorum);
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
int peerNodeCount = h.getInitialPeerHosts().size();
// include self in peers
assertTrue(totalCount >= peerNodeCount + 1);
// Before factory synch is complete, make sure POSTs to existing services fail,
// since they are not marked idempotent.
verifyReplicatedInConflictPost(dupStates);
// now verify all nodes synchronize and see the example service instances that existed on the single
// host
waitForReplicatedFactoryChildServiceConvergence(
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker,
this.serviceCount, 0);
// Send some updates after the full group has formed and verify the updates are seen by services on all nodes
doStateUpdateReplicationTest(Action.PATCH, this.serviceCount, this.updateCount, 0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
exampleStatesPerSelfLink);
URI exampleFactoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(exampleFactoryUri, ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
} finally {
this.host.log("test finished");
if (h != null) {
h.stop();
tmpFolder.delete();
}
}
}
private void verifyReplicatedInConflictPost(Map<URI, ExampleServiceState> dupStates)
throws Throwable {
// Its impossible to guarantee that this runs during factory synch. It might run before,
// it might run during, it might run after. Since we runs 1000s of tests per day, CI
// will let us know if the production code works. Here, we add a small sleep so we increase
// chance we overlap with factory synchronization.
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(
this.host.getPeerHost().getMaintenanceIntervalMicros()));
// Issue a POST for a service we know exists and expect failure, since the example service
// is not marked IDEMPOTENT. We expect CONFLICT error code, but if synchronization is active
// we want to confirm we dont get 500, but the 409 is preserved
TestContext ctx = this.host.testCreate(dupStates.size());
for (ExampleServiceState st : dupStates.values()) {
URI factoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
Operation post = Operation.createPost(factoryUri).setBody(st)
.setCompletion((o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
ctx.failIteration(new IllegalStateException(
"Expected conflict status, got " + o.getStatusCode()));
return;
}
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"Expected failure on duplicate POST"));
});
this.host.send(post);
}
this.host.testWait(ctx);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopOnDemandLoad() throws Throwable {
tearDown();
for (int i = 0; i < this.testIterationCount; i++) {
setUpOnDemandLoad();
int hostStopCount = 2;
doReplicationWithQuorumAfterAbruptNodeStop(hostStopCount);
this.host.log("Done with iteration %d", i);
tearDown();
this.host = null;
}
}
private void doReplicationWithQuorumAfterAbruptNodeStop(int hostStopCount)
throws Throwable {
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop minority number of hosts - quorum is still intact
int i = 0;
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(e.getValue());
if (++i >= hostStopCount) {
break;
}
}
// do some updates with strong quorum enabled
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopMultiLocation()
throws Throwable {
// we need 6 nodes, 3 in each location
this.nodeCount = 6;
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
this.isMultiLocationTest = true;
if (this.host == null) {
// create node group, join nodes and set local majority quorum
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(2);
}
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop hosts in location "L2"
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
VerificationHost h = e.getValue();
if (h.getLocation().equals(VerificationHost.LOCATION2)) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(h);
}
}
// do some updates
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
/**
* This test validates that if a host, joined in a peer node group, stops/fails and another
* host, listening on the same address:port, rejoins, the existing peer members will mark the
* OLD host instance as FAILED, and mark the new instance, with the new ID as HEALTHY
*
* @throws Throwable
*/
@Test
public void nodeRestartWithSameAddressDifferentId() throws Throwable {
int failedNodeCount = 1;
int afterFailureQuorum = this.nodeCount - failedNodeCount;
setUp(this.nodeCount);
setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(5));
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.log("Stopping node");
// relax quorum for convergence check
this.host.setNodeGroupQuorum(afterFailureQuorum);
// we should now have N nodes, that see each other. Stop one of the
// nodes, and verify the other host's node group deletes the entry
List<ServiceHostState> hostStates = stopHostsToSimulateFailure(failedNodeCount);
URI remainingPeerNodeGroup = this.host.getPeerNodeGroupUri();
// wait for convergence of the remaining peers, before restarting. The failed host
// should be marked FAILED, otherwise we will not converge
this.host.waitForNodeGroupConvergence(this.nodeCount - failedNodeCount);
ServiceHostState stoppedHostState = hostStates.get(0);
// start a new HOST, with a new ID, but with the same address:port as the one we stopped
this.host.testStart(1);
VerificationHost newHost = this.host.setUpLocalPeerHost(stoppedHostState.httpPort,
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null);
this.host.testWait();
// re-join the remaining peers
URI newHostNodeGroupService = UriUtils
.buildUri(newHost.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.joinNodeGroup(newHostNodeGroupService, remainingPeerNodeGroup);
this.host.testWait();
// now wait for convergence. If the logic is correct, the old HOST, that listened on the
// same port as the new host, should stay in the FAILED state, but the new host should
// be marked as HEALTHY
this.host.waitForNodeGroupConvergence(this.nodeCount);
}
public void setMaintenanceIntervalMillis(long defaultMaintIntervalMillis) {
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
// set short interval so failure detection and convergence happens quickly
h1.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(defaultMaintIntervalMillis));
}
}
@Test
public void synchronizationRequestQueuing() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
VerificationHost peerHost = this.host.getPeerHost();
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(peerHost, 1, exampleUris, null);
URI instanceUri = exampleUris.get(0);
ExampleServiceState synchState = new ExampleServiceState();
synchState.documentSelfLink = UriUtils.getLastPathSegment(instanceUri);
TestContext ctx = this.host.testCreate(this.updateCount);
for (int i = 0; i < this.updateCount; i++) {
Operation op = Operation.createPost(peerHost, ExampleService.FACTORY_LINK)
.setBody(synchState)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(op);
}
ctx.await();
}
@Test
public void enforceHighQuorumWithNodeConcurrentStop()
throws Throwable {
int hostRestartCount = 2;
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(1);
}
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.host.setNodeGroupQuorum((this.nodeCount + 1) / 2);
// do some replication with strong quorum enabled
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
long now = Utils.getNowMicrosUtc();
validatePerOperationReplicationQuorum(childStates, now);
// expect failure, since we will stop some hosts, break quorum
this.expectFailure = true;
// when quorum is not met the runtime will just queue requests until expiration, so
// we set expiration to something quick. Some requests will make it past queuing
// and will fail because replication quorum is not met
long opTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(500);
setOperationTimeoutMicros(opTimeoutMicros);
int i = 0;
for (URI h : this.host.getInProcessHostMap().keySet()) {
this.expectedFailedHosts.add(h);
if (++i >= hostRestartCount) {
break;
}
}
// stop one host right away
stopHostsToSimulateFailure(1);
// concurrently with the PATCH requests below, stop another host
Runnable r = () -> {
stopHostsToSimulateFailure(hostRestartCount - 1);
// add a small bit of time slop since its feasible a host completed a operation *after* we stopped it,
// the netty handlers are stopped in async (not forced) mode
this.expectedFailureStartTimeMicros = Utils.getNowMicrosUtc()
+ TimeUnit.MILLISECONDS.toMicros(250);
};
this.host.schedule(r, 1, TimeUnit.MILLISECONDS);
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
this.updateCount,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), this.updateCount,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), 1,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
private void validatePerOperationReplicationQuorum(Map<String, ExampleServiceState> childStates,
long now) throws Throwable {
Random r = new Random();
// issue a patch, with per operation quorum set, verify it applied
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(body);
// add an explicit replication count header, using either the "all" value, or an
// explicit node count
if (r.nextBoolean()) {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
} else {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
this.nodeCount + "");
}
this.host.send(patch);
this.host.testWait(ctx);
// Go to each peer, directly to their index, and verify update is present. This is not
// proof the per operation quorum was applied "synchronously", before the response
// was sent, but over many runs, if there is a race or its applied asynchronously,
// we will see failures
for (URI hostBaseUri : this.host.getNodeGroupMap().keySet()) {
URI indexUri = UriUtils.buildUri(hostBaseUri, ServiceUriPaths.CORE_DOCUMENT_INDEX);
indexUri = UriUtils.buildIndexQueryUri(indexUri,
e.getKey(), true, false, ServiceOption.PERSISTENCE);
ExampleServiceState afterState = this.host.getServiceState(null,
ExampleServiceState.class, indexUri);
assertEquals(body.counter, afterState.counter);
}
}
this.host.toggleNegativeTestMode(true);
// verify that if we try to set per operation quorum too high, request will fail
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
(this.nodeCount * 2) + "")
.setCompletion(ctx.getExpectedFailureCompletion())
.setBody(body);
this.host.send(patch);
this.host.testWait(ctx);
break;
}
this.host.toggleNegativeTestMode(false);
}
private void setOperationTimeoutMicros(long opTimeoutMicros) {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setOperationTimeOutMicros(opTimeoutMicros);
}
this.host.setOperationTimeOutMicros(opTimeoutMicros);
}
/**
* This test creates N local service hosts, each with K instances of a replicated service. The
* service will create a query task, also replicated, and self patch itself. The test makes sure
* all K instances, on all N hosts see the self PATCHs AND that the query tasks exist on all
* hosts
*
* @throws Throwable
*/
@Test
public void replicationWithCrossServiceDependencies() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI hostUri = this.host.getPeerServiceUri(null);
URI factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> ownerSelectedServices = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri, ReplicationFactoryTestService.STRICT_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ReplicationTestServiceState.class));
q.query.addBooleanClause(kindClause);
Query nameClause = new Query();
nameClause.setTermPropertyName("stringField")
.setTermMatchValue("*")
.setTermMatchType(MatchType.WILDCARD);
q.query.addBooleanClause(nameClause);
// expect results for strict and regular service instances
int expectedServiceCount = this.serviceCount * 3;
Date exp = this.host.getTestExpiration();
while (exp.after(new Date())) {
// create N direct query tasks. Direct tasks complete in the context of the POST to the
// query task factory
int count = 10;
URI queryFactoryUri = UriUtils.extendUri(hostUri,
ServiceUriPaths.CORE_QUERY_TASKS);
TestContext testContext = this.host.testCreate(count);
Map<String, QueryTask> taskResults = new ConcurrentSkipListMap<>();
for (int i = 0; i < count; i++) {
QueryTask qt = QueryTask.create(q);
qt.taskInfo.isDirect = true;
qt.documentSelfLink = UUID.randomUUID().toString();
Operation startPost = Operation
.createPost(queryFactoryUri)
.setBody(qt)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
qt.results = rsp.results;
qt.documentOwner = rsp.documentOwner;
taskResults.put(rsp.documentSelfLink, qt);
testContext.complete();
});
this.host.send(startPost);
}
testContext.await();
this.host.logThroughput();
boolean converged = true;
for (QueryTask qt : taskResults.values()) {
if (qt.results == null || qt.results.documentLinks == null) {
throw new IllegalStateException("Missing results");
}
if (qt.results.documentLinks.size() != expectedServiceCount) {
this.host.log("%s", Utils.toJsonHtml(qt));
converged = false;
break;
}
}
if (!converged) {
Thread.sleep(250);
continue;
}
break;
}
if (exp.before(new Date())) {
throw new TimeoutException();
}
// Negative tests: Make sure custom error response body is preserved
URI childUri = ownerSelectedServices.keySet().iterator().next();
TestContext testContext = this.host.testCreate(1);
ReplicationTestServiceState badRequestBody = new ReplicationTestServiceState();
this.host
.send(Operation
.createPatch(childUri)
.setBody(badRequestBody)
.setCompletion(
(o, e) -> {
if (e == null) {
testContext.fail(new IllegalStateException(
"Expected failure"));
return;
}
ReplicationTestServiceErrorResponse rsp = o
.getBody(ReplicationTestServiceErrorResponse.class);
if (!ReplicationTestServiceErrorResponse.KIND
.equals(rsp.documentKind)) {
testContext.fail(new IllegalStateException(
"Expected custom response body"));
return;
}
testContext.complete();
}));
testContext.await();
// verify that each owner selected service reports stats from the same node that reports state
Map<URI, ReplicationTestServiceState> latestState = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
Map<String, String> ownerIdPerLink = new HashMap<>();
List<URI> statsUris = new ArrayList<>();
for (ReplicationTestServiceState state : latestState.values()) {
URI statsUri = this.host.getPeerServiceUri(UriUtils.buildUriPath(
state.documentSelfLink, ServiceHost.SERVICE_URI_SUFFIX_STATS));
ownerIdPerLink.put(state.documentSelfLink, state.documentOwner);
statsUris.add(statsUri);
}
Map<URI, ServiceStats> latestStats = this.host.getServiceState(null, ServiceStats.class,
statsUris);
for (ServiceStats perServiceStats : latestStats.values()) {
String serviceLink = UriUtils.getParentPath(perServiceStats.documentSelfLink);
String expectedOwnerId = ownerIdPerLink.get(serviceLink);
if (expectedOwnerId.equals(perServiceStats.documentOwner)) {
continue;
}
throw new IllegalStateException("owner routing issue with stats: "
+ Utils.toJsonHtml(perServiceStats));
}
exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
// verify all factories report same number of children
for (VerificationHost peerHost : this.host.getInProcessHostMap().values()) {
factoryUri = UriUtils.buildUri(peerHost,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
ServiceDocumentQueryResult rsp = this.host.getFactoryState(factoryUri);
if (rsp.documentLinks.size() != latestState.size()) {
this.host.log("Factory %s reporting %d children, expected %d", factoryUri,
rsp.documentLinks.size(), latestState.size());
isConverged = false;
break;
}
}
if (!isConverged) {
Thread.sleep(250);
continue;
}
break;
}
if (new Date().after(exp)) {
throw new TimeoutException("factories did not converge");
}
this.host.log("Inducing synchronization");
// Induce synchronization on stable node group. No changes should be observed since
// all nodes should have identical state
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
// give synchronization a chance to run, its 100% asynchronous so we can't really tell when each
// child is done, but a small delay should be sufficient for 99.9% of test environments, even under
// load
Thread.sleep(2000);
// verify that example states did not change due to the induced synchronization
Map<URI, ReplicationTestServiceState> latestStateAfter = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
for (Entry<URI, ReplicationTestServiceState> afterEntry : latestStateAfter.entrySet()) {
ReplicationTestServiceState beforeState = latestState.get(afterEntry.getKey());
ReplicationTestServiceState afterState = afterEntry.getValue();
assertEquals(beforeState.documentVersion, afterState.documentVersion);
}
verifyOperationJoinAcrossPeers(latestStateAfter);
}
private Map<URI, ReplicationTestServiceState> doReplicatedServiceFactoryPost(int serviceCount,
Consumer<Operation> setBodyCallback, URI factoryUri) throws Throwable,
InterruptedException, TimeoutException {
ServiceDocumentDescription sdd = this.host
.buildDescription(ReplicationTestServiceState.class);
Map<URI, ReplicationTestServiceState> serviceMap = this.host.doFactoryChildServiceStart(
null, serviceCount, ReplicationTestServiceState.class, setBodyCallback, factoryUri);
Date expiration = this.host.getTestExpiration();
boolean isConverged = true;
Map<URI, String> uriToSignature = new HashMap<>();
while (new Date().before(expiration)) {
isConverged = true;
uriToSignature.clear();
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
URI baseUri = e.getKey();
VerificationHost h = e.getValue();
URI u = UriUtils.buildUri(baseUri, factoryUri.getPath());
u = UriUtils.buildExpandLinksQueryUri(u);
ServiceDocumentQueryResult r = this.host.getFactoryState(u);
if (r.documents.size() != serviceCount) {
this.host.log("instance count mismatch, expected %d, got %d, from %s",
serviceCount, r.documents.size(), u);
isConverged = false;
break;
}
for (URI instanceUri : serviceMap.keySet()) {
ReplicationTestServiceState initialState = serviceMap.get(instanceUri);
ReplicationTestServiceState newState = Utils.fromJson(
r.documents.get(instanceUri.getPath()),
ReplicationTestServiceState.class);
if (newState.documentVersion == 0) {
this.host.log("version mismatch, expected %d, got %d, from %s", 0,
newState.documentVersion, instanceUri);
isConverged = false;
break;
}
if (initialState.stringField.equals(newState.stringField)) {
this.host.log("field mismatch, expected %s, got %s, from %s",
initialState.stringField, newState.stringField, instanceUri);
isConverged = false;
break;
}
if (newState.queryTaskLink == null) {
this.host.log("missing query task link from %s", instanceUri);
isConverged = false;
break;
}
// Only instances with OWNER_SELECTION patch string field with self link so bypass this check
if (!newState.documentSelfLink
.contains(ReplicationFactoryTestService.STRICT_SELF_LINK)
&& !newState.documentSelfLink
.contains(ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK)
&& !newState.stringField.equals(newState.documentSelfLink)) {
this.host.log("State not in final state");
isConverged = false;
break;
}
String sig = uriToSignature.get(instanceUri);
if (sig == null) {
sig = Utils.computeSignature(newState, sdd);
uriToSignature.put(instanceUri, sig);
} else {
String newSig = Utils.computeSignature(newState, sdd);
if (!sig.equals(newSig)) {
isConverged = false;
this.host.log("signature mismatch, expected %s, got %s, from %s",
sig, newSig, instanceUri);
}
}
ProcessingStage ps = h.getServiceStage(newState.queryTaskLink);
if (ps == null || ps != ProcessingStage.AVAILABLE) {
this.host.log("missing query task service from %s", newState.queryTaskLink,
instanceUri);
isConverged = false;
break;
}
}
if (isConverged == false) {
break;
}
}
if (isConverged == true) {
break;
}
Thread.sleep(100);
}
if (!isConverged) {
throw new TimeoutException("States did not converge");
}
return serviceMap;
}
@Test
public void replicationWithOutOfOrderPostAndUpdates() throws Throwable {
// This test verifies that if a replica receives
// replication requests of POST and PATCH/PUT
// out-of-order, xenon can still handle it
// by doing retries for failed out-of-order
// updates. To verify this, we setup a node
// group and set quorum to just 1, so that the post
// returns as soon as the owner commits the post,
// so that we increase the chance of out-of-order
// update replication requests.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
state.counter = 1L;
VerificationHost peer = this.host.getPeerHost();
TestContext ctx = this.host.testCreate(this.serviceCount * this.updateCount);
for (int i = 0; i < this.serviceCount; i++) {
Operation post = Operation
.createPost(peer, ExampleService.FACTORY_LINK)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
for (int k = 0; k < this.updateCount; k++) {
ExampleServiceState update = new ExampleServiceState();
state.counter = (long) k;
Operation patch = Operation
.createPatch(peer, rsp.documentSelfLink)
.setBody(update)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
});
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void replication() throws Throwable {
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replicationSsl() throws Throwable {
this.replicationUriScheme = ServiceHost.HttpScheme.HTTPS_ONLY;
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replication1x() throws Throwable {
this.replicationFactor = 1L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication1xExampleFactoryService.SELF_LINK;
doReplication();
}
@Test
public void replication3x() throws Throwable {
this.replicationFactor = 3L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_3X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication3xExampleFactoryService.SELF_LINK;
this.nodeCount = Math.max(5, this.nodeCount);
doReplication();
}
private void doReplication() throws Throwable {
this.isPeerSynchronizationEnabled = false;
CommandLineArgumentParser.parseFromProperties(this);
Date expiration = new Date();
if (this.testDurationSeconds > 0) {
expiration = new Date(expiration.getTime()
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
}
Map<Action, Long> elapsedTimePerAction = new HashMap<>();
Map<Action, Long> countPerAction = new HashMap<>();
long totalOperations = 0;
int iterationCount = 0;
do {
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// for limited replication factor, we will still set the quorum high, and expect
// the limited replication selector to use the minimum between majority of replication
// factor, versus node group membership quorum
this.host.setNodeGroupQuorum(this.nodeCount);
// since we have disabled peer synch, trigger it explicitly so factories become available
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
waitForReplicationFactoryConvergence();
if (this.replicationUriScheme == ServiceHost.HttpScheme.HTTPS_ONLY) {
// confirm nodes are joined using HTTPS group references
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
assertTrue(UriUtils.HTTPS_SCHEME.equals(nodeGroup.getScheme()));
}
}
}
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, countPerAction, elapsedTimePerAction);
totalOperations += this.serviceCount;
if (this.testDurationSeconds == 0) {
// various validation tests, executed just once, ignored in long running test
this.host.doExampleServiceUpdateAndQueryByVersion(this.host.getPeerHostUri(),
this.serviceCount);
verifyReplicatedForcedPostAfterDelete(childStates);
verifyInstantNotFoundFailureOnBadLinks();
verifyReplicatedIdempotentPost(childStates);
verifyDynamicMaintOptionToggle(childStates);
}
totalOperations += this.serviceCount;
if (expiration == null) {
expiration = this.host.getTestExpiration();
}
int expectedVersion = this.updateCount;
if (!this.host.isStressTest()
&& (this.host.getPeerCount() > 16
|| this.serviceCount * this.updateCount > 100)) {
this.host.setStressTest(true);
}
long opCount = this.serviceCount * this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
expectedVersion += this.updateCount;
totalOperations += opCount;
childStates = doStateUpdateReplicationTest(Action.PUT, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += opCount;
Date queryExp = this.host.getTestExpiration();
if (expiration.after(queryExp)) {
queryExp = expiration;
}
while (new Date().before(queryExp)) {
Set<String> links = verifyReplicatedServiceCountWithBroadcastQueries();
if (links.size() < this.serviceCount) {
this.host.log("Found only %d links across nodes, retrying", links.size());
Thread.sleep(500);
continue;
}
break;
}
totalOperations += this.serviceCount;
if (queryExp.before(new Date())) {
throw new TimeoutException();
}
expectedVersion += 1;
doStateUpdateReplicationTest(Action.DELETE, this.serviceCount, 1,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += this.serviceCount;
// compute the binary serialized payload, and the JSON payload size
ExampleServiceState st = childStates.values().iterator().next();
String json = Utils.toJson(st);
int byteCount = KryoSerializers.serializeDocument(st, 4096).position();
int jsonByteCount = json.getBytes(Utils.CHARSET).length;
// estimate total bytes transferred between nodes. The owner receives JSON from the client
// but then uses binary serialization to the N-1 replicas
long totalBytes = jsonByteCount * totalOperations
+ (this.nodeCount - 1) * byteCount * totalOperations;
this.host.log(
"Bytes per json:%d, per binary: %d, Total operations: %d, Total bytes:%d",
jsonByteCount,
byteCount,
totalOperations,
totalBytes);
if (iterationCount++ < 2 && this.testDurationSeconds > 0) {
// ignore data during JVM warm-up, first two iterations
countPerAction.clear();
elapsedTimePerAction.clear();
}
} while (new Date().before(expiration) && this.totalOperationLimit > totalOperations);
logHostStats();
logPerActionThroughput(elapsedTimePerAction, countPerAction);
this.host.doNodeGroupStatsVerification(this.host.getNodeGroupMap());
}
private void logHostStats() {
for (URI u : this.host.getNodeGroupMap().keySet()) {
URI mgmtUri = UriUtils.buildUri(u, ServiceHostManagementService.SELF_LINK);
mgmtUri = UriUtils.buildStatsUri(mgmtUri);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, mgmtUri);
this.host.log("%s: %s", u, Utils.toJsonHtml(stats));
}
}
private void logPerActionThroughput(Map<Action, Long> elapsedTimePerAction,
Map<Action, Long> countPerAction) {
for (Action a : EnumSet.allOf(Action.class)) {
Long count = countPerAction.get(a);
if (count == null) {
continue;
}
Long elapsedMicros = elapsedTimePerAction.get(a);
double thpt = (count * 1.0) / (1.0 * elapsedMicros);
thpt *= 1000000;
this.host.log("Total ops for %s: %d, Throughput (ops/sec): %f", a, count, thpt);
}
}
private void updatePerfDataPerAction(Action a, Long startTime, Long opCount,
Map<Action, Long> countPerAction, Map<Action, Long> elapsedTime) {
if (opCount == null || countPerAction != null) {
countPerAction.merge(a, opCount, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
if (startTime == null || elapsedTime == null) {
return;
}
long delta = Utils.getNowMicrosUtc() - startTime;
elapsedTime.merge(a, delta, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
private void verifyReplicatedIdempotentPost(Map<String, ExampleServiceState> childStates)
throws Throwable {
// verify IDEMPOTENT POST conversion to PUT, with replication
// Since the factory is not idempotent by default, enable the option dynamically
Map<URI, URI> exampleFactoryUris = this.host
.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK);
for (URI factoryUri : exampleFactoryUris.values()) {
this.host.toggleServiceOptions(factoryUri,
EnumSet.of(ServiceOption.IDEMPOTENT_POST), null);
}
TestContext ctx = this.host.testCreate(childStates.size());
for (Entry<String, ExampleServiceState> entry : childStates.entrySet()) {
Operation post = Operation
.createPost(this.host.getPeerServiceUri(ExampleService.FACTORY_LINK))
.setBody(entry.getValue())
.setCompletion(ctx.getCompletion());
this.host.send(post);
}
ctx.await();
}
/**
* Verifies that DELETE actions propagate and commit, and, that forced POST actions succeed
*/
private void verifyReplicatedForcedPostAfterDelete(Map<String, ExampleServiceState> childStates)
throws Throwable {
// delete one of the children, then re-create but with a zero version, using a special
// directive that forces creation
Entry<String, ExampleServiceState> childEntry = childStates.entrySet().iterator().next();
TestContext ctx = this.host.testCreate(1);
Operation delete = Operation
.createDelete(this.host.getPeerServiceUri(childEntry.getKey()))
.setCompletion(ctx.getCompletion());
this.host.send(delete);
ctx.await();
if (!this.host.isRemotePeerTest()) {
this.host.waitFor("services not deleted", () -> {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(childEntry.getKey());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
childEntry.getKey(), h.toString(), stg);
return false;
}
}
return true;
});
}
TestContext postCtx = this.host.testCreate(1);
Operation opPost = Operation
.createPost(this.host.getPeerServiceUri(this.replicationTargetFactoryLink))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE)
.setBody(childEntry.getValue())
.setCompletion((o, e) -> {
if (e != null) {
postCtx.failIteration(e);
} else {
postCtx.completeIteration();
}
});
this.host.send(opPost);
this.host.testWait(postCtx);
}
private void waitForReplicationFactoryConvergence() throws Throwable {
// for code coverage, verify the convenience method on the host also reports available
WaitHandler wh = () -> {
TestContext ctx = this.host.testCreate(1);
boolean[] isReady = new boolean[1];
CompletionHandler ch = (o, e) -> {
if (e != null) {
isReady[0] = false;
} else {
isReady[0] = true;
}
ctx.completeIteration();
};
VerificationHost peerHost = this.host.getPeerHost();
if (peerHost == null) {
NodeGroupUtils.checkServiceAvailability(ch, this.host,
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
} else {
peerHost.checkReplicatedServiceAvailable(ch, this.replicationTargetFactoryLink);
}
ctx.await();
return isReady[0];
};
this.host.waitFor("available check timeout for " + this.replicationTargetFactoryLink, wh);
}
private Set<String> verifyReplicatedServiceCountWithBroadcastQueries()
throws Throwable {
// create a query task, which will execute on a randomly selected node. Since there is no guarantee the node
// selected to execute the query task is the one with all the replicated services, broadcast to all nodes, then
// join the results
URI nodeUri = this.host.getPeerHostUri();
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
URI queryTaskFactoryUri = UriUtils
.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
// send the POST to the forwarding service on one of the nodes, with the broadcast query parameter set
URI forwardingService = UriUtils.buildBroadcastRequestUri(queryTaskFactoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
Set<String> links = new HashSet<>();
TestContext testContext = this.host.testCreate(1);
Operation postQuery = Operation
.createPost(forwardingService)
.setBody(task)
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
NodeGroupBroadcastResponse rsp = o
.getBody(NodeGroupBroadcastResponse.class);
NodeGroupBroadcastResult broadcastResponse = NodeGroupUtils.toBroadcastResult(rsp);
if (broadcastResponse.hasFailure()) {
testContext.fail(new IllegalStateException(
"Failure from query tasks: " + Utils.toJsonHtml(rsp)));
return;
}
// verify broadcast requests should come from all discrete nodes
Set<String> ownerIds = new HashSet<>();
for (PeerNodeResult successResponse : broadcastResponse.successResponses) {
QueryTask qt = successResponse.castBodyTo(QueryTask.class);
this.host.log("Broadcast response from %s %s", qt.documentSelfLink,
qt.documentOwner);
ownerIds.add(qt.documentOwner);
if (qt.results == null) {
this.host.log("Node %s had no results", successResponse.requestUri);
continue;
}
for (String l : qt.results.documentLinks) {
links.add(l);
}
}
testContext.completeIteration();
});
this.host.send(postQuery);
testContext.await();
return links;
}
private void verifyInstantNotFoundFailureOnBadLinks() throws Throwable {
this.host.toggleNegativeTestMode(true);
TestContext testContext = this.host.testCreate(this.serviceCount);
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.complete();
return;
}
// strange, service exists, lets verify
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(o.getUri().getPath());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
o.getUri().getPath(), h.toString(), stg);
}
}
testContext.fail(new Throwable("Expected service to not exist:"
+ o.toString()));
};
// do a negative test: send request to a example child we know does not exist, but disable queuing
// so we get 404 right away
for (int i = 0; i < this.serviceCount; i++) {
URI factoryURI = this.host.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK)
.values().iterator().next();
URI bogusChild = UriUtils.extendUri(factoryURI,
Utils.getNowMicrosUtc() + UUID.randomUUID().toString());
Operation patch = Operation.createPatch(bogusChild)
.setCompletion(c)
.setBody(new ExampleServiceState());
this.host.send(patch);
}
testContext.await();
this.host.toggleNegativeTestMode(false);
}
@Test
public void factorySynchronization() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
factorySynchronizationNoChildren();
factoryDuplicatePost();
}
@Test
public void replicationWithAuthzCacheClear() throws Throwable {
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.setNodeGroupQuorum(this.nodeCount);
VerificationHost groupHost = this.host.getPeerHost();
// wait for auth related services to be stabilized
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, ResourceGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, RoleService.FACTORY_LINK));
String fooUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"foo@vmware.com");
String barUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"bar@vmware.com");
String bazUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"baz@vmware.com");
groupHost.setSystemAuthorizationContext();
// create user, user-group, resource-group, role for foo@vmware.com
// user: /core/authz/users/foo@vmware.com
// user-group: /core/authz/user-groups/foo-user-group
// resource-group: /core/authz/resource-groups/foo-resource-group
// role: /core/authz/roles/foo-role-1
TestContext testContext = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("foo@vmware.com")
.setUserEmail("foo@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setUserGroupName("foo-user-group")
.setResourceGroupName("foo-resource-group")
.setRoleName("foo-role-1")
.setCompletion(testContext.getCompletion())
.start();
testContext.await();
// create another user-group, resource-group, and role for foo@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: /core/authz/role/foo-role-2
TestContext ctxToCreateAnotherRole = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(fooUserLink)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setRoleName("foo-role-2")
.setCompletion(ctxToCreateAnotherRole.getCompletion())
.setupRole();
ctxToCreateAnotherRole.await();
// create user, user-group, resource-group, role for bar@vmware.com
// user: /core/authz/users/bar@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("bar@vmware.com")
.setUserEmail("bar@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBar.getCompletion())
.start();
ctxToCreateBar.await();
// create user, user-group, resource-group, role for baz@vmware.com
// user: /core/authz/users/baz@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBaz = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("baz@vmware.com")
.setUserEmail("baz@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBaz.getCompletion())
.start();
ctxToCreateBaz.await();
AuthorizationContext fooAuthContext = groupHost.assumeIdentity(fooUserLink);
AuthorizationContext barAuthContext = groupHost.assumeIdentity(barUserLink);
AuthorizationContext bazAuthContext = groupHost.assumeIdentity(bazUserLink);
String fooToken = fooAuthContext.getToken();
String barToken = barAuthContext.getToken();
String bazToken = bazAuthContext.getToken();
groupHost.resetSystemAuthorizationContext();
// verify GET will NOT clear cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/users/foo@vmware.com")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/resource-groups/foo-resource-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
// verify deleting role should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user-group should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
// delete the user group associated with the user
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify creating new role should clear the auth cache (using bar@vmware.com)
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
Query q = Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.build();
TestContext ctxToCreateAnotherRoleForBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(barUserLink)
.setResourceGroupName("/core/authz/resource-groups/new-rg")
.setResourceQuery(q)
.setRoleName("bar-role-2")
.setCompletion(ctxToCreateAnotherRoleForBar.getCompletion())
.setupRole();
ctxToCreateAnotherRoleForBar.await();
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
//
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
// Updating the resource group should be able to handle the fact that the user group does not exist
String newResourceGroupLink = "/core/authz/resource-groups/new-rg";
Query updateResourceGroupQuery = Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.query = updateResourceGroupQuery;
this.host.sendAndWaitExpectSuccess(
Operation.createPut(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(resourceGroupState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
// verify patching user should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
UserState userState = new UserState();
userState.userGroupLinks = new HashSet<>();
userState.userGroupLinks.add("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, fooUserLink))
.setBody(userState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user should clear the auth cache
populateAuthCacheInAllPeers(bazAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(groupHost, bazUserLink)));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(bazToken);
// verify patching ResourceGroup should clear the auth cache
// uses "new-rg" resource group that has associated to user bar
TestRequestSender sender = new TestRequestSender(this.host.getPeerHost());
groupHost.setSystemAuthorizationContext();
Operation newResourceGroupGetOp = Operation.createGet(groupHost, newResourceGroupLink);
ResourceGroupState newResourceGroupState = sender.sendAndWait(newResourceGroupGetOp, ResourceGroupState.class);
groupHost.resetSystemAuthorizationContext();
PatchQueryRequest patchBody = PatchQueryRequest.create(newResourceGroupState.query, false);
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(patchBody));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
}
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {
// send a GET request to the ExampleService factory to populate auth cache on each peer.
// since factory is not OWNER_SELECTION service, request goes to the specified node.
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setAuthorizationContext(authContext);
// based on the role created in test, all users have access to ExampleService
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK)));
}
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(authContext.getToken(), true));
}
private void verifyAuthCacheHasClearedInAllPeers(String userToken) {
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(userToken, false));
}
private boolean checkCacheInAllPeers(String token, boolean expectEntries) throws Throwable {
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setSystemAuthorizationContext();
MinimalTestService s = new MinimalTestService();
peer.addPrivilegedService(MinimalTestService.class);
peer.startServiceAndWait(s, UUID.randomUUID().toString(), null);
peer.resetSystemAuthorizationContext();
boolean contextFound = peer.getAuthorizationContext(s, token) != null;
if ((expectEntries && !contextFound) || (!expectEntries && contextFound)) {
return false;
}
}
return true;
}
private void factoryDuplicatePost() throws Throwable, InterruptedException, TimeoutException {
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI factoryUri = this.host
.getPeerServiceUri(ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> states = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
TestContext testContext = serviceHost.testCreate(states.size());
ReplicationTestServiceState initialState = new ReplicationTestServiceState();
for (URI uri : states.keySet()) {
initialState.documentSelfLink = uri.toString().substring(uri.toString()
.lastIndexOf(UriUtils.URI_PATH_CHAR) + 1);
Operation createPost = Operation
.createPost(factoryUri)
.setBody(initialState)
.setCompletion(
(o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
testContext.fail(
new IllegalStateException(
"Incorrect response code received"));
return;
}
testContext.complete();
});
serviceHost.send(createPost);
}
testContext.await();
}
private void factorySynchronizationNoChildren() throws Throwable {
int factoryCount = Math.max(this.serviceCount, 25);
setUp(this.nodeCount);
// start many factories, in each host, so when the nodes join there will be a storm
// of synchronization requests between the nodes + factory instances
TestContext testContext = this.host.testCreate(this.nodeCount * factoryCount);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
for (int i = 0; i < factoryCount; i++) {
Operation startPost = Operation.createPost(
UriUtils.buildUri(h,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, UUID
.randomUUID().toString())))
.setCompletion(testContext.getCompletion());
h.startService(startPost, ExampleService.createFactory());
}
}
testContext.await();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
@Test
public void forwardingAndSelection() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
for (int i = 0; i < this.iterationCount; i++) {
directOwnerSelection();
forwardingToPeerId();
forwardingToKeyHashNode();
broadcast();
}
}
public void broadcast() throws Throwable {
// Do a broadcast on a local, non replicated service. Replicated services can not
// be used with broadcast since they will duplicate the update and potentially route
// to a single node
URI nodeGroup = this.host.getPeerNodeGroupUri();
long c = this.updateCount * this.nodeCount;
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
// we broadcast one update, per service, through one peer. We expect to see
// the same update across all peers, just like with replicated services
nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildBroadcastRequestUri(serviceUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
for (URI baseHostUri : this.host.getNodeGroupMap().keySet()) {
List<URI> uris = new ArrayList<>();
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(baseHostUri, s.documentSelfLink);
uris.add(serviceUri);
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service broadcast failure");
}
}
}
}
public void forwardingToKeyHashNode() throws Throwable {
long c = this.updateCount * this.nodeCount;
Map<String, List<String>> ownersPerServiceLink = new HashMap<>();
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to owner, per service link
// 2) verify the request ended up on the owner the partitioning service predicted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
URI nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildForwardRequestUri(serviceUri,
null,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
this.host.logThroughput();
AtomicInteger assignedLinks = new AtomicInteger();
TestContext testContextForPost = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
// make sure the key is the path to the service. The initial state self link is not a
// path ...
String key = UriUtils.normalizeUriPath(s.documentSelfLink);
s.documentSelfLink = key;
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion((o, e) -> {
if (e != null) {
testContextForPost.fail(e);
return;
}
synchronized (ownersPerServiceLink) {
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
List<String> links = ownersPerServiceLink.get(rsp.ownerNodeId);
if (links == null) {
links = new ArrayList<>();
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
links.add(key);
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
assignedLinks.incrementAndGet();
testContextForPost.complete();
});
this.host.send(post);
}
testContextForPost.await();
assertTrue(assignedLinks.get() == initialStates.size());
// verify the services on the node that should be owner, has modified state
for (Entry<String, List<String>> e : ownersPerServiceLink.entrySet()) {
String nodeId = e.getKey();
List<String> links = e.getValue();
NodeState ns = this.host.getNodeStateMap().get(nodeId);
List<URI> uris = new ArrayList<>();
// make a list of URIs to the services assigned to this peer node
for (String l : links) {
uris.add(UriUtils.buildUri(ns.groupReference, l));
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service forwarding failure");
} else {
}
}
}
}
public void forwardingToPeerId() throws Throwable {
long c = this.updateCount * this.nodeCount;
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to a specific peer id, per service link
// 2) verify the request ended up on the peer we targeted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
s = Utils.clone(s);
// set the owner to be the target node. we will use this to verify it matches
// the id in the state, which is set through a forwarded PATCH
s.documentOwner = peer.getId();
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
VerificationHost peerEntryPoint = this.host.getPeerHost();
// add a custom header and make sure the service sees it in its handler, in the request
// headers, and we see a service response header in our response
String headerName = MinimalTestService.TEST_HEADER_NAME.toLowerCase();
UUID id = UUID.randomUUID();
String headerRequestValue = "request-" + id;
String headerResponseValue = "response-" + id;
TestContext testContextForPut = this.host.testCreate(initialStates.size() * this.nodeCount);
for (ServiceDocument s : initialStates) {
// send a PATCH the id for each document, to each peer. If it routes to the proper peer
// the initial state.documentOwner, will match the state.id
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
// For testing coverage, force the use of the same forwarding service instance.
// We make all request flow from one peer to others, testing both loopback p2p
// and true forwarding. Otherwise, the forwarding happens by directly contacting
// peer we want to land on!
URI localForwardingUri = UriUtils.buildUri(peerEntryPoint.getUri(),
s.documentSelfLink);
// add a query to make sure it does not affect forwarding
localForwardingUri = UriUtils.extendUriWithQuery(localForwardingUri, "k", "v",
"k1", "v1", "k2", "v2");
URI u = UriUtils.buildForwardToPeerUri(localForwardingUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR, EnumSet.noneOf(ServiceOption.class));
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = peer.getId();
this.host.send(Operation.createPut(u)
.addRequestHeader(headerName, headerRequestValue)
.setCompletion(
(o, e) -> {
if (e != null) {
testContextForPut.fail(e);
return;
}
String value = o.getResponseHeader(headerName);
if (value == null || !value.equals(headerResponseValue)) {
testContextForPut.fail(new IllegalArgumentException(
"response header not found"));
return;
}
testContextForPut.complete();
})
.setBody(body));
}
}
testContextForPut.await();
this.host.logThroughput();
TestContext ctx = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation get = Operation.createGet(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
MinimalTestServiceState rsp = o
.getBody(MinimalTestServiceState.class);
if (!rsp.id.equals(rsp.documentOwner)) {
ctx.fail(
new IllegalStateException("Expected: "
+ rsp.documentOwner + " was: " + rsp.id));
} else {
ctx.complete();
}
});
this.host.send(get);
}
}
ctx.await();
// Do a negative test: Send a request that will induce failure in the service handler and
// make sure we receive back failure, with a ServiceErrorResponse body
this.host.toggleDebuggingMode(true);
TestContext testCxtForPut = this.host.testCreate(this.host.getInProcessHostMap().size());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
ServiceDocument s = initialStates.get(0);
URI serviceUri = UriUtils.buildUri(peerEntryPoint.getUri(), s.documentSelfLink);
URI u = UriUtils.buildForwardToPeerUri(serviceUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
null);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
// setting id to null will cause validation failure.
body.id = null;
this.host.send(Operation.createPut(u)
.setCompletion(
(o, e) -> {
if (e == null) {
testCxtForPut.fail(new IllegalStateException(
"expected failure"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (rsp.message == null || rsp.message.isEmpty()) {
testCxtForPut.fail(new IllegalStateException(
"expected error response message"));
return;
}
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)
|| 0 != Double.compare(Math.PI, rsp.customErrorField)) {
testCxtForPut.fail(new IllegalStateException(
"expected custom error fields"));
return;
}
testCxtForPut.complete();
})
.setBody(body));
}
testCxtForPut.await();
this.host.toggleDebuggingMode(false);
}
private void directOwnerSelection() throws Throwable {
Map<URI, Map<String, Long>> keyToNodeAssignmentsPerNode = new HashMap<>();
List<String> keys = new ArrayList<>();
long c = this.updateCount * this.nodeCount;
// generate N keys once, then ask each node to assign to its peers. Each node should come up
// with the same distribution
for (int i = 0; i < c; i++) {
keys.add(Utils.getNowMicrosUtc() + "");
}
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
keyToNodeAssignmentsPerNode.put(nodeGroup, new HashMap<>());
}
this.host.waitForNodeGroupConvergence(this.nodeCount);
TestContext testContext = this.host.testCreate(c * this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
for (String key : keys) {
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation
.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion(
(o, e) -> {
try {
synchronized (keyToNodeAssignmentsPerNode) {
SelectOwnerResponse rsp = o
.getBody(SelectOwnerResponse.class);
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode
.get(nodeGroup);
Long l = assignmentsPerNode.get(rsp.ownerNodeId);
if (l == null) {
l = 0L;
}
assignmentsPerNode.put(rsp.ownerNodeId, l + 1);
testContext.complete();
}
} catch (Throwable ex) {
testContext.fail(ex);
}
});
this.host.send(post);
}
}
testContext.await();
this.host.logThroughput();
Map<String, Long> countPerNode = null;
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode.get(nodeGroup);
if (countPerNode == null) {
countPerNode = assignmentsPerNode;
}
this.host.log("Node group %s assignments: %s", nodeGroup, assignmentsPerNode);
for (Entry<String, Long> e : assignmentsPerNode.entrySet()) {
// we assume that with random keys, and random node ids, each node will get at least
// one key.
assertTrue(e.getValue() > 0);
Long count = countPerNode.get(e.getKey());
if (count == null) {
continue;
}
if (!count.equals(e.getValue())) {
this.host.logNodeGroupState();
throw new IllegalStateException(
"Node id got assigned the same key different number of times, on one of the nodes");
}
}
}
}
@Test
public void replicationFullQuorumMissingServiceOnPeer() throws Throwable {
// This test verifies the following scenario:
// A new node joins an existing node-group with
// services already created. Synchronization is
// still in-progress and a write request arrives.
// If the quorum is configured to FULL, the write
// request will fail on the new node with not-found
// error, since synchronization hasn't completed.
// The test verifies that when this happens, the
// owner node will try to synchronize on-demand
// and retry the original update reqeust.
// Artificially setting the replica not found timeout to
// a lower-value, to reduce the wait time before owner
// retries
System.setProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS,
Long.toString(TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS)));
this.host = VerificationHost.create(0);
this.host.setPeerSynchronizationEnabled(false);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.start();
// Setup one host and create some example
// services on it.
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(this.host, this.serviceCount, exampleUris, null);
// Add a second host with synchronization disabled,
// Join it to the existing host.
VerificationHost host2 = new VerificationHost();
try {
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--id=" + mainHostId,
"--port=0",
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + this.host.getUri()
};
host2.initialize(args);
host2.setPeerSynchronizationEnabled(false);
host2.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
host2.start();
this.host.addPeerNode(host2);
// Wait for node-group to converge
List<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.buildUri(this.host, ServiceUriPaths.DEFAULT_NODE_GROUP));
nodeGroupUris.add(UriUtils.buildUri(host2, ServiceUriPaths.DEFAULT_NODE_GROUP));
this.host.waitForNodeGroupConvergence(nodeGroupUris, 2, 2, true);
// Set the quorum to full.
this.host.setNodeGroupQuorum(2, nodeGroupUris.get(0));
host2.setNodeGroupQuorum(2);
// Filter the created examples to only those
// that are owned by host-1.
List<URI> host1Examples = exampleUris.stream()
.filter(e -> this.host.isOwner(e.getPath(), ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.collect(Collectors.toList());
// Start patching all filtered examples. Because
// synchronization is disabled each of these
// example services will not exist on the new
// node that we added resulting in a non_found
// error. However, the owner will retry this
// after on-demand synchronization and hence
// patches should succeed.
ExampleServiceState state = new ExampleServiceState();
state.counter = 1L;
if (host1Examples.size() > 0) {
this.host.log(Level.INFO, "Starting patches");
TestContext ctx = this.host.testCreate(host1Examples.size());
for (URI exampleUri : host1Examples) {
Operation patch = Operation
.createPatch(exampleUri)
.setBody(state)
.setReferer("localhost")
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
ctx.await();
}
} finally {
host2.tearDown();
}
}
@Test
public void replicationWithAuthAndNodeRestart() throws Throwable {
AuthorizationHelper authHelper;
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
authHelper = new AuthorizationHelper(this.host);
// relax quorum to allow for divergent writes, on independent nodes (not yet joined)
this.host.setSystemAuthorizationContext();
// Create the same users and roles on every peer independently
Map<ServiceHost, Collection<String>> roleLinksByHost = new HashMap<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String email = "jane@doe.com";
authHelper.createUserService(h, email);
authHelper.createRoles(h, email);
}
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = getRolesByHost(roleLinksByHost);
// Join nodes to force synchronization and convergence
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> newRoleStateByHost = getRolesByHost(roleLinksByHost);
// Verify that every host independently advances their version & epoch
for (ServiceHost h : roleStateByHost.keySet()) {
Map<URI, RoleState> roleState = roleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState oldRole = roleState.get(u);
RoleState newRole = newRoleStateByHost.get(h).get(u);
assertTrue("version should have advanced",
newRole.documentVersion > oldRole.documentVersion);
assertTrue("epoch should have advanced",
newRole.documentEpoch > oldRole.documentEpoch);
}
}
// Verify that every host converged to the same version, epoch, and owner
Map<String, Long> versions = new HashMap<>();
Map<String, Long> epochs = new HashMap<>();
Map<String, String> owners = new HashMap<>();
for (ServiceHost h : newRoleStateByHost.keySet()) {
Map<URI, RoleState> roleState = newRoleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState newRole = roleState.get(u);
if (versions.containsKey(newRole.documentSelfLink)) {
assertTrue(versions.get(newRole.documentSelfLink) == newRole.documentVersion);
} else {
versions.put(newRole.documentSelfLink, newRole.documentVersion);
}
if (epochs.containsKey(newRole.documentSelfLink)) {
assertTrue(Objects.equals(epochs.get(newRole.documentSelfLink),
newRole.documentEpoch));
} else {
epochs.put(newRole.documentSelfLink, newRole.documentEpoch);
}
if (owners.containsKey(newRole.documentSelfLink)) {
assertEquals(owners.get(newRole.documentSelfLink), newRole.documentOwner);
} else {
owners.put(newRole.documentSelfLink, newRole.documentOwner);
}
}
}
// create some example tasks, which delete example services. We dont have any
// examples services created, which is good, since we just want these tasks to
// go to finished state, then verify, after node restart, they all start
Set<String> exampleTaskLinks = new ConcurrentSkipListSet<>();
createReplicatedExampleTasks(exampleTaskLinks, null);
Set<String> exampleLinks = new ConcurrentSkipListSet<>();
verifyReplicatedAuthorizedPost(exampleLinks);
// verify restart, with authorization.
// stop one host
VerificationHost hostToStop = this.host.getInProcessHostMap().values().iterator().next();
stopAndRestartHost(exampleLinks, exampleTaskLinks, hostToStop);
}
private void createReplicatedExampleTasks(Set<String> exampleTaskLinks, String name)
throws Throwable {
URI factoryUri = UriUtils.buildFactoryUri(this.host.getPeerHost(),
ExampleTaskService.class);
this.host.setSystemAuthorizationContext();
// Sample body that this user is authorized to create
ExampleTaskServiceState exampleServiceState = new ExampleTaskServiceState();
if (name != null) {
exampleServiceState.customQueryClause = Query.Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, name).build();
}
this.host.log("creating example *task* instances");
TestContext testContext = this.host.testCreate(this.serviceCount);
for (int i = 0; i < this.serviceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
ExampleTaskServiceState rsp = o.getBody(ExampleTaskServiceState.class);
synchronized (exampleTaskLinks) {
exampleTaskLinks.add(rsp.documentSelfLink);
}
testContext.complete();
};
this.host.send(Operation
.createPost(factoryUri)
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
// ensure all tasks are in finished state
this.host.waitFor("Example tasks did not finish", () -> {
ServiceDocumentQueryResult rsp = this.host.getExpandedFactoryState(factoryUri);
for (Object o : rsp.documents.values()) {
ExampleTaskServiceState doc = Utils.fromJson(o, ExampleTaskServiceState.class);
if (TaskState.isFailed(doc.taskInfo)) {
this.host.log("task %s failed: %s", doc.documentSelfLink, doc.failureMessage);
throw new IllegalStateException("task failed");
}
if (!TaskState.isFinished(doc.taskInfo)) {
return false;
}
}
return true;
});
}
private void verifyReplicatedAuthorizedPost(Set<String> exampleLinks)
throws Throwable {
Collection<VerificationHost> hosts = this.host.getInProcessHostMap().values();
RoundRobinIterator<VerificationHost> it = new RoundRobinIterator<>(hosts);
int exampleServiceCount = this.serviceCount;
String userLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "jane@doe.com");
// Verify we can assert identity and make a request to every host
this.host.assumeIdentity(userLink);
// Sample body that this user is authorized to create
ExampleServiceState exampleServiceState = new ExampleServiceState();
exampleServiceState.name = "jane";
this.host.log("creating example instances");
TestContext testContext = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
try {
// Verify the user is set as principal
ExampleServiceState state = o.getBody(ExampleServiceState.class);
assertEquals(state.documentAuthPrincipalLink,
userLink);
exampleLinks.add(state.documentSelfLink);
testContext.complete();
} catch (Throwable e2) {
testContext.fail(e2);
}
};
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
this.host.toggleNegativeTestMode(true);
// Sample body that this user is NOT authorized to create
ExampleServiceState invalidExampleServiceState = new ExampleServiceState();
invalidExampleServiceState.name = "somebody other than jane";
this.host.log("issuing non authorized request");
TestContext testCtx = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(invalidExampleServiceState)
.setCompletion((o, e) -> {
if (e != null) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, o.getStatusCode());
testCtx.complete();
return;
}
testCtx.fail(new IllegalStateException("expected failure"));
}));
}
testCtx.await();
this.host.toggleNegativeTestMode(false);
}
private void stopAndRestartHost(Set<String> exampleLinks, Set<String> exampleTaskLinks,
VerificationHost hostToStop)
throws Throwable, InterruptedException {
// relax quorum
this.host.setNodeGroupQuorum(this.nodeCount - 1);
// expire node that went away quickly to avoid alot of log spam from gossip failures
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(1);
this.host.setNodeGroupConfig(cfg);
this.host.stopHostAndPreserveState(hostToStop);
this.host.waitForNodeGroupConvergence(2, 2);
VerificationHost existingHost = this.host.getInProcessHostMap().values().iterator().next();
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleTaskService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// create some additional tasks on the remaining two hosts, but make sure they don't delete
// any example service instances, by specifying a name value we know will not match anything
createReplicatedExampleTasks(exampleTaskLinks, UUID.randomUUID().toString());
// delete some of the task links, to test synchronization of deleted entries on the restarted
// host
Set<String> deletedExampleLinks = deleteSomeServices(exampleLinks);
// increase quorum on existing nodes, so they wait for new node
this.host.setNodeGroupQuorum(this.nodeCount);
hostToStop.setPort(0);
hostToStop.setSecurePort(0);
if (!VerificationHost.restartStatefulHost(hostToStop)) {
this.host.log("Failed restart of host, aborting");
return;
}
// restart host, rejoin it
URI nodeGroupU = UriUtils.buildUri(hostToStop, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI eNodeGroupU = UriUtils.buildUri(existingHost, ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.setSystemAuthorizationContext();
this.host.joinNodeGroup(nodeGroupU, eNodeGroupU, this.nodeCount);
this.host.testWait();
this.host.addPeerNode(hostToStop);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// set quorum on new node as well
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.resetAuthorizationContext();
this.host.waitFor("Task services not started in restarted host:" + exampleTaskLinks, () -> {
return checkChildServicesIfStarted(exampleTaskLinks, hostToStop) == 0;
});
// verify all services, not previously deleted, are restarted
this.host.waitFor("Services not started in restarted host:" + exampleLinks, () -> {
return checkChildServicesIfStarted(exampleLinks, hostToStop) == 0;
});
int deletedCount = deletedExampleLinks.size();
this.host.waitFor("Deleted services still present in restarted host", () -> {
return checkChildServicesIfStarted(deletedExampleLinks, hostToStop) == deletedCount;
});
}
private Set<String> deleteSomeServices(Set<String> exampleLinks)
throws Throwable {
int deleteCount = exampleLinks.size() / 3;
Iterator<String> itLinks = exampleLinks.iterator();
Set<String> deletedExampleLinks = new HashSet<>();
TestContext testContext = this.host.testCreate(deleteCount);
for (int i = 0; i < deleteCount; i++) {
String link = itLinks.next();
deletedExampleLinks.add(link);
exampleLinks.remove(link);
Operation delete = Operation.createDelete(this.host.getPeerServiceUri(link))
.setCompletion(testContext.getCompletion());
this.host.send(delete);
}
testContext.await();
this.host.log("Deleted links: %s", deletedExampleLinks);
return deletedExampleLinks;
}
private int checkChildServicesIfStarted(Set<String> exampleTaskLinks,
VerificationHost host) {
this.host.setSystemAuthorizationContext();
int notStartedCount = 0;
for (String s : exampleTaskLinks) {
ProcessingStage st = host.getServiceStage(s);
if (st == null) {
notStartedCount++;
}
}
this.host.resetAuthorizationContext();
if (notStartedCount > 0) {
this.host.log("%d services not started on %s (%s)", notStartedCount,
host.getPublicUri(), host.getId());
}
return notStartedCount;
}
private Map<ServiceHost, Map<URI, RoleState>> getRolesByHost(
Map<ServiceHost, Collection<String>> roleLinksByHost) throws Throwable {
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = new HashMap<>();
for (ServiceHost h : roleLinksByHost.keySet()) {
Collection<String> roleLinks = roleLinksByHost.get(h);
Collection<URI> roleURIs = new ArrayList<>();
for (String link : roleLinks) {
roleURIs.add(UriUtils.buildUri(h, link));
}
Map<URI, RoleState> serviceState = this.host.getServiceState(null, RoleState.class,
roleURIs);
roleStateByHost.put(h, serviceState);
}
return roleStateByHost;
}
private void verifyOperationJoinAcrossPeers(Map<URI, ReplicationTestServiceState> childStates)
throws Throwable {
// do a OperationJoin across N nodes, making sure join works when forwarding is involved
List<Operation> joinedOps = new ArrayList<>();
for (ReplicationTestServiceState st : childStates.values()) {
Operation get = Operation.createGet(
this.host.getPeerServiceUri(st.documentSelfLink)).setReferer(
this.host.getReferer());
joinedOps.add(get);
}
TestContext testContext = this.host.testCreate(1);
OperationJoin
.create(joinedOps)
.setCompletion(
(ops, exc) -> {
if (exc != null) {
testContext.fail(exc.values().iterator().next());
return;
}
for (Operation o : ops.values()) {
ReplicationTestServiceState state = o.getBody(
ReplicationTestServiceState.class);
if (state.stringField == null) {
testContext.fail(new IllegalStateException());
return;
}
}
testContext.complete();
})
.sendWith(this.host.getPeerHost());
testContext.await();
}
public Map<String, Set<String>> computeOwnerIdsPerLink(VerificationHost joinedHost,
Collection<String> links)
throws Throwable {
TestContext testContext = this.host.testCreate(links.size());
Map<String, Set<String>> expectedOwnersPerLink = new ConcurrentSkipListMap<>();
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
Set<String> eligibleNodeIds = new HashSet<>();
for (NodeState ns : rsp.selectedNodes) {
eligibleNodeIds.add(ns.id);
}
expectedOwnersPerLink.put(rsp.key, eligibleNodeIds);
testContext.complete();
};
for (String link : links) {
Operation selectOp = Operation.createGet(null)
.setCompletion(c)
.setExpiration(this.host.getOperationTimeoutMicros() + Utils.getNowMicrosUtc());
joinedHost.selectOwner(this.replicationNodeSelector, link, selectOp);
}
testContext.await();
return expectedOwnersPerLink;
}
public <T extends ServiceDocument> void verifyDocumentOwnerAndEpoch(Map<String, T> childStates,
VerificationHost joinedHost,
List<URI> joinedHostUris,
int minExpectedEpochRetries,
int maxExpectedEpochRetries, int expectedOwnerChanges)
throws Throwable, InterruptedException, TimeoutException {
Map<URI, NodeGroupState> joinedHostNodeGroupStates = this.host.getServiceState(null,
NodeGroupState.class, joinedHostUris);
Set<String> joinedHostOwnerIds = new HashSet<>();
for (NodeGroupState st : joinedHostNodeGroupStates.values()) {
joinedHostOwnerIds.add(st.documentOwner);
}
this.host.waitFor("ownership did not converge", () -> {
Map<String, Set<String>> ownerIdsPerLink = computeOwnerIdsPerLink(joinedHost,
childStates.keySet());
boolean isConverged = true;
Map<String, Set<Long>> epochsPerLink = new HashMap<>();
List<URI> nodeSelectorStatsUris = new ArrayList<>();
for (URI baseNodeUri : joinedHostUris) {
nodeSelectorStatsUris.add(UriUtils.buildUri(baseNodeUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
URI factoryUri = UriUtils.buildUri(
baseNodeUri, this.replicationTargetFactoryLink);
ServiceDocumentQueryResult factoryRsp = this.host
.getFactoryState(factoryUri);
if (factoryRsp.documentLinks == null
|| factoryRsp.documentLinks.size() != childStates.size()) {
isConverged = false;
// services not all started in new nodes yet;
this.host.log("Node %s does not have all services: %s", baseNodeUri,
Utils.toJsonHtml(factoryRsp));
break;
}
List<URI> childUris = new ArrayList<>();
for (String link : childStates.keySet()) {
childUris.add(UriUtils.buildUri(baseNodeUri, link));
}
// retrieve the document state directly from each service
Map<URI, ServiceDocument> childDocs = this.host.getServiceState(null,
ServiceDocument.class, childUris);
List<URI> childStatUris = new ArrayList<>();
for (ServiceDocument state : childDocs.values()) {
if (state.documentOwner == null) {
this.host.log("Owner not set in service on new node: %s",
Utils.toJsonHtml(state));
isConverged = false;
break;
}
URI statUri = UriUtils.buildUri(baseNodeUri, state.documentSelfLink,
ServiceHost.SERVICE_URI_SUFFIX_STATS);
childStatUris.add(statUri);
Set<Long> epochs = epochsPerLink.get(state.documentEpoch);
if (epochs == null) {
epochs = new HashSet<>();
epochsPerLink.put(state.documentSelfLink, epochs);
}
epochs.add(state.documentEpoch);
Set<String> eligibleNodeIds = ownerIdsPerLink.get(state.documentSelfLink);
if (!joinedHostOwnerIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not expected: %s, valid ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
if (eligibleNodeIds != null && !eligibleNodeIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not eligible: %s, eligible ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
}
int nodeGroupMaintCount = 0;
int docOwnerToggleOffCount = 0;
int docOwnerToggleCount = 0;
// verify stats were reported by owner node, not a random peer
Map<URI, ServiceStats> allChildStats = this.host.getServiceState(null,
ServiceStats.class, childStatUris);
for (ServiceStats childStats : allChildStats.values()) {
String parentLink = UriUtils.getParentPath(childStats.documentSelfLink);
Set<String> eligibleNodes = ownerIdsPerLink.get(parentLink);
if (!eligibleNodes.contains(childStats.documentOwner)) {
this.host.log("Stats for %s owner not expected. Is %s, should be %s",
parentLink, childStats.documentOwner,
ownerIdsPerLink.get(parentLink));
isConverged = false;
break;
}
ServiceStat maintStat = childStats.entries
.get(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (maintStat != null) {
nodeGroupMaintCount++;
}
ServiceStat docOwnerToggleOffStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
if (docOwnerToggleOffStat != null) {
docOwnerToggleOffCount++;
}
ServiceStat docOwnerToggleStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
if (docOwnerToggleStat != null) {
docOwnerToggleCount++;
}
}
this.host.log("Node group change maintenance observed: %d", nodeGroupMaintCount);
if (nodeGroupMaintCount < expectedOwnerChanges) {
isConverged = false;
}
this.host.log("Toggled off doc owner count: %d, toggle on count: %d",
docOwnerToggleOffCount, docOwnerToggleCount);
if (docOwnerToggleCount < childStates.size()) {
isConverged = false;
}
// verify epochs
for (Set<Long> epochs : epochsPerLink.values()) {
if (epochs.size() > 1) {
this.host.log("Documents have different epochs:%s", epochs.toString());
isConverged = false;
}
}
if (!isConverged) {
break;
}
}
return isConverged;
});
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild) throws Throwable {
return doStateUpdateReplicationTest(action, childCount, updateCount, expectedVersion,
updateBodySetter, convergenceChecker, initialStatesPerChild, null, null);
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild,
Map<Action, Long> countsPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
int testCount = childCount * updateCount;
String testName = "Replication with " + action;
TestContext testContext = this.host.testCreate(testCount);
testContext.setTestName(testName).logBefore();
if (!this.expectFailure) {
// Before we do the replication test, wait for factory availability.
for (URI fu : this.host.getNodeGroupToFactoryMap(this.replicationTargetFactoryLink)
.values()) {
// confirm that /factory/available returns 200 across all nodes
waitForReplicatedFactoryServiceAvailable(fu, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
}
long before = Utils.getNowMicrosUtc();
AtomicInteger failedCount = new AtomicInteger();
// issue an update to each child service and verify it was reflected
// among
// peers
for (T initState : initialStatesPerChild.values()) {
// change a field in the initial state of each service but keep it
// the same across all updates so potential re ordering of the
// updates does not cause spurious test breaks
updateBodySetter.apply(initState);
for (int i = 0; i < updateCount; i++) {
long sentTime = 0;
if (this.expectFailure) {
sentTime = Utils.getNowMicrosUtc();
}
URI factoryOnRandomPeerUri = this.host
.getPeerServiceUri(this.replicationTargetFactoryLink);
long finalSentTime = sentTime;
this.host
.send(Operation
.createPatch(UriUtils.buildUri(factoryOnRandomPeerUri,
initState.documentSelfLink))
.setAction(action)
.forceRemote()
.setBodyNoCloning(initState)
.setCompletion(
(o, e) -> {
if (e != null) {
if (this.expectFailure) {
failedCount.incrementAndGet();
testContext.complete();
return;
}
testContext.fail(e);
return;
}
if (this.expectFailure
&& this.expectedFailureStartTimeMicros > 0
&& finalSentTime > this.expectedFailureStartTimeMicros) {
testContext.fail(new IllegalStateException(
"Request should have failed: %s"
+ o.toString()
+ " sent at " + finalSentTime));
return;
}
testContext.complete();
}));
}
}
testContext.await();
testContext.logAfter();
updatePerfDataPerAction(action, before, (long) (childCount * updateCount), countsPerAction,
elapsedTimePerAction);
if (this.expectFailure) {
this.host.log("Failed count: %d", failedCount.get());
if (failedCount.get() == 0) {
throw new IllegalStateException(
"Possible false negative but expected at least one failure");
}
return initialStatesPerChild;
}
// All updates sent to all children within one host, now wait for
// convergence
if (action != Action.DELETE) {
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
childCount,
expectedVersion);
}
// for DELETE replication, we expect the child services to be stopped
// across hosts and their state marked "deleted". So confirm no children
// are available
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
0,
expectedVersion);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction)
throws Throwable {
return doExampleFactoryPostReplicationTest(childCount, null,
countPerAction, elapsedTimePerAction);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
EnumSet<TestProperty> props,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
this.host.toggleNegativeTestMode(true);
}
String factoryPath = this.replicationTargetFactoryLink;
Map<String, ExampleServiceState> serviceStates = new HashMap<>();
long before = Utils.getNowMicrosUtc();
TestContext testContext = this.host.testCreate(childCount);
testContext.setTestName("POST replication");
testContext.logBefore();
for (int i = 0; i < childCount; i++) {
URI factoryOnRandomPeerUri = this.host.getPeerServiceUri(factoryPath);
Operation post = Operation
.createPost(factoryOnRandomPeerUri)
.setCompletion(testContext.getCompletion());
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = "" + post.getId();
initialState.counter = Long.MIN_VALUE;
// set the self link as a hint so the child service URI is
// predefined instead of random
initialState.documentSelfLink = "" + post.getId();
// factory service is started on all hosts. Now issue a POST to one,
// to create a child service with some initial state.
post.setReferer(this.host.getReferer());
this.host.sendRequest(post.setBody(initialState));
// initial state is cloned and sent, now we can change self link per
// child to reflect its runtime URI, which will
// contain the factory service path
initialState.documentSelfLink = UriUtils.buildUriPath(factoryPath,
initialState.documentSelfLink);
serviceStates.put(initialState.documentSelfLink, initialState);
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
// do not wait for convergence of the child services. Instead
// proceed to the next test which is probably stopping hosts
// abruptly
return serviceStates;
}
testContext.await();
updatePerfDataPerAction(Action.POST, before, (long) this.serviceCount, countPerAction,
elapsedTimePerAction);
testContext.logAfter();
return waitForReplicatedFactoryChildServiceConvergence(serviceStates,
this.exampleStateConvergenceChecker,
childCount,
0L);
}
private void updateExampleServiceOptions(
Map<String, ExampleServiceState> statesPerSelfLink) throws Throwable {
if (this.postCreationServiceOptions == null || this.postCreationServiceOptions.isEmpty()) {
return;
}
TestContext testContext = this.host.testCreate(statesPerSelfLink.size());
URI nodeGroup = this.host.getNodeGroupMap().values().iterator().next();
for (String link : statesPerSelfLink.keySet()) {
URI bUri = UriUtils.buildBroadcastRequestUri(
UriUtils.buildUri(nodeGroup, link, ServiceHost.SERVICE_URI_SUFFIX_CONFIG),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
ServiceConfigUpdateRequest cfgBody = ServiceConfigUpdateRequest.create();
cfgBody.addOptions = this.postCreationServiceOptions;
this.host.send(Operation.createPatch(bUri)
.setBody(cfgBody)
.setCompletion(testContext.getCompletion()));
}
testContext.await();
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
return waitForReplicatedFactoryChildServiceConvergence(
getFactoriesPerNodeGroup(this.replicationTargetFactoryLink),
serviceStates,
stateChecker,
expectedChildCount,
expectedVersion);
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<URI, URI> factories,
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
// now poll all hosts until they converge: They all have a child service
// with the expected URI and it has the same state
Map<String, T> updatedStatesPerSelfLink = new HashMap<>();
Date expiration = new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(this.host.getTimeoutSeconds()));
do {
URI node = factories.keySet().iterator().next();
AtomicInteger getFailureCount = new AtomicInteger();
if (expectedChildCount != 0) {
// issue direct GETs to the services, we do not trust the factory
for (String link : serviceStates.keySet()) {
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(node, link))
.setReferer(this.host.getReferer())
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(5))
.setCompletion(
(o, e) -> {
if (e != null) {
getFailureCount.incrementAndGet();
}
ctx.completeIteration();
});
this.host.sendRequest(get);
this.host.testWait(ctx);
}
}
if (getFailureCount.get() > 0) {
this.host.log("Child services not propagated yet. Failure count: %d",
getFailureCount.get());
Thread.sleep(500);
continue;
}
TestContext testContext = this.host.testCreate(factories.size());
Map<URI, ServiceDocumentQueryResult> childServicesPerNode = new HashMap<>();
for (URI remoteFactory : factories.values()) {
URI factoryUriWithExpand = UriUtils.buildExpandLinksQueryUri(remoteFactory);
Operation get = Operation.createGet(factoryUriWithExpand)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.complete();
return;
}
if (!o.hasBody()) {
testContext.complete();
return;
}
ServiceDocumentQueryResult r = o
.getBody(ServiceDocumentQueryResult.class);
synchronized (childServicesPerNode) {
childServicesPerNode.put(o.getUri(), r);
}
testContext.complete();
});
this.host.send(get);
}
testContext.await();
long expectedNodeCountPerLinkMax = factories.size();
long expectedNodeCountPerLinkMin = expectedNodeCountPerLinkMax;
if (this.replicationFactor != 0) {
// We expect services to end up either on K nodes, or K + 1 nodes,
// if limited replication is enabled. The reason we might end up with services on
// an additional node, is because we elect an owner to synchronize an entire factory,
// using the factory's link, and that might end up on a node not used for any child.
// This will produce children on that node, giving us K+1 replication, which is acceptable
// given K (replication factor) << N (total nodes in group)
expectedNodeCountPerLinkMax = this.replicationFactor + 1;
expectedNodeCountPerLinkMin = this.replicationFactor;
}
if (expectedChildCount == 0) {
expectedNodeCountPerLinkMax = 0;
expectedNodeCountPerLinkMin = 0;
}
// build a service link to node map so we can tell on which node each service instance landed
Map<String, Set<URI>> linkToNodeMap = new HashMap<>();
boolean isConverged = true;
for (Entry<URI, ServiceDocumentQueryResult> entry : childServicesPerNode.entrySet()) {
for (String link : entry.getValue().documentLinks) {
if (!serviceStates.containsKey(link)) {
this.host.log("service %s not expected, node: %s", link, entry.getKey());
isConverged = false;
continue;
}
Set<URI> hostsPerLink = linkToNodeMap.get(link);
if (hostsPerLink == null) {
hostsPerLink = new HashSet<>();
}
hostsPerLink.add(entry.getKey());
linkToNodeMap.put(link, hostsPerLink);
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
// each link must exist on N hosts, where N is either the replication factor, or, if not used, all nodes
for (Entry<String, Set<URI>> e : linkToNodeMap.entrySet()) {
if (e.getValue() == null && this.replicationFactor == 0) {
this.host.log("Service %s not found on any nodes", e.getKey());
isConverged = false;
continue;
}
if (e.getValue().size() < expectedNodeCountPerLinkMin
|| e.getValue().size() > expectedNodeCountPerLinkMax) {
this.host.log("Service %s found on %d nodes, expected %d -> %d", e.getKey(), e
.getValue().size(), expectedNodeCountPerLinkMin,
expectedNodeCountPerLinkMax);
isConverged = false;
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
if (expectedChildCount == 0) {
// DELETE test, all children removed from all hosts, we are done
return updatedStatesPerSelfLink;
}
// verify /available reports correct results on the factory.
URI factoryUri = factories.values().iterator().next();
Class<?> stateType = serviceStates.values().iterator().next().getClass();
waitForReplicatedFactoryServiceAvailable(factoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// we have the correct number of services on all hosts. Now verify
// the state of each service matches what we expect
isConverged = true;
for (Entry<String, Set<URI>> entry : linkToNodeMap.entrySet()) {
String selfLink = entry.getKey();
int convergedNodeCount = 0;
for (URI nodeUri : entry.getValue()) {
ServiceDocumentQueryResult childLinksAndDocsPerHost = childServicesPerNode
.get(nodeUri);
Object jsonState = childLinksAndDocsPerHost.documents.get(selfLink);
if (jsonState == null && this.replicationFactor == 0) {
this.host
.log("Service %s not present on host %s", selfLink, entry.getKey());
continue;
}
if (jsonState == null) {
continue;
}
T initialState = serviceStates.get(selfLink);
if (initialState == null) {
continue;
}
@SuppressWarnings("unchecked")
T stateOnNode = (T) Utils.fromJson(jsonState, stateType);
if (!stateChecker.test(initialState, stateOnNode)) {
this.host
.log("State for %s not converged on node %s. Current state: %s, Initial: %s",
selfLink, nodeUri, Utils.toJsonHtml(stateOnNode),
Utils.toJsonHtml(initialState));
break;
}
if (stateOnNode.documentVersion < expectedVersion) {
this.host
.log("Version (%d, expected %d) not converged, state: %s",
stateOnNode.documentVersion,
expectedVersion,
Utils.toJsonHtml(stateOnNode));
break;
}
if (stateOnNode.documentEpoch == null) {
this.host.log("Epoch is missing, state: %s",
Utils.toJsonHtml(stateOnNode));
break;
}
// Do not check exampleState.counter, in this validation loop.
// We can not compare the counter since the replication test sends the updates
// in parallel, meaning some of them will get re-ordered and ignored due to
// version being out of date.
updatedStatesPerSelfLink.put(selfLink, stateOnNode);
convergedNodeCount++;
}
if (convergedNodeCount < expectedNodeCountPerLinkMin
|| convergedNodeCount > expectedNodeCountPerLinkMax) {
isConverged = false;
break;
}
}
if (isConverged) {
return updatedStatesPerSelfLink;
}
Thread.sleep(500);
} while (new Date().before(expiration));
throw new TimeoutException();
}
private List<ServiceHostState> stopHostsToSimulateFailure(int failedNodeCount) {
int k = 0;
List<ServiceHostState> stoppedHosts = new ArrayList<>();
for (VerificationHost hostToStop : this.host.getInProcessHostMap().values()) {
this.host.log("Stopping host %s", hostToStop);
stoppedHosts.add(hostToStop.getState());
this.host.stopHost(hostToStop);
k++;
if (k >= failedNodeCount) {
break;
}
}
return stoppedHosts;
}
public static class StopVerificationTestService extends StatefulService {
public Collection<URI> serviceTargets;
public AtomicInteger outboundRequestCompletion = new AtomicInteger();
public AtomicInteger outboundRequestFailureCompletion = new AtomicInteger();
public StopVerificationTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation deleteForStop) {
// send requests to replicated services, during stop to verify that the
// runtime prevents any outbound requests from making it out
for (URI uri : this.serviceTargets) {
ReplicationTestServiceState body = new ReplicationTestServiceState();
body.stringField = ReplicationTestServiceState.CLIENT_PATCH_HINT;
for (int i = 0; i < 10; i++) {
// send patch to self, so the select owner logic gets invoked and in theory
// queues or cancels the request
Operation op = Operation.createPatch(this, uri.getPath()).setBody(body)
.setTargetReplicated(true)
.setCompletion((o, e) -> {
if (e != null) {
this.outboundRequestFailureCompletion.incrementAndGet();
} else {
this.outboundRequestCompletion.incrementAndGet();
}
});
sendRequest(op);
}
}
}
}
private void stopHostsAndVerifyQueuing(Collection<VerificationHost> hostsToStop,
VerificationHost remainingHost,
Collection<URI> serviceTargets) throws Throwable {
this.host.log("Starting to stop hosts and verify queuing");
// reduce node expiration for unavailable hosts so gossip warning
// messages do not flood the logs
this.nodeGroupConfig.nodeRemovalDelayMicros = remainingHost.getMaintenanceIntervalMicros();
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(10));
// relax quorum to single remaining host
this.host.setNodeGroupQuorum(1);
// start a special test service that will attempt to send messages when it sees
// handleStop(). This is not expected of production code, since service authors
// should never have to worry about handleStop(). We rely on the fact that handleStop
// will be called due to node shutdown, and issue requests to replicated targets,
// then check if anyone of them actually made it out (they should not have)
List<StopVerificationTestService> verificationServices = new ArrayList<>();
// Do the inverse test. Remove all of the original hosts and this time, expect all the
// documents have owners assigned to the new hosts
for (VerificationHost h : hostsToStop) {
StopVerificationTestService s = new StopVerificationTestService();
verificationServices.add(s);
s.serviceTargets = serviceTargets;
h.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.stopHost(h);
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
for (StopVerificationTestService s : verificationServices) {
if (s.outboundRequestCompletion.get() > 0) {
throw new IllegalStateException("Replicated request succeeded");
}
if (s.outboundRequestFailureCompletion.get() < serviceTargets.size()) {
// We expect at least one failure per service target, if we have less
// keep polling.
this.host.log(
"Not converged yet: service %s on host %s has %d outbound request failures, which is lower than %d",
s.getSelfLink(), s.getHost().getId(),
s.outboundRequestFailureCompletion.get(), serviceTargets.size());
isConverged = false;
break;
}
}
if (isConverged) {
this.host.log("Done with stop hosts and verify queuing");
return;
}
Thread.sleep(250);
}
throw new TimeoutException();
}
private void waitForReplicatedFactoryServiceAvailable(URI uri, String nodeSelectorPath)
throws Throwable {
if (this.skipAvailabilityChecks) {
return;
}
if (UriUtils.isHostEqual(this.host, uri)) {
VerificationHost host = this.host;
// if uri is for in-process peers, then use the one
URI peerUri = UriUtils.buildUri(uri.toString().replace(uri.getPath(), ""));
VerificationHost peer = this.host.getInProcessHostMap().get(peerUri);
if (peer != null) {
host = peer;
}
TestContext ctx = host.testCreate(1);
CompletionHandler ch = (o, e) -> {
if (e != null) {
String msg = "Failed to check replicated factory service availability";
ctx.failIteration(new RuntimeException(msg, e));
return;
}
ctx.completeIteration();
};
host.registerForServiceAvailability(ch, nodeSelectorPath, true, uri.getPath());
ctx.await();
} else {
// for remote host
this.host.waitForReplicatedFactoryServiceAvailable(uri, nodeSelectorPath);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_7
|
crossvul-java_data_bad_3078_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_5
|
crossvul-java_data_bad_3082_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.var.equals((1.0 * numBins) / 2.0));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_5
|
crossvul-java_data_good_3078_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_5
|
crossvul-java_data_good_3080_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_4
|
crossvul-java_data_bad_3080_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_1
|
crossvul-java_data_bad_3075_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_2
|
crossvul-java_data_good_3075_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid aith subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.forceRemote()
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
this.host.testStart(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// issue a GET on a factory with no auth context, no documents should be returned
this.host.testStart(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email, true);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_1
|
crossvul-java_data_bad_3080_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_5
|
crossvul-java_data_bad_3077_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_0
|
crossvul-java_data_bad_3076_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SynchronizationRequest;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION)) {
handleSynchRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleSynchRequest(Operation op) {
if (op.getAction() != Action.PATCH && op.getAction() != Action.PUT) {
Operation.failActionNotSupported(op);
return;
}
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
SynchronizationRequest synchRequest = op.getBody(SynchronizationRequest.class);
if (synchRequest.kind == null || !synchRequest.kind.equals(Utils.buildKind(SynchronizationRequest.class))) {
op.fail(new IllegalArgumentException(String.format(
"Invalid 'kind' in the request body")));
return;
}
if (!synchRequest.documentSelfLink.equals(this.parent.getSelfLink())) {
op.fail(new IllegalArgumentException("Invalid param in the body: " + synchRequest.documentSelfLink));
return;
}
// Synchronize the FactoryService
if (this.parent instanceof FactoryService) {
((FactoryService)this.parent).synchronizeChildServicesIfOwner(new Operation());
op.complete();
return;
}
if (this.parent instanceof StatelessService) {
op.fail(new IllegalArgumentException("Nothing to synchronize for stateless service: " +
synchRequest.documentSelfLink));
return;
}
// Synchronize the single child service.
synchronizeChildService(this.parent.getSelfLink(), op);
}
private void synchronizeChildService(String link, Operation op) {
// To trigger synchronization of the child-service, we make
// a SYNCH-OWNER request. The request body is an empty document
// with just the documentSelfLink property set to the link
// of the child-service. This is done so that the FactoryService
// routes the request to the DOCUMENT_OWNER.
ServiceDocument d = new ServiceDocument();
d.documentSelfLink = UriUtils.getLastPathSegment(link);
String factoryLink = UriUtils.getParentPath(link);
Operation.CompletionHandler c = (o, e) -> {
if (e != null) {
String msg = String.format("Synchronization failed for service %s with status code %d, message %s",
o.getUri().getPath(), o.getStatusCode(), e.getMessage());
this.parent.getHost().log(Level.WARNING, msg);
op.fail(new IllegalStateException(msg));
return;
}
op.complete();
};
Operation.createPost(this, factoryLink)
.setBody(d)
.setCompletion(c)
.setReferer(getUri())
.setConnectionSharing(true)
.setConnectionTag(ServiceClient.CONNECTION_TAG_SYNCHRONIZATION)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.sendWith(this.parent);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public void setProcessingStage(ProcessingStage initialized) {
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_0
|
crossvul-java_data_bad_3080_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_4
|
crossvul-java_data_bad_3082_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_2
|
crossvul-java_data_bad_3081_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_2
|
crossvul-java_data_good_3083_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_2
|
crossvul-java_data_bad_2469_1
|
package cz.metacentrum.perun.core.impl;
import com.zaxxer.hikari.HikariDataSource;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.Destination;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.DiacriticNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceExistsException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.MaxSizeExceededException;
import cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.MinSizeExceededException;
import cz.metacentrum.perun.core.api.exceptions.NumberNotInRangeException;
import cz.metacentrum.perun.core.api.exceptions.NumbersNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.ParseUserNameException;
import cz.metacentrum.perun.core.api.exceptions.ParserException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.core.api.exceptions.SpaceNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.SpecialCharsNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongPatternException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.blImpl.ModulesUtilsBlImpl;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.text.StringCharacterIterator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utilities.
*/
public class Utils {
private final static Logger log = LoggerFactory.getLogger(Utils.class);
public final static String configurationsLocations = "/etc/perun/";
public static final String TITLE_BEFORE = "titleBefore";
public static final String FIRST_NAME = "firstName";
public static final String LAST_NAME = "lastName";
public static final String TITLE_AFTER = "titleAfter";
private static Properties properties;
public static final Pattern emailPattern = Pattern.compile("^[-_A-Za-z0-9+']+(\\.[-_A-Za-z0-9+']+)*@[-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
private static final Pattern titleBeforePattern = Pattern.compile("^(([\\p{L}]+[.])|(et))$");
private static final Pattern firstNamePattern = Pattern.compile("^[\\p{L}-']+$");
private static final Pattern lastNamePattern = Pattern.compile("^(([\\p{L}-']+)|([\\p{L}][.]))$");
private static final String userPhoneAttribute = "urn:perun:user:attribute-def:def:phone";
private static final String memberPhoneAttribute = "urn:perun:member:attribute-def:def:phone";
/**
* Replaces dangerous characters.
* Replaces : with - and spaces with _.
*
* @param str string to be normalized
* @return normalized string
*/
public static String normalizeString(String str) {
log.trace("Entering normalizeString: str='{}'", str);
return str.replace(':', '-').replace(' ', '_');
}
public static <T> boolean hasDuplicate(List<T> all) {
Set<T> set = new HashSet<>(all.size());
// Set#add returns false if the set does not change, which
// indicates that a duplicate element has been added.
for (T each: all) if (!set.add(each)) return true;
return false;
}
/**
* Joins Strings or any objects into a String. Use as
* <pre>
* List<?> list = Arrays.asList("a", 1, 2.0);
* String s = join(list,",");
* </pre>
* @param collection anything Iterable, like a {@link java.util.List} or {@link java.util.Collection}
* @param separator any separator, like a comma
* @return string with string representations of objects joined by separators
*/
public static String join(Iterable<?> collection, String separator) {
Iterator<?> oIter;
if (collection == null || (!(oIter = collection.iterator()).hasNext()))
return "";
StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next()));
while (oIter.hasNext())
oBuilder.append(separator).append(oIter.next());
return oBuilder.toString();
}
/**
* Returns additionalUserExtSources from the subject. It's used for synchronization from different ExtSources. subjectFromExtSource was obtained from the ExtSource.
*
* @param sess perun session
* @param subjectFromExtSource map with the subject
* @return List<UserExtSource> all additional ExtSources from the subject, returned list will never contain null value
* @throws InternalErrorException
*/
public static List<UserExtSource> extractAdditionalUserExtSources(PerunSession sess, Map<String, String> subjectFromExtSource) throws InternalErrorException {
List<UserExtSource> additionalUserExtSources = new ArrayList<>();
for (String attrName : subjectFromExtSource.keySet()) {
if(attrName != null &&
subjectFromExtSource.get(attrName) != null &&
attrName.startsWith(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING)) {
String login = subjectFromExtSource.get("login");
String[] userExtSourceRaw = subjectFromExtSource.get(attrName).split("\\|"); // Entry contains extSourceName|extSourceType|extLogin[|LoA]
log.debug("Processing additionalUserExtSource {}", subjectFromExtSource.get(attrName));
//Check if the array has at least 3 parts, this is protection against outOfBoundException
if(userExtSourceRaw.length < 3) {
throw new InternalErrorException("There is a missing mandatory part of additional user extSource value when processing it - '" + attrName + "'");
}
String additionalExtSourceName = userExtSourceRaw[0];
String additionalExtSourceType = userExtSourceRaw[1];
String additionalExtLogin = userExtSourceRaw[2];
int additionalExtLoa = 0;
// Loa is not mandatory argument
if (userExtSourceRaw.length>3 && userExtSourceRaw[3] != null) {
try {
additionalExtLoa = Integer.parseInt(userExtSourceRaw[3]);
} catch (NumberFormatException e) {
throw new ParserException("Subject with login [" + login + "] has wrong LoA '" + userExtSourceRaw[3] + "'.", e, "LoA");
}
}
ExtSource additionalExtSource;
if (additionalExtSourceName == null || additionalExtSourceName.isEmpty() ||
additionalExtSourceType == null || additionalExtSourceType.isEmpty() ||
additionalExtLogin == null || additionalExtLogin.isEmpty()) {
log.error("User with login {} has invalid additional userExtSource defined {}.", login, userExtSourceRaw);
} else {
try {
// Try to get extSource, with full extSource object (containg ID)
additionalExtSource = ((PerunBl) sess.getPerun()).getExtSourcesManagerBl().getExtSourceByName(sess, additionalExtSourceName);
} catch (ExtSourceNotExistsException e) {
try {
// Create new one if not exists
additionalExtSource = new ExtSource(additionalExtSourceName, additionalExtSourceType);
additionalExtSource = ((PerunBl) sess.getPerun()).getExtSourcesManagerBl().createExtSource(sess, additionalExtSource, null);
} catch (ExtSourceExistsException e1) {
throw new ConsistencyErrorException("Creating existing extSource: " + additionalExtSourceName);
}
}
// Add additional user extSource
additionalUserExtSources.add(new UserExtSource(additionalExtSource, additionalExtLoa, additionalExtLogin));
}
}
}
return additionalUserExtSources;
}
/**
* Joins Strings or any objects into a String. Use as
* <pre>
* String[] sa = { "a", "b", "c"};
* String s = join(list,",");
* </pre>
* @param objs array of objects
* @param separator any separator, like a comma
* @return string with string representations of objects joined by separators
*/
public static String join(Object[] objs, String separator) {
log.trace("Entering join: objs='{}', separator='{}'", objs, separator);
return join(Arrays.asList(objs),separator);
}
/**
* Integer row mapper
*/
public static final RowMapper<Integer> ID_MAPPER = (resultSet, i) -> resultSet.getInt("id");
/**
* String row mapper
*/
public static final RowMapper<String> STRING_MAPPER = (resultSet, i) -> resultSet.getString("value");
// FIXME prijde odstranit
public static void checkPerunSession(PerunSession sess) throws InternalErrorException {
notNull(sess, "sess");
}
/**
* Creates copy of given Map with Sets as values. The returned object contains a new Map
* and new Sets, the {@link T} objects remain the same.
*
* @param original original Map
* @param <T> parameter
* @return new Map with new Sets as values
*/
public static <T> Map<T, Set<T>> createDeepCopyOfMapWithSets(Map<T, Set<T>> original) {
Map<T, Set<T>> copy = new HashMap<>();
for (T key : original.keySet()) {
Set<T> setCopy = original.get(key) == null ? null : new HashSet<>(original.get(key));
copy.put(key, setCopy);
}
return copy;
}
/**
* Checks whether the object is null or not.
*
* @param e
* @param name
* @throws InternalErrorException which wraps NullPointerException
*/
public static void notNull(Object e, String name) throws InternalErrorException {
if(e == null){
throw new InternalErrorException(new NullPointerException("'" + name + "' is null"));
}
}
/**
* Throws a MinSizeExceededException if the given value does not specified minLength.
* If the value is null then MinSizeExceededException is thrown as well.
*
* @param propertyName name of checked property
* @param minLength minimal length
* @throws MinSizeExceededException when length of actualValue is lower than minLength or null
*/
public static void checkMinLength(String propertyName, String actualValue, int minLength) throws MinSizeExceededException {
if (actualValue == null) {
throw new MinSizeExceededException("The property '" + propertyName + "' does not have a minimal length equal to '" + minLength + "' because it is null.");
}
if (actualValue.length() < minLength) {
throw new MinSizeExceededException("Length of '" + propertyName + "' is too short! MinLength=" + minLength + ", ActualLength=" + actualValue.length());
}
}
/**
* Throws a MaxSizeExceededException if the given value is longer than maxLength.
* If the value is null then nothing happens.
*
* @param propertyName name of checked property
* @param maxLength max length
* @throws MaxSizeExceededException when length of actualValue is higher than maxLength
*/
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException {
if (actualValue == null) {
return;
}
if (actualValue.length() > maxLength) {
throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length());
}
}
/**
* Define, if some entity contain a diacritic symbol.
*
* @param name name of entity
* @throws DiacriticNotAllowedException
*/
public static void checkWithoutDiacritic(String name) throws DiacriticNotAllowedException{
if(!Normalizer.isNormalized(name, Form.NFKD))throw new DiacriticNotAllowedException("Name of the entity is not in the normalized form NFKD (diacritic not allowed)!");
}
/**
* Define, if some entity contain a special symbol
* Special symbol is everything except - numbers, letters and space
*
* @param name name of entity
* @throws SpecialCharsNotAllowedException
*/
public static void checkWithoutSpecialChars(String name) throws SpecialCharsNotAllowedException{
if(!name.matches("^[0-9 \\p{L}]*$")) throw new SpecialCharsNotAllowedException("The special chars in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a special symbol
* Special symbol is everything except - numbers, letters and space (and allowedSpecialChars)
* The allowedSpecialChars are on the end of regular expresion, so the same rule must be observed.
* (example, symbol - must be on the end of string) rules are the same like in regular expresion
*
* @param name name of entity
* @param allowedSpecialChars this String must contain only special chars which are allowed
* @throws SpecialCharsNotAllowedException
*/
public static void checkWithoutSpecialChars(String name, String allowedSpecialChars) throws SpecialCharsNotAllowedException{
if(!name.matches("^([0-9 \\p{L}" + allowedSpecialChars + "])*$")) throw new SpecialCharsNotAllowedException("The special chars (except " + allowedSpecialChars + ") in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a number
*
* @param name
* @throws NumbersNotAllowedException
*/
public static void checkWithoutNumbers(String name) throws NumbersNotAllowedException{
if(!name.matches("^([^0-9])*$")) throw new NumbersNotAllowedException("The numbers in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a space
*
* @param name
* @throws SpaceNotAllowedException
*/
public static void checkWithoutSpaces(String name)throws SpaceNotAllowedException{
if(name.contains(" ")) throw new SpaceNotAllowedException("The spaces in the name of entity are not allowed!");
}
/**
* Define, if some number is in range.
* Example: number 4 is in range 4 - 12, number 3 is not
*
* @param number
* @param lowestValue
* @param highestValue
* @throws NumberNotInRangeException
*/
public static void checkRangeOfNumbers(int number, int lowestValue, int highestValue) throws NumberNotInRangeException {
if(number<lowestValue || number>highestValue) throw new NumberNotInRangeException("Number is not in range, Lowest="+lowestValue+" < Number="+number+" < Highest="+highestValue);
}
/**
* Gets the next number from the sequence. This function hides differences in the databases engines.
*
* @param jdbc
* @param sequenceName
* @return new ID
* @throws InternalErrorException
*/
public static int getNewId(JdbcTemplate jdbc, String sequenceName) throws InternalErrorException {
String dbType;
String url = "";
String query;
// try to deduce database type from jdbc connection metadata
try {
DataSource ds = jdbc.getDataSource();
if (ds instanceof HikariDataSource) {
url = ((HikariDataSource) ds).getJdbcUrl();
}
} catch (Exception e) {
log.error("cannot get JDBC url", e);
}
if (url.contains("hsqldb")) {
dbType = "hsqldb";
} else if (url.contains("oracle")) {
dbType = "oracle";
} else if (url.contains("postgresql")) {
dbType = "postgresql";
} else {
dbType = BeansUtils.getCoreConfig().getDbType();
}
switch (dbType) {
case "oracle":
query = "select " + sequenceName + ".nextval from dual";
break;
case "postgresql":
query = "select nextval('" + sequenceName + "')";
break;
case "hsqldb":
query = "call next value for " + sequenceName + ";";
break;
default:
throw new InternalErrorException("Unsupported DB type");
}
// Decide which type of the JdbcTemplate is provided
try {
Integer i = jdbc.queryForObject(query, Integer.class);
if (i == null) {
throw new InternalErrorException("New ID should not be null.");
}
return i;
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
/**
* Returns current time in millis. Result of this call can then be used by function getRunningTime().
*
* @return current time in millis.
*/
public static long startTimer() {
return System.currentTimeMillis();
}
/**
* Returns difference between startTime and current time in millis.
*
* @param startTime
* @return difference between current time in millis and startTime.
*/
public static long getRunningTime(long startTime) {
return System.currentTimeMillis()-startTime;
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
* @throws ClassNotFoundException
* @throws IOException
*/
public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class<?>> classes = new ArrayList<>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private static String limit(String s,int limit) {
if(s==null) return null;
return s.length() > limit ? s.substring(0, limit) : s;
}
public static User createUserFromNameMap(Map<String, String> name) throws InternalErrorException {
User user = new User();
if (name.get(FIRST_NAME) == null || name.get(LAST_NAME) == null || name.get(FIRST_NAME).isEmpty() || name.get(LAST_NAME).isEmpty()) {
throw new InternalErrorException("First name/last name is either empty or null when creating user");
}
user.setTitleBefore(limit(name.get(TITLE_BEFORE),40));
user.setFirstName(limit(name.get(FIRST_NAME),64));
user.setLastName(limit(name.get(LAST_NAME),64));
user.setTitleAfter(limit(name.get(TITLE_AFTER),40));
return user;
}
/**
* Creates a new instance of User with names initialized from parsed rawName.
* Imposes limit on leghts of fields.
* @see #parseCommonName(String)
* @param rawName raw name
* @param fullNameRequired if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
* @return user
*/
public static User parseUserFromCommonName(String rawName, boolean fullNameRequired) throws ParseUserNameException {
Map<String, String> m = parseCommonName(rawName, fullNameRequired);
return createUserFromNameMap(m);
}
/**
* @see Utils.parseCommonName(String rawName, boolean fullNameRequired) - where fullNameRequired is false
*/
public static Map<String, String> parseCommonName(String rawName) {
try {
return Utils.parseCommonName(rawName, false);
} catch (ParseUserNameException ex) {
throw new InternalErrorException("Unexpected behavior while parsing user name without full name requirement.");
}
}
/**
* Try to parse rawName to keys: "titleBefore" "firstName" "lastName" "titleAfter"
*
* If rawName is null or empty, return map with empty values of all keys.
*
* Parsing procedure:
* 1] prepare list of parts by replacing all characters "," and "_" by spaces
* 2] change all sequence of invisible characters (space, tabulator etc.) to one space
* 3] one by one try to parsing parts from the list
* - A] try to find all titleBefore parts
* - B] try to find one firstName part
* - C] try to find all lastName parts
* - D] if the rest is not lastName so save it to the title after
*
* Example of parsing rawName:
* 1] rawName = "Mgr. et Mgr. Petr_Jiri R. Sojka, Ph.D., CSc."
* 2] convert all ',' and '_' to spaces: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc."
* 3] convert more than 1 invisible char to 1 space: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc."
* 4] parse string to list of parts by space: ListOfParts= ["Mgr.","et","Mgr.","Petr","Jiri","R.","Sojka","Ph.D.","CSc."]
* 5] first fill everything what can be in title before: titleBefore="Mgr. et Mgr."
* 6] then fill everything what can be in first name (maximum 1 part): firstName="Petr"
* 7] then fill everything what can be in last name: lastName="Jiri R. Sojka"
* 8] everything else put to the title after: titleAfter="Ph.D. CSc."
* 9] put these variables to map like key=value, for ex.: Map[titleBefore="Mgr. et Mgr.",firstName="Petr", ... ] and return this map
*
* @param rawName name to parse
* @param fullNameRequired if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
* @return map string to string where are 4 keys (titleBefore,titleAfter,firstName and lastName) with their values (value can be null)
* @throws ParseUserNameException when method was unable to parse both first name and last name from the rawName
*/
public static Map<String, String> parseCommonName(String rawName, boolean fullNameRequired) throws ParseUserNameException {
// prepare variables and result map
Map<String, String> parsedName = new HashMap<>();
String titleBefore = "";
String firstName = "";
String lastName = "";
String titleAfter = "";
if (rawName != null && !rawName.isEmpty()) {
// replace all ',' and '_' characters for ' ' for rawName
rawName = rawName.replaceAll("[,_]", " ");
// replace all invisible chars in row for ' '
rawName = rawName.replaceAll("\\s+", " ").trim();
// split parts by space
List<String> nameParts = new ArrayList<>(Arrays.asList(rawName.split(" ")));
// if length of nameParts is 1, save it to the lastName
if(nameParts.size() == 1) {
lastName = nameParts.get(0);
// if length of nameParts is more than 1, try to choose which part belong to which value
} else {
// join title before name to single string with ' ' as delimiter
titleBefore = parsePartOfName(nameParts, new StringJoiner(" "), titleBeforePattern);
// get first name as a next name part if pattern matches and nameParts are not empty
if (!nameParts.isEmpty()) firstName = parsePartOfName(nameParts, new StringJoiner(" "), firstNamePattern);
// join last names to single string with ' ' as delimiter
if (!nameParts.isEmpty()) lastName = parsePartOfName(nameParts, new StringJoiner(" "), lastNamePattern);
// if any nameParts are left join them to one string with ' ' as delimiter and assume they are titles after name
if (!nameParts.isEmpty()) {
StringJoiner titleAfterBuilder = new StringJoiner(" ");
for (String namePart : nameParts) {
titleAfterBuilder.add(namePart);
}
titleAfter = titleAfterBuilder.toString();
}
}
}
// add variables to map, empty string means null
if (titleBefore.isEmpty()) titleBefore = null;
parsedName.put(TITLE_BEFORE, titleBefore);
if (firstName.isEmpty()) firstName = null;
parsedName.put(FIRST_NAME, firstName);
if (lastName.isEmpty()) lastName = null;
parsedName.put(LAST_NAME, lastName);
if (titleAfter.isEmpty()) titleAfter = null;
parsedName.put(TITLE_AFTER, titleAfter);
if(fullNameRequired) {
if (parsedName.get(FIRST_NAME) == null)
throw new ParseUserNameException("Unable to parse first name from text.", rawName);
if (parsedName.get(LAST_NAME) == null)
throw new ParseUserNameException("Unable to parse last name from text.", rawName);
}
return parsedName;
}
private static String parsePartOfName(List<String> nameParts, StringJoiner result, Pattern pattern) {
Matcher matcher = pattern.matcher(nameParts.get(0));
// if the matcher does not match continue to the next part of the name
if (!matcher.matches()) return result.toString();
result.add(nameParts.get(0));
nameParts.remove(0);
// when nameParts are depleted or firstName was found there is no reason to continue the recursion
if (nameParts.isEmpty() || pattern.equals(firstNamePattern)) return result.toString();
// continue the recursion to find the next part
return parsePartOfName(nameParts, result, pattern);
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
* @throws ClassNotFoundException
*/
private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
}
return classes;
}
/**
* Return true, if char on position in text is escaped by '\' Return false,
* if not.
*
* @param text text in which will be searching
* @param position position in text <0-text.length>
* @return true if char is escaped, false if not
*/
public static boolean isEscaped(String text, int position) {
boolean escaped = false;
while (text.charAt(position) == '\\') {
escaped = !escaped;
position--;
if (position < 0) {
return escaped;
}
}
return escaped;
}
/**
* Serialize map to string
*
* @param map
* @return string of escaped map
*/
public static String serializeMapToString(Map<String, String> map) {
if(map == null) return "\\0";
Map<String, String> attrNew = new HashMap<>(map);
Set<String> keys = new HashSet<>(attrNew.keySet());
for(String s: keys) {
attrNew.put("<" + BeansUtils.createEscaping(s) + ">", "<" + BeansUtils.createEscaping(attrNew.get(s)) + ">");
attrNew.remove(s);
}
return attrNew.toString();
}
public static Attribute copyAttributeToViAttributeWithoutValue(Attribute copyFrom, Attribute copyTo) {
copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt());
copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy());
copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt());
copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy());
return copyTo;
}
public static Attribute copyAttributeToVirtualAttributeWithValue(Attribute copyFrom, Attribute copyTo) {
copyTo.setValue(copyFrom.getValue());
copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt());
copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy());
copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt());
copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy());
return copyTo;
}
/**
* Method generates strings by pattern.
* The pattern is string with square brackets, e.g. "a[1-3]b". Then the content of the brackets
* is distributed, so the list is [a1b, a2b, a3c].
* Multibrackets are aslo allowed. For example "a[00-01]b[90-91]c" generates [a00b90c, a00b91c, a01b90c, a01b91c].
*
* @param pattern
* @return list of all generated strings
*/
public static List<String> generateStringsByPattern(String pattern) throws WrongPatternException {
List<String> result = new ArrayList<>();
// get chars between the brackets
List<String> values = new ArrayList<>(Arrays.asList(pattern.split("\\[[^]]*]")));
// get content of the brackets
List<String> generators = new ArrayList<>();
Pattern generatorPattern = Pattern.compile("\\[([^]]*)]");
Matcher m = generatorPattern.matcher(pattern);
while (m.find()) {
generators.add(m.group(1));
}
// if values strings contain square brackets, wrong syntax, abort
for (String value: values) {
if (value.contains("]") || (value.contains("["))) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much closing brackets.");
}
}
// if generators strings contain square brackets, wrong syntax, abort
for (String generator: generators) {
if (generator.contains("]") || (generator.contains("["))) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much opening brackets.");
}
}
// list, that contains list for each generator, with already generated numbers
List<List<String>> listOfGenerated = new ArrayList<>();
Pattern rangePattern = Pattern.compile("^(\\d+)-(\\d+)$");
for (String range: generators) {
m = rangePattern.matcher(range);
if (m.find()) {
String start = m.group(1);
String end = m.group(2);
int startNumber;
int endNumber;
try {
startNumber = Integer.parseInt(start);
endNumber = Integer.parseInt(end);
} catch (NumberFormatException ex) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Wrong format of the range.");
}
// if end is before start -> abort
if (startNumber > endNumber) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Start number has to be lower than end number.");
}
// find out, how many zeros are before start number
int zerosInStart = 0;
int counter = 0;
while ( (start.charAt(counter) == '0') && (counter < start.length()-1) ) {
zerosInStart++;
counter++;
}
String zeros = start.substring(0, zerosInStart);
int oldNumberOfDigits = String.valueOf(startNumber).length();
// list of already generated numbers
List<String> generated = new ArrayList<>();
while (endNumber >= startNumber) {
// keep right number of zeros before number
if (String.valueOf(startNumber).length() == oldNumberOfDigits +1) {
if (!zeros.isEmpty()) zeros = zeros.substring(1);
}
generated.add(zeros + startNumber);
oldNumberOfDigits = String.valueOf(startNumber).length();
startNumber++;
}
listOfGenerated.add(generated);
} else {
// range is not in the format number-number -> abort
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. The format numer-number not found.");
}
}
// add values among the generated numbers as one item lists
List<List<String>> listOfGeneratorsAndValues = new ArrayList<>();
int index = 0;
for (List<String> list : listOfGenerated) {
if (index < values.size()) {
List<String> listWithValue = new ArrayList<>();
listWithValue.add(values.get(index));
listOfGeneratorsAndValues.add(listWithValue);
index++;
}
listOfGeneratorsAndValues.add(list);
}
// complete list with remaining values
for (int i = index; i < values.size(); i++) {
List<String> listWithValue = new ArrayList<>();
listWithValue.add(values.get(i));
listOfGeneratorsAndValues.add(listWithValue);
}
// generate all posibilities
return getCombinationsOfLists(listOfGeneratorsAndValues);
}
/**
* Method generates all combinations of joining of strings.
* It respects given order of lists.
* Example: input: [[a,b],[c,d]], output: [ac,ad,bc,bd]
* @param lists list of lists, which will be joined
* @return all joined strings
*/
private static List<String> getCombinationsOfLists(List<List<String>> lists) {
if (lists.isEmpty()) {
// this should not happen
return new ArrayList<>();
}
if (lists.size() == 1) {
return lists.get(0);
}
List<String> result = new ArrayList<>();
List<String> list = lists.remove(0);
// get recursively all posibilities without first list
List<String> posibilities = getCombinationsOfLists(lists);
// join all strings from first list with the others
for (String item: list) {
if (posibilities.isEmpty()) {
result.add(item);
} else {
for (String itemToConcat : posibilities) {
result.add(item + itemToConcat);
}
}
}
return result;
}
/**
* Return encrypted version of input in UTF-8 by HmacSHA256
*
* @param input input to encrypt
* @return encrypted value
*/
public static String getMessageAuthenticationCode(String input) {
if (input == null)
throw new NullPointerException("input must not be null");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(BeansUtils.getCoreConfig().getMailchangeSecretKey().getBytes(StandardCharsets.UTF_8),"HmacSHA256"));
byte[] macbytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
return new BigInteger(macbytes).toString(Character.MAX_RADIX);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Send validation email related to requested change of users preferred email.
*
* @param user user to change preferred email for
* @param url base URL of running perun instance passed from RPC
* @param email new email address to send notification to
* @param changeId ID of change request in DB
* @param subject Template subject or null
* @param content Template message or null
* @throws InternalErrorException
*/
public static void sendValidationEmail(User user, String url, String email, int changeId, String subject, String content) throws InternalErrorException {
// create mail sender
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("localhost");
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null ||subject.isEmpty()) {
message.setSubject("["+instanceName+"] New email address verification");
} else {
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// get validation link params
String i = Integer.toString(changeId, Character.MAX_RADIX);
String m = Utils.getMessageAuthenticationCode(i);
try {
// !! There is a hard-requirement for Perun instance
// to host GUI on same server as RPC like: "serverUrl/gui/"
URL urlObject = new URL(url);
// use default if unknown rpc path
String path = "/gui/";
if (urlObject.getPath().contains("/krb/")) {
path = "/krb/gui/";
} else if (urlObject.getPath().contains("/fed/")) {
path = "/fed/gui/";
} else if (urlObject.getPath().contains("/cert/")) {
path = "/cert/gui/";
}
StringBuilder link = new StringBuilder();
link.append(urlObject.getProtocol());
link.append("://");
link.append(urlObject.getHost());
link.append(path);
link.append("?i=");
link.append(URLEncoder.encode(i, "UTF-8"));
link.append("&m=");
link.append(URLEncoder.encode(m, "UTF-8"));
link.append("&u=" + user.getId());
// Build message
String text = "Dear "+user.getDisplayName()+",\n\nWe've received request to change your preferred email address to: "+email+"."+
"\n\nTo confirm this change please use link below:\n\n"+link+"\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (content == null || content.isEmpty()) {
message.setText(text);
} else {
content = content.replace("{link}",link);
message.setText(content);
}
mailSender.send(message);
} catch (UnsupportedEncodingException ex) {
throw new InternalErrorException("Unable to encode validation URL for mail change.", ex);
} catch (MalformedURLException ex) {
throw new InternalErrorException("Not valid URL of running Perun instance.", ex);
}
}
/**
* Sends email with link to non-authz password reset GUI where user
* can reset forgotten password
*
* @param user user to send notification for
* @param email user's email to send notification to
* @param namespace namespace to reset password in
* @param url base URL of Perun instance
* @param id ID of pwd reset request
* @param messageTemplate message of the email
* @param subject subject of the email
* @throws InternalErrorException
*/
public static void sendPasswordResetEmail(User user, String email, String namespace, String url, int id, String messageTemplate, String subject) throws InternalErrorException {
// create mail sender
JavaMailSender mailSender = BeansUtils.getDefaultMailSender();
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null) {
message.setSubject("[" + instanceName + "] Password reset in namespace: " + namespace);
} else {
subject = subject.replace("{namespace}", namespace);
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// get validation link params
String i = cipherInput(String.valueOf(user.getId()), false);
String m = cipherInput(String.valueOf(id), false);
try {
URL urlObject = new URL(url);
StringBuilder link = new StringBuilder();
link.append(urlObject.getProtocol());
link.append("://");
link.append(urlObject.getHost());
// reset link uses non-authz
link.append("/non/pwd-reset/");
link.append("?i=");
link.append(URLEncoder.encode(i, "UTF-8"));
link.append("&m=");
link.append(URLEncoder.encode(m, "UTF-8"));
// append login-namespace so GUI is themes and password checked by namespace rules
link.append("&login-namespace=");
link.append(URLEncoder.encode(namespace, "UTF-8"));
//validity formatting
String validity = Integer.toString(BeansUtils.getCoreConfig().getPwdresetValidationWindow());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now().plusHours(Integer.parseInt(validity));
String validityFormatted = dtf.format(localDateTime);
// Build message en
String textEn = "Dear " + user.getDisplayName() + ",\n\nWe've received request to reset your password in namespace \"" + namespace + "\"." +
"\n\nPlease visit the link below, where you can set new password:\n\n" + link + "\n\n" +
"Link is valid till " + validityFormatted + "\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (messageTemplate == null) {
message.setText(textEn);
} else {
// allow enforcing per-language links
if (messageTemplate.contains("{link-")) {
Pattern pattern = Pattern.compile("\\{link-[^}]+}");
Matcher matcher = pattern.matcher(messageTemplate);
while (matcher.find()) {
// whole "{link-something}"
String toSubstitute = matcher.group(0);
String langLink = link.toString();
Pattern namespacePattern = Pattern.compile("-(.*?)}");
Matcher m2 = namespacePattern.matcher(toSubstitute);
if (m2.find()) {
// only language "cs", "en",...
String lang = m2.group(1);
langLink = langLink + "&locale=" + lang;
}
messageTemplate = messageTemplate.replace(toSubstitute, langLink);
}
} else {
messageTemplate = messageTemplate.replace("{link}", link);
}
messageTemplate = messageTemplate.replace("{displayName}", user.getDisplayName());
messageTemplate = messageTemplate.replace("{namespace}", namespace);
messageTemplate = messageTemplate.replace("{validity}", validityFormatted);
message.setText(messageTemplate);
}
mailSender.send(message);
} catch (MailException ex) {
throw new InternalErrorException("Unable to send mail for password reset.", ex);
} catch (UnsupportedEncodingException ex) {
throw new InternalErrorException("Unable to encode URL for password reset.", ex);
} catch (MalformedURLException ex) {
throw new InternalErrorException("Not valid URL of running Perun instance.", ex);
}
}
/**
* Sends email to user confirming his password was changed.
*
* @param user user to send notification for
* @param email user's email to send notification to
* @param namespace namespace the password was re-set
* @param login login of user
* @param subject Subject from template or null
* @param content Message from template or null
*/
public static void sendPasswordResetConfirmationEmail(User user, String email, String namespace, String login, String subject, String content) {
// create mail sender
JavaMailSender mailSender = BeansUtils.getDefaultMailSender();
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null || subject.isEmpty()) {
message.setSubject("["+instanceName+"] Password reset in namespace: "+namespace);
} else {
subject = subject.replace("{namespace}", namespace);
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// Build message
String text = "Dear "+user.getDisplayName()+",\n\nyour password in namespace \""+namespace+"\" was successfully reset."+
"\n\nThis message is automatically sent to all your email addresses registered in "+instanceName+" in order to prevent malicious password reset without your knowledge.\n\n" +
"If you didn't request / perform password reset, please notify your administrators and support at "+BeansUtils.getCoreConfig().getMailchangeBackupFrom()+" to resolve this security issue.\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (content == null || content.isEmpty()) {
message.setText(text);
} else {
content = content.replace("{displayName}", user.getDisplayName());
content = content.replace("{namespace}", namespace);
content = content.replace("{login}", login);
content = content.replace("{instanceName}", instanceName);
message.setText(content);
}
mailSender.send(message);
}
/**
* Return en/decrypted version of input using AES/CBC/PKCS5PADDING cipher.
* Perun's internal secretKey and initVector are used (you can configure them in
* perun.properties file).
*
* @param plainText text to en/decrypt
* @param decrypt TRUE = decrypt input / FALSE = encrypt input
* @return en/decrypted text
* @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException if anything fails
*/
public static String cipherInput(String plainText, boolean decrypt) throws InternalErrorException {
try {
String encryptionKey = BeansUtils.getCoreConfig().getPwdresetSecretKey();
String initVector = BeansUtils.getCoreConfig().getPwdresetInitVector();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecretKeySpec k = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8), "AES");
c.init((decrypt) ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, k, new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8)));
if (decrypt) {
byte[] bytes = Base64.decodeBase64(plainText.getBytes(StandardCharsets.UTF_8));
return new String(c.doFinal(bytes), StandardCharsets.UTF_8);
} else {
byte[] bytes = Base64.encodeBase64(c.doFinal(plainText.getBytes(StandardCharsets.UTF_8)));
return new String(bytes, StandardCharsets.UTF_8);
}
} catch (Exception ex) {
throw new InternalErrorException("Error when encrypting message", ex);
}
}
/**
* Checks whether the destination is not null and is of the right type.
*
* @param destination destination to check
* @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException if destination is null
* @throws cz.metacentrum.perun.core.api.exceptions.WrongPatternException if destination is not of the right type
*/
public static void checkDestinationType(Destination destination) throws InternalErrorException, WrongPatternException {
if (destination == null) {
throw new InternalErrorException("Destination is null.");
}
String destinationType = destination.getType();
if ((!Objects.equals(destinationType, Destination.DESTINATIONHOSTTYPE)
&& (!Objects.equals(destinationType, Destination.DESTINATIONEMAILTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONSEMAILTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONURLTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONUSERHOSTTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONUSERHOSTPORTTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONSERVICESPECIFICTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONWINDOWS))
&& (!Objects.equals(destinationType, Destination.DESTINATIONWINDOWSPROXY)))) {
throw new WrongPatternException("Destination type " + destinationType + " is not supported.");
}
}
/**
* Sends SMS to the phone number of a user with the given message.
* The phone number is taken from the user attribute urn:perun:user:attribute-def:def:phone.
*
* @param sess session
* @param user receiver of the message
* @param message sms message to send
* @throws InternalErrorException when the attribute value cannot be found or is broken
* @throws cz.metacentrum.perun.core.api.exceptions.PrivilegeException when the actor has not right to get the attribute
* @throws cz.metacentrum.perun.core.api.exceptions.UserNotExistsException when given user does not exist
*/
public static void sendSMS(PerunSession sess, User user, String message) throws InternalErrorException, PrivilegeException, UserNotExistsException {
if (user == null) {
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException("user is null");
}
if (message == null) {
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException("message is null");
}
String telNumber;
try {
telNumber = (String) sess.getPerun().getAttributesManager().getAttribute(sess, user, userPhoneAttribute).getValue();
} catch (AttributeNotExistsException ex ) {
log.error("Sendig SMS with text \"{}\" to user {} failed: cannot get tel. number.", message, user );
throw new InternalErrorException("The attribute " + userPhoneAttribute + " has not been found.", ex);
} catch (WrongAttributeAssignmentException ex) {
log.error("Sendig SMS with text \"{}\" to user {} failed: cannot get tel. number.", message, user );
throw new InternalErrorException("The attribute " + userPhoneAttribute + " has not been found in user attributes.", ex);
}
sendSMS(telNumber, message);
}
/**
* Sends SMS to the phone number of a member with the given message.
* The phone number is taken from the user attribute urn:perun:member:attribute-def:def:phone.
*
* @param sess session
* @param member receiver of the message
* @param message sms message to send
* @throws InternalErrorException when the attribute value cannot be found or is broken
* @throws cz.metacentrum.perun.core.api.exceptions.PrivilegeException when the actor has not right to get the attribute
* @throws cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException when given member does not exist
*/
public static void sendSMS(PerunSession sess, Member member, String message) throws InternalErrorException, PrivilegeException, MemberNotExistsException {
String telNumber;
try {
telNumber = (String) sess.getPerun().getAttributesManager().getAttribute(sess, member, memberPhoneAttribute).getValue();
} catch (AttributeNotExistsException ex) {
log.error("Sendig SMS with text \"{}\" to member {} failed: cannot get tel. number.", message, member );
throw new InternalErrorException("The attribute " + memberPhoneAttribute + " has not been found.", ex);
} catch (WrongAttributeAssignmentException ex) {
log.error("Sendig SMS with text \"{}\" to member {} failed: cannot get tel. number.", message, member );
throw new InternalErrorException("The attribute " + memberPhoneAttribute + " has not been found in user attributes.", ex);
}
sendSMS(telNumber, message);
}
/**
* Sends SMS to the phone number with the given message.
* The sending provides external program for sending sms.
* Its path is saved in the perun property perun.sms.program.
*
* @param telNumber phone number of the receiver
* @param message sms message to send
* @throws InternalErrorException when there is something wrong with external program
* @throws IllegalArgumentException when the phone or message has a wrong format
*/
public static void sendSMS(String telNumber, String message) throws InternalErrorException {
log.debug("Sending SMS with text \"{}\" to tel. number {}.", message, telNumber);
try {
// create properties list
List<String> processProperties = new ArrayList<>();
// pass the location of external program for sending sms
processProperties.add(BeansUtils.getCoreConfig().getSmsProgram());
// pass program options
processProperties.add("-p");
processProperties.add(telNumber);
processProperties.add("-m");
processProperties.add(message);
// execute
ProcessBuilder pb = new ProcessBuilder(processProperties);
Process process;
process = pb.start();
int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ex) {
String errMsg = "The external process for sending sms was interrupted.";
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException(errMsg, ex);
}
// handle response
if (exitValue == 0) {
// successful
log.debug("SMS with text \"{}\" to tel. number {} successfully sent.", message, telNumber);
} else if ((exitValue == 1) || (exitValue == 2)) {
// users fault
String errMsg = getStringFromInputStream(process.getErrorStream());
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException(errMsg);
} else if (exitValue > 2) {
// internal fault
String errMsg = getStringFromInputStream(process.getErrorStream());
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException(errMsg);
}
} catch (IOException ex) {
log.warn("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException("Cannot access the sms external application.", ex);
}
}
/**
* Get BigDecimal number like '1024' in Bytes and create better readable
* String with metric value like '1K' where K means KiloBytes.
*
* Use M,G,T,P,E like multipliers of 1024.
*
* If quota is not dividable by 1024 use B (Bytes) without dividing.
*
* @param quota in big natural number
* @return string with number and metric
*/
public static String bigDecimalBytesToReadableStringWithMetric(BigDecimal quota) throws InternalErrorException {
if(quota == null) throw new InternalErrorException("Quota in BigDecimal can't be null if we want to convert it to number with metric.");
//Prepare variable for result
String stringWithMetric;
//Try to divide quota to get result module 1024^x = 0 where X is in [K-0,M-1,G-2,T-3,P-4,E-5]
//If module is bigger than 0, try x-1
if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.E)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^5
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.E)).stripTrailingZeros().toPlainString() + "E";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.P)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^4
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.P)).stripTrailingZeros().toPlainString() + "P";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.T)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^3
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.T)).stripTrailingZeros().toPlainString() + "T";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.G)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^2
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.G)).stripTrailingZeros().toPlainString() + "G";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.M)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^1
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.M)).stripTrailingZeros().toPlainString() + "M";
} else {
//can't be diveded by 1024^x where x>0 so let it be in the format like it already is, convert it to BigInteger without fractional part
stringWithMetric = quota.toBigInteger().toString() + "K";
}
//return result format with metric
return stringWithMetric;
}
private static String getStringFromInputStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
return out.toString();
}
/**
* IMPORTANT: this method not convert utf to ascii, just try to convert some problematic
* chars to UTF and others change to '?'!!!
*
* @param s
* @return converted string from ascii to something near utf
*/
public synchronized static String utftoasci(String s){
final StringBuilder sb = new StringBuilder( s.length() * 2 );
final StringCharacterIterator iterator = new StringCharacterIterator( s );
char ch = iterator.current();
while( ch != StringCharacterIterator.DONE ){
if(Character.getNumericValue(ch)>=0){
sb.append( ch );
}else{
boolean f=false;
if(Character.toString(ch).equals("Ê")){sb.append("E");f=true;}
if(Character.toString(ch).equals("È")){sb.append("E");f=true;}
if(Character.toString(ch).equals("ë")){sb.append("e");f=true;}
if(Character.toString(ch).equals("é")){sb.append("e");f=true;}
if(Character.toString(ch).equals("è")){sb.append("e");f=true;}
if(Character.toString(ch).equals("Â")){sb.append("A");f=true;}
if(Character.toString(ch).equals("ä")){sb.append("a");f=true;}
if(Character.toString(ch).equals("ß")){sb.append("ss");f=true;}
if(Character.toString(ch).equals("Ç")){sb.append("C");f=true;}
if(Character.toString(ch).equals("Ö")){sb.append("O");f=true;}
if(Character.toString(ch).equals("º")){sb.append("");f=true;}
if(Character.toString(ch).equals("ª")){sb.append("");f=true;}
if(Character.toString(ch).equals("º")){sb.append("");f=true;}
if(Character.toString(ch).equals("Ñ")){sb.append("N");f=true;}
if(Character.toString(ch).equals("É")){sb.append("E");f=true;}
if(Character.toString(ch).equals("Ä")){sb.append("A");f=true;}
if(Character.toString(ch).equals("Å")){sb.append("A");f=true;}
if(Character.toString(ch).equals("Ü")){sb.append("U");f=true;}
if(Character.toString(ch).equals("ö")){sb.append("o");f=true;}
if(Character.toString(ch).equals("ü")){sb.append("u");f=true;}
if(Character.toString(ch).equals("á")){sb.append("a");f=true;}
if(Character.toString(ch).equals("Ó")){sb.append("O");f=true;}
if(Character.toString(ch).equals("ě")){sb.append("e");f=true;}
if(Character.toString(ch).equals("Ě")){sb.append("E");f=true;}
if(Character.toString(ch).equals("š")){sb.append("s");f=true;}
if(Character.toString(ch).equals("Š")){sb.append("S");f=true;}
if(Character.toString(ch).equals("č")){sb.append("c");f=true;}
if(Character.toString(ch).equals("Č")){sb.append("C");f=true;}
if(Character.toString(ch).equals("ř")){sb.append("r");f=true;}
if(Character.toString(ch).equals("Ř")){sb.append("R");f=true;}
if(Character.toString(ch).equals("ž")){sb.append("z");f=true;}
if(Character.toString(ch).equals("Ž")){sb.append("Z");f=true;}
if(Character.toString(ch).equals("ý")){sb.append("y");f=true;}
if(Character.toString(ch).equals("Ý")){sb.append("Y");f=true;}
if(Character.toString(ch).equals("í")){sb.append("i");f=true;}
if(Character.toString(ch).equals("Í")){sb.append("I");f=true;}
if(Character.toString(ch).equals("ó")){sb.append("o");f=true;}
if(Character.toString(ch).equals("ú")){sb.append("u");f=true;}
if(Character.toString(ch).equals("Ú")){sb.append("u");f=true;}
if(Character.toString(ch).equals("ů")){sb.append("u");f=true;}
if(Character.toString(ch).equals("Ů")){sb.append("U");f=true;}
if(Character.toString(ch).equals("Ň")){sb.append("N");f=true;}
if(Character.toString(ch).equals("ň")){sb.append("n");f=true;}
if(Character.toString(ch).equals("Ť")){sb.append("T");f=true;}
if(Character.toString(ch).equals("ť")){sb.append("t");f=true;}
if(Character.toString(ch).equals(" ")){sb.append(" ");f=true;}
if(!f){
sb.append("?");
}
}
ch = iterator.next();
}
return sb.toString();
}
/**
* Convert input string (expected UTF-8) to ASCII if possible.
* Any non-ASCII character is replaced by replacement parameter.
*
* @param input String to convert from UTF-8 to ASCII.
* @param replacement Replacement character used for all non-ASCII chars in input.
* @return converted string from ascii to something near utf
*/
public synchronized static String toASCII(String input, Character replacement) {
String normalizedOutput = "";
// take unicode characters one by one and normalize them
for ( int i=0; i<input.length(); i++ ) {
char c = input.charAt(i);
// normalize a single unicode character, then remove every non-ascii symbol (like accents)
String normalizedChar = Normalizer.normalize(String.valueOf(c) , Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
if ( ! normalizedChar.isEmpty() ) {
// if there is a valid ascii representation, use it
normalizedOutput += normalizedChar;
} else {
// otherwise replace character with an "replacement"
normalizedOutput += replacement;
}
}
return normalizedOutput;
}
/**
* Determine if attribute is large (can contain value over 4kb).
*
* @param sess perun session
* @param attribute attribute to be checked
* @return true if the attribute is large
*/
public static boolean isLargeAttribute(PerunSession sess, AttributeDefinition attribute) {
return (attribute.getType().equals(LinkedHashMap.class.getName()) ||
attribute.getType().equals(BeansUtils.largeStringClassName) ||
attribute.getType().equals(BeansUtils.largeArrayListClassName));
}
/**
* Extends given date by given period.
*
* @param localDate date to be extended
* @param period period used to extend date
* @throws InternalErrorException when the period has wrong format,
* allowed format is given by regex "\\+([0-9]+)([dmy]?)"
*/
public static LocalDate extendDateByPeriod(LocalDate localDate, String period) throws InternalErrorException {
// We will add days/months/years
Pattern p = Pattern.compile("\\+([0-9]+)([dmy]?)");
Matcher m = p.matcher(period);
if (m.matches()) {
String countString = m.group(1);
int amount = Integer.valueOf(countString);
String dmyString = m.group(2);
switch (dmyString) {
case "d":
return localDate.plusDays(amount);
case "m":
return localDate.plusMonths(amount);
case "y":
return localDate.plusYears(amount);
default:
throw new InternalErrorException("Wrong format of period. Period: " + period);
}
} else {
throw new InternalErrorException("Wrong format of period. Period: " + period);
}
}
/**
* Returns closest future LocalDate based on values given by matcher.
* If returned value should fall to 29. 2. of non-leap year, the date is extended to 28. 2. instead.
*
* @param matcher matcher with day and month values
* @return Extended date.
*/
public static LocalDate getClosestExpirationFromStaticDate(Matcher matcher) {
int day = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
// We must detect if the extension date is in current year or in a next year (we use year 2000 in comparison because it is a leap year)
LocalDate extensionDate = LocalDate.of(2000, month, day);
// check if extension is next year
// in case of static date being today's date, we want to extend to next year (that's why we use the negation later)
boolean extensionInThisYear = LocalDate.of(2000, LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth()).isBefore(extensionDate);
// Get current year
int year = LocalDate.now().getYear();
if (!extensionInThisYear) {
// Add year to get next year
year++;
}
// Set the date to which the membership should be extended, can be changed if there was grace period, see next part of the code
if (day == 29 && month == 2 && !LocalDate.of(year, 1,1).isLeapYear()) {
// If extended date is 29. 2. of non-leap year, the date is set to 28. 2.
extensionDate = LocalDate.of(year, 2, 28);
} else {
extensionDate = LocalDate.of(year, month, day);
}
return extensionDate;
}
/**
* Prepares grace period date by values from given matcher.
* @param matcher matcher
* @return pair of field(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS) and amount
* @throws InternalErrorException when given matcher contains invalid data
* @throws IllegalArgumentException when matcher does not match gracePeriod format
*/
public static Pair<Integer, TemporalUnit> prepareGracePeriodDate(Matcher matcher) throws InternalErrorException {
if (!matcher.matches()) {
throw new IllegalArgumentException("Wrong format of gracePeriod.");
}
String countString = matcher.group(1);
int amount = Integer.valueOf(countString);
TemporalUnit field;
String dmyString = matcher.group(2);
switch (dmyString) {
case "d":
field = ChronoUnit.DAYS;
break;
case "m":
field = ChronoUnit.MONTHS;
break;
case "y":
field = ChronoUnit.YEARS;
break;
default:
throw new InternalErrorException("Wrong format of gracePeriod.");
}
return new Pair<>(amount, field);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_2469_1
|
crossvul-java_data_good_3078_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_0
|
crossvul-java_data_good_3080_6
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_6
|
crossvul-java_data_bad_3079_6
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
@Override
protected void configureLoggerFormatter(Logger logger) {
super.configureLoggerFormatter(logger);
// override with formatters for VerificationHost
// if custom formatter has already set, do NOT replace it.
for (Handler h : logger.getParent().getHandlers()) {
if (Objects.equals(h.getFormatter(), LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.NORMAL_FORMAT);
} else if (Objects.equals(h.getFormatter(), COLOR_LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.COLORED_FORMAT);
}
}
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getBody(ServiceErrorResponse.class);
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = Utils.getNowMicrosUtc() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getOperationTimeoutMicros();
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
log("Starting query with options:%s, resultLimit: %d",
create.querySpec.options,
create.querySpec.resultLimit);
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(10))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QueryTask.QuerySpecification spec, long documentCount, long expectedResultCount) {
long start = Utils.getNowMicrosUtc();
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = Utils.getNowMicrosUtc();
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.getNowMicrosUtc() + getOperationTimeoutMicros());
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
ServiceStats stats = this.getServiceState(
null, ServiceStats.class, UriUtils.buildStatsUri(serviceUri));
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
private void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> void doPutPerService(List<Service> services)
throws Throwable {
doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> void doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> void doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> void doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PUT, count, properties, services);
}
public void doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getMaintenanceIntervalMicros();
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri).setReferer(getReferer());
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
send(putClone);
});
} else if (properties.contains(TestProperty.CALLBACK_SEND)) {
updateOp.toggleOption(OperationOption.SEND_WITH_CALLBACK, true);
send(updateOp.setBody(b));
} else {
send(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
} else {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum)
throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
setNodeGroupQuorum(quorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
Date exp = getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (quorum != ns.membershipQuorum) {
isConverged = false;
}
}
}
resetAuthorizationContext();
if (isConverged) {
log("converged");
return;
}
Thread.sleep(500);
}
waitForNodeSelectorQuorumConvergence(ServiceUriPaths.DEFAULT_NODE_SELECTOR, quorum);
resetAuthorizationContext();
throw new TimeoutException();
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri) {
ServiceStats stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\tAvg\t\tTotal\t\t\tName%n"));
for (ServiceStat st : stats.entries.values()) {
logStat(uri, st, sb);
}
log(sb.toString());
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.getNowMicrosUtc() + host.getOperationTimeoutMicros();
do {
Thread.sleep(2000);
try {
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_6
|
crossvul-java_data_good_3083_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
OperationContext.setAuthorizationContext(null);
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
OperationContext.setAuthorizationContext(null);
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_1
|
crossvul-java_data_bad_3077_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_2
|
crossvul-java_data_good_2469_1
|
package cz.metacentrum.perun.core.impl;
import com.zaxxer.hikari.HikariDataSource;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.Destination;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.DiacriticNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceExistsException;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.MaxSizeExceededException;
import cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.MinSizeExceededException;
import cz.metacentrum.perun.core.api.exceptions.NumberNotInRangeException;
import cz.metacentrum.perun.core.api.exceptions.NumbersNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.ParseUserNameException;
import cz.metacentrum.perun.core.api.exceptions.ParserException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.core.api.exceptions.SpaceNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.SpecialCharsNotAllowedException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongPatternException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.blImpl.ModulesUtilsBlImpl;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.text.StringCharacterIterator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utilities.
*/
public class Utils {
private final static Logger log = LoggerFactory.getLogger(Utils.class);
public final static String configurationsLocations = "/etc/perun/";
public static final String TITLE_BEFORE = "titleBefore";
public static final String FIRST_NAME = "firstName";
public static final String LAST_NAME = "lastName";
public static final String TITLE_AFTER = "titleAfter";
private static Properties properties;
public static final Pattern emailPattern = Pattern.compile("^[-_A-Za-z0-9+']+(\\.[-_A-Za-z0-9+']+)*@[-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
private static final Pattern titleBeforePattern = Pattern.compile("^(([\\p{L}]+[.])|(et))$");
private static final Pattern firstNamePattern = Pattern.compile("^[\\p{L}-']+$");
private static final Pattern lastNamePattern = Pattern.compile("^(([\\p{L}-']+)|([\\p{L}][.]))$");
private static final String userPhoneAttribute = "urn:perun:user:attribute-def:def:phone";
private static final String memberPhoneAttribute = "urn:perun:member:attribute-def:def:phone";
/**
* Replaces dangerous characters.
* Replaces : with - and spaces with _.
*
* @param str string to be normalized
* @return normalized string
*/
public static String normalizeString(String str) {
log.trace("Entering normalizeString: str='{}'", str);
return str.replace(':', '-').replace(' ', '_');
}
public static <T> boolean hasDuplicate(List<T> all) {
Set<T> set = new HashSet<>(all.size());
// Set#add returns false if the set does not change, which
// indicates that a duplicate element has been added.
for (T each: all) if (!set.add(each)) return true;
return false;
}
/**
* Joins Strings or any objects into a String. Use as
* <pre>
* List<?> list = Arrays.asList("a", 1, 2.0);
* String s = join(list,",");
* </pre>
* @param collection anything Iterable, like a {@link java.util.List} or {@link java.util.Collection}
* @param separator any separator, like a comma
* @return string with string representations of objects joined by separators
*/
public static String join(Iterable<?> collection, String separator) {
Iterator<?> oIter;
if (collection == null || (!(oIter = collection.iterator()).hasNext()))
return "";
StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next()));
while (oIter.hasNext())
oBuilder.append(separator).append(oIter.next());
return oBuilder.toString();
}
/**
* Returns additionalUserExtSources from the subject. It's used for synchronization from different ExtSources. subjectFromExtSource was obtained from the ExtSource.
*
* @param sess perun session
* @param subjectFromExtSource map with the subject
* @return List<UserExtSource> all additional ExtSources from the subject, returned list will never contain null value
* @throws InternalErrorException
*/
public static List<UserExtSource> extractAdditionalUserExtSources(PerunSession sess, Map<String, String> subjectFromExtSource) throws InternalErrorException {
List<UserExtSource> additionalUserExtSources = new ArrayList<>();
for (String attrName : subjectFromExtSource.keySet()) {
if(attrName != null &&
subjectFromExtSource.get(attrName) != null &&
attrName.startsWith(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING)) {
String login = subjectFromExtSource.get("login");
String[] userExtSourceRaw = subjectFromExtSource.get(attrName).split("\\|"); // Entry contains extSourceName|extSourceType|extLogin[|LoA]
log.debug("Processing additionalUserExtSource {}", subjectFromExtSource.get(attrName));
//Check if the array has at least 3 parts, this is protection against outOfBoundException
if(userExtSourceRaw.length < 3) {
throw new InternalErrorException("There is a missing mandatory part of additional user extSource value when processing it - '" + attrName + "'");
}
String additionalExtSourceName = userExtSourceRaw[0];
String additionalExtSourceType = userExtSourceRaw[1];
String additionalExtLogin = userExtSourceRaw[2];
int additionalExtLoa = 0;
// Loa is not mandatory argument
if (userExtSourceRaw.length>3 && userExtSourceRaw[3] != null) {
try {
additionalExtLoa = Integer.parseInt(userExtSourceRaw[3]);
} catch (NumberFormatException e) {
throw new ParserException("Subject with login [" + login + "] has wrong LoA '" + userExtSourceRaw[3] + "'.", e, "LoA");
}
}
ExtSource additionalExtSource;
if (additionalExtSourceName == null || additionalExtSourceName.isEmpty() ||
additionalExtSourceType == null || additionalExtSourceType.isEmpty() ||
additionalExtLogin == null || additionalExtLogin.isEmpty()) {
log.error("User with login {} has invalid additional userExtSource defined {}.", login, userExtSourceRaw);
} else {
try {
// Try to get extSource, with full extSource object (containg ID)
additionalExtSource = ((PerunBl) sess.getPerun()).getExtSourcesManagerBl().getExtSourceByName(sess, additionalExtSourceName);
} catch (ExtSourceNotExistsException e) {
try {
// Create new one if not exists
additionalExtSource = new ExtSource(additionalExtSourceName, additionalExtSourceType);
additionalExtSource = ((PerunBl) sess.getPerun()).getExtSourcesManagerBl().createExtSource(sess, additionalExtSource, null);
} catch (ExtSourceExistsException e1) {
throw new ConsistencyErrorException("Creating existing extSource: " + additionalExtSourceName);
}
}
// Add additional user extSource
additionalUserExtSources.add(new UserExtSource(additionalExtSource, additionalExtLoa, additionalExtLogin));
}
}
}
return additionalUserExtSources;
}
/**
* Joins Strings or any objects into a String. Use as
* <pre>
* String[] sa = { "a", "b", "c"};
* String s = join(list,",");
* </pre>
* @param objs array of objects
* @param separator any separator, like a comma
* @return string with string representations of objects joined by separators
*/
public static String join(Object[] objs, String separator) {
log.trace("Entering join: objs='{}', separator='{}'", objs, separator);
return join(Arrays.asList(objs),separator);
}
/**
* Integer row mapper
*/
public static final RowMapper<Integer> ID_MAPPER = (resultSet, i) -> resultSet.getInt("id");
/**
* String row mapper
*/
public static final RowMapper<String> STRING_MAPPER = (resultSet, i) -> resultSet.getString("value");
// FIXME prijde odstranit
public static void checkPerunSession(PerunSession sess) throws InternalErrorException {
notNull(sess, "sess");
}
/**
* Creates copy of given Map with Sets as values. The returned object contains a new Map
* and new Sets, the {@link T} objects remain the same.
*
* @param original original Map
* @param <T> parameter
* @return new Map with new Sets as values
*/
public static <T> Map<T, Set<T>> createDeepCopyOfMapWithSets(Map<T, Set<T>> original) {
Map<T, Set<T>> copy = new HashMap<>();
for (T key : original.keySet()) {
Set<T> setCopy = original.get(key) == null ? null : new HashSet<>(original.get(key));
copy.put(key, setCopy);
}
return copy;
}
/**
* Checks whether the object is null or not.
*
* @param e
* @param name
* @throws InternalErrorException which wraps NullPointerException
*/
public static void notNull(Object e, String name) throws InternalErrorException {
if(e == null){
throw new InternalErrorException(new NullPointerException("'" + name + "' is null"));
}
}
/**
* Throws a MinSizeExceededException if the given value does not specified minLength.
* If the value is null then MinSizeExceededException is thrown as well.
*
* @param propertyName name of checked property
* @param minLength minimal length
* @throws MinSizeExceededException when length of actualValue is lower than minLength or null
*/
public static void checkMinLength(String propertyName, String actualValue, int minLength) throws MinSizeExceededException {
if (actualValue == null) {
throw new MinSizeExceededException("The property '" + propertyName + "' does not have a minimal length equal to '" + minLength + "' because it is null.");
}
if (actualValue.length() < minLength) {
throw new MinSizeExceededException("Length of '" + propertyName + "' is too short! MinLength=" + minLength + ", ActualLength=" + actualValue.length());
}
}
/**
* Throws a MaxSizeExceededException if the given value is longer than maxLength.
* If the value is null then nothing happens.
*
* @param propertyName name of checked property
* @param maxLength max length
* @throws MaxSizeExceededException when length of actualValue is higher than maxLength
*/
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException {
if (actualValue == null) {
return;
}
if (actualValue.length() > maxLength) {
throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length());
}
}
/**
* Define, if some entity contain a diacritic symbol.
*
* @param name name of entity
* @throws DiacriticNotAllowedException
*/
public static void checkWithoutDiacritic(String name) throws DiacriticNotAllowedException{
if(!Normalizer.isNormalized(name, Form.NFKD))throw new DiacriticNotAllowedException("Name of the entity is not in the normalized form NFKD (diacritic not allowed)!");
}
/**
* Define, if some entity contain a special symbol
* Special symbol is everything except - numbers, letters and space
*
* @param name name of entity
* @throws SpecialCharsNotAllowedException
*/
public static void checkWithoutSpecialChars(String name) throws SpecialCharsNotAllowedException{
if(!name.matches("^[0-9 \\p{L}]*$")) throw new SpecialCharsNotAllowedException("The special chars in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a special symbol
* Special symbol is everything except - numbers, letters and space (and allowedSpecialChars)
* The allowedSpecialChars are on the end of regular expresion, so the same rule must be observed.
* (example, symbol - must be on the end of string) rules are the same like in regular expresion
*
* @param name name of entity
* @param allowedSpecialChars this String must contain only special chars which are allowed
* @throws SpecialCharsNotAllowedException
*/
public static void checkWithoutSpecialChars(String name, String allowedSpecialChars) throws SpecialCharsNotAllowedException{
if(!name.matches("^([0-9 \\p{L}" + allowedSpecialChars + "])*$")) throw new SpecialCharsNotAllowedException("The special chars (except " + allowedSpecialChars + ") in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a number
*
* @param name
* @throws NumbersNotAllowedException
*/
public static void checkWithoutNumbers(String name) throws NumbersNotAllowedException{
if(!name.matches("^([^0-9])*$")) throw new NumbersNotAllowedException("The numbers in the name of entity are not allowed!");
}
/**
* Define, if some entity contain a space
*
* @param name
* @throws SpaceNotAllowedException
*/
public static void checkWithoutSpaces(String name)throws SpaceNotAllowedException{
if(name.contains(" ")) throw new SpaceNotAllowedException("The spaces in the name of entity are not allowed!");
}
/**
* Define, if some number is in range.
* Example: number 4 is in range 4 - 12, number 3 is not
*
* @param number
* @param lowestValue
* @param highestValue
* @throws NumberNotInRangeException
*/
public static void checkRangeOfNumbers(int number, int lowestValue, int highestValue) throws NumberNotInRangeException {
if(number<lowestValue || number>highestValue) throw new NumberNotInRangeException("Number is not in range, Lowest="+lowestValue+" < Number="+number+" < Highest="+highestValue);
}
/**
* Gets the next number from the sequence. This function hides differences in the databases engines.
*
* @param jdbc
* @param sequenceName
* @return new ID
* @throws InternalErrorException
*/
public static int getNewId(JdbcTemplate jdbc, String sequenceName) throws InternalErrorException {
String dbType;
String url = "";
String query;
// try to deduce database type from jdbc connection metadata
try {
DataSource ds = jdbc.getDataSource();
if (ds instanceof HikariDataSource) {
url = ((HikariDataSource) ds).getJdbcUrl();
}
} catch (Exception e) {
log.error("cannot get JDBC url", e);
}
if (url.contains("hsqldb")) {
dbType = "hsqldb";
} else if (url.contains("oracle")) {
dbType = "oracle";
} else if (url.contains("postgresql")) {
dbType = "postgresql";
} else {
dbType = BeansUtils.getCoreConfig().getDbType();
}
switch (dbType) {
case "oracle":
query = "select " + sequenceName + ".nextval from dual";
break;
case "postgresql":
query = "select nextval('" + sequenceName + "')";
break;
case "hsqldb":
query = "call next value for " + sequenceName + ";";
break;
default:
throw new InternalErrorException("Unsupported DB type");
}
// Decide which type of the JdbcTemplate is provided
try {
Integer i = jdbc.queryForObject(query, Integer.class);
if (i == null) {
throw new InternalErrorException("New ID should not be null.");
}
return i;
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
/**
* Returns current time in millis. Result of this call can then be used by function getRunningTime().
*
* @return current time in millis.
*/
public static long startTimer() {
return System.currentTimeMillis();
}
/**
* Returns difference between startTime and current time in millis.
*
* @param startTime
* @return difference between current time in millis and startTime.
*/
public static long getRunningTime(long startTime) {
return System.currentTimeMillis()-startTime;
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
* @throws ClassNotFoundException
* @throws IOException
*/
public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class<?>> classes = new ArrayList<>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private static String limit(String s,int limit) {
if(s==null) return null;
return s.length() > limit ? s.substring(0, limit) : s;
}
public static User createUserFromNameMap(Map<String, String> name) throws InternalErrorException {
User user = new User();
if (name.get(FIRST_NAME) == null || name.get(LAST_NAME) == null || name.get(FIRST_NAME).isEmpty() || name.get(LAST_NAME).isEmpty()) {
throw new InternalErrorException("First name/last name is either empty or null when creating user");
}
user.setTitleBefore(limit(name.get(TITLE_BEFORE),40));
user.setFirstName(limit(name.get(FIRST_NAME),64));
user.setLastName(limit(name.get(LAST_NAME),64));
user.setTitleAfter(limit(name.get(TITLE_AFTER),40));
return user;
}
/**
* Creates a new instance of User with names initialized from parsed rawName.
* Imposes limit on leghts of fields.
* @see #parseCommonName(String)
* @param rawName raw name
* @param fullNameRequired if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
* @return user
*/
public static User parseUserFromCommonName(String rawName, boolean fullNameRequired) throws ParseUserNameException {
Map<String, String> m = parseCommonName(rawName, fullNameRequired);
return createUserFromNameMap(m);
}
/**
* @see Utils.parseCommonName(String rawName, boolean fullNameRequired) - where fullNameRequired is false
*/
public static Map<String, String> parseCommonName(String rawName) {
try {
return Utils.parseCommonName(rawName, false);
} catch (ParseUserNameException ex) {
throw new InternalErrorException("Unexpected behavior while parsing user name without full name requirement.");
}
}
/**
* Try to parse rawName to keys: "titleBefore" "firstName" "lastName" "titleAfter"
*
* If rawName is null or empty, return map with empty values of all keys.
*
* Parsing procedure:
* 1] prepare list of parts by replacing all characters "," and "_" by spaces
* 2] change all sequence of invisible characters (space, tabulator etc.) to one space
* 3] one by one try to parsing parts from the list
* - A] try to find all titleBefore parts
* - B] try to find one firstName part
* - C] try to find all lastName parts
* - D] if the rest is not lastName so save it to the title after
*
* Example of parsing rawName:
* 1] rawName = "Mgr. et Mgr. Petr_Jiri R. Sojka, Ph.D., CSc."
* 2] convert all ',' and '_' to spaces: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc."
* 3] convert more than 1 invisible char to 1 space: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc."
* 4] parse string to list of parts by space: ListOfParts= ["Mgr.","et","Mgr.","Petr","Jiri","R.","Sojka","Ph.D.","CSc."]
* 5] first fill everything what can be in title before: titleBefore="Mgr. et Mgr."
* 6] then fill everything what can be in first name (maximum 1 part): firstName="Petr"
* 7] then fill everything what can be in last name: lastName="Jiri R. Sojka"
* 8] everything else put to the title after: titleAfter="Ph.D. CSc."
* 9] put these variables to map like key=value, for ex.: Map[titleBefore="Mgr. et Mgr.",firstName="Petr", ... ] and return this map
*
* @param rawName name to parse
* @param fullNameRequired if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
* @return map string to string where are 4 keys (titleBefore,titleAfter,firstName and lastName) with their values (value can be null)
* @throws ParseUserNameException when method was unable to parse both first name and last name from the rawName
*/
public static Map<String, String> parseCommonName(String rawName, boolean fullNameRequired) throws ParseUserNameException {
// prepare variables and result map
Map<String, String> parsedName = new HashMap<>();
String titleBefore = "";
String firstName = "";
String lastName = "";
String titleAfter = "";
if (rawName != null && !rawName.isEmpty()) {
// replace all ',' and '_' characters for ' ' for rawName
rawName = rawName.replaceAll("[,_]", " ");
// replace all invisible chars in row for ' '
rawName = rawName.replaceAll("\\s+", " ").trim();
// split parts by space
List<String> nameParts = new ArrayList<>(Arrays.asList(rawName.split(" ")));
// if length of nameParts is 1, save it to the lastName
if(nameParts.size() == 1) {
lastName = nameParts.get(0);
// if length of nameParts is more than 1, try to choose which part belong to which value
} else {
// join title before name to single string with ' ' as delimiter
titleBefore = parsePartOfName(nameParts, new StringJoiner(" "), titleBeforePattern);
// get first name as a next name part if pattern matches and nameParts are not empty
if (!nameParts.isEmpty()) firstName = parsePartOfName(nameParts, new StringJoiner(" "), firstNamePattern);
// join last names to single string with ' ' as delimiter
if (!nameParts.isEmpty()) lastName = parsePartOfName(nameParts, new StringJoiner(" "), lastNamePattern);
// if any nameParts are left join them to one string with ' ' as delimiter and assume they are titles after name
if (!nameParts.isEmpty()) {
StringJoiner titleAfterBuilder = new StringJoiner(" ");
for (String namePart : nameParts) {
titleAfterBuilder.add(namePart);
}
titleAfter = titleAfterBuilder.toString();
}
}
}
// add variables to map, empty string means null
if (titleBefore.isEmpty()) titleBefore = null;
parsedName.put(TITLE_BEFORE, titleBefore);
if (firstName.isEmpty()) firstName = null;
parsedName.put(FIRST_NAME, firstName);
if (lastName.isEmpty()) lastName = null;
parsedName.put(LAST_NAME, lastName);
if (titleAfter.isEmpty()) titleAfter = null;
parsedName.put(TITLE_AFTER, titleAfter);
if(fullNameRequired) {
if (parsedName.get(FIRST_NAME) == null)
throw new ParseUserNameException("Unable to parse first name from text.", rawName);
if (parsedName.get(LAST_NAME) == null)
throw new ParseUserNameException("Unable to parse last name from text.", rawName);
}
return parsedName;
}
private static String parsePartOfName(List<String> nameParts, StringJoiner result, Pattern pattern) {
Matcher matcher = pattern.matcher(nameParts.get(0));
// if the matcher does not match continue to the next part of the name
if (!matcher.matches()) return result.toString();
result.add(nameParts.get(0));
nameParts.remove(0);
// when nameParts are depleted or firstName was found there is no reason to continue the recursion
if (nameParts.isEmpty() || pattern.equals(firstNamePattern)) return result.toString();
// continue the recursion to find the next part
return parsePartOfName(nameParts, result, pattern);
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
* @throws ClassNotFoundException
*/
private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
}
return classes;
}
/**
* Return true, if char on position in text is escaped by '\' Return false,
* if not.
*
* @param text text in which will be searching
* @param position position in text <0-text.length>
* @return true if char is escaped, false if not
*/
public static boolean isEscaped(String text, int position) {
boolean escaped = false;
while (text.charAt(position) == '\\') {
escaped = !escaped;
position--;
if (position < 0) {
return escaped;
}
}
return escaped;
}
/**
* Serialize map to string
*
* @param map
* @return string of escaped map
*/
public static String serializeMapToString(Map<String, String> map) {
if(map == null) return "\\0";
Map<String, String> attrNew = new HashMap<>(map);
Set<String> keys = new HashSet<>(attrNew.keySet());
for(String s: keys) {
attrNew.put("<" + BeansUtils.createEscaping(s) + ">", "<" + BeansUtils.createEscaping(attrNew.get(s)) + ">");
attrNew.remove(s);
}
return attrNew.toString();
}
public static Attribute copyAttributeToViAttributeWithoutValue(Attribute copyFrom, Attribute copyTo) {
copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt());
copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy());
copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt());
copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy());
return copyTo;
}
public static Attribute copyAttributeToVirtualAttributeWithValue(Attribute copyFrom, Attribute copyTo) {
copyTo.setValue(copyFrom.getValue());
copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt());
copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy());
copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt());
copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy());
return copyTo;
}
/**
* Method generates strings by pattern.
* The pattern is string with square brackets, e.g. "a[1-3]b". Then the content of the brackets
* is distributed, so the list is [a1b, a2b, a3c].
* Multibrackets are aslo allowed. For example "a[00-01]b[90-91]c" generates [a00b90c, a00b91c, a01b90c, a01b91c].
*
* @param pattern
* @return list of all generated strings
*/
public static List<String> generateStringsByPattern(String pattern) throws WrongPatternException {
List<String> result = new ArrayList<>();
// get chars between the brackets
List<String> values = new ArrayList<>(Arrays.asList(pattern.split("\\[[^]]*]")));
// get content of the brackets
List<String> generators = new ArrayList<>();
Pattern generatorPattern = Pattern.compile("\\[([^]]*)]");
Matcher m = generatorPattern.matcher(pattern);
while (m.find()) {
generators.add(m.group(1));
}
// if values strings contain square brackets, wrong syntax, abort
for (String value: values) {
if (value.contains("]") || (value.contains("["))) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much closing brackets.");
}
}
// if generators strings contain square brackets, wrong syntax, abort
for (String generator: generators) {
if (generator.contains("]") || (generator.contains("["))) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much opening brackets.");
}
}
// list, that contains list for each generator, with already generated numbers
List<List<String>> listOfGenerated = new ArrayList<>();
Pattern rangePattern = Pattern.compile("^(\\d+)-(\\d+)$");
for (String range: generators) {
m = rangePattern.matcher(range);
if (m.find()) {
String start = m.group(1);
String end = m.group(2);
int startNumber;
int endNumber;
try {
startNumber = Integer.parseInt(start);
endNumber = Integer.parseInt(end);
} catch (NumberFormatException ex) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Wrong format of the range.");
}
// if end is before start -> abort
if (startNumber > endNumber) {
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Start number has to be lower than end number.");
}
// find out, how many zeros are before start number
int zerosInStart = 0;
int counter = 0;
while ( (start.charAt(counter) == '0') && (counter < start.length()-1) ) {
zerosInStart++;
counter++;
}
String zeros = start.substring(0, zerosInStart);
int oldNumberOfDigits = String.valueOf(startNumber).length();
// list of already generated numbers
List<String> generated = new ArrayList<>();
while (endNumber >= startNumber) {
// keep right number of zeros before number
if (String.valueOf(startNumber).length() == oldNumberOfDigits +1) {
if (!zeros.isEmpty()) zeros = zeros.substring(1);
}
generated.add(zeros + startNumber);
oldNumberOfDigits = String.valueOf(startNumber).length();
startNumber++;
}
listOfGenerated.add(generated);
} else {
// range is not in the format number-number -> abort
throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. The format numer-number not found.");
}
}
// add values among the generated numbers as one item lists
List<List<String>> listOfGeneratorsAndValues = new ArrayList<>();
int index = 0;
for (List<String> list : listOfGenerated) {
if (index < values.size()) {
List<String> listWithValue = new ArrayList<>();
listWithValue.add(values.get(index));
listOfGeneratorsAndValues.add(listWithValue);
index++;
}
listOfGeneratorsAndValues.add(list);
}
// complete list with remaining values
for (int i = index; i < values.size(); i++) {
List<String> listWithValue = new ArrayList<>();
listWithValue.add(values.get(i));
listOfGeneratorsAndValues.add(listWithValue);
}
// generate all posibilities
return getCombinationsOfLists(listOfGeneratorsAndValues);
}
/**
* Method generates all combinations of joining of strings.
* It respects given order of lists.
* Example: input: [[a,b],[c,d]], output: [ac,ad,bc,bd]
* @param lists list of lists, which will be joined
* @return all joined strings
*/
private static List<String> getCombinationsOfLists(List<List<String>> lists) {
if (lists.isEmpty()) {
// this should not happen
return new ArrayList<>();
}
if (lists.size() == 1) {
return lists.get(0);
}
List<String> result = new ArrayList<>();
List<String> list = lists.remove(0);
// get recursively all posibilities without first list
List<String> posibilities = getCombinationsOfLists(lists);
// join all strings from first list with the others
for (String item: list) {
if (posibilities.isEmpty()) {
result.add(item);
} else {
for (String itemToConcat : posibilities) {
result.add(item + itemToConcat);
}
}
}
return result;
}
/**
* Return encrypted version of input in UTF-8 by HmacSHA256
*
* @param input input to encrypt
* @return encrypted value
*/
public static String getMessageAuthenticationCode(String input) {
if (input == null)
throw new NullPointerException("input must not be null");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(BeansUtils.getCoreConfig().getMailchangeSecretKey().getBytes(StandardCharsets.UTF_8),"HmacSHA256"));
byte[] macbytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
return new BigInteger(macbytes).toString(Character.MAX_RADIX);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Send validation email related to requested change of users preferred email.
*
* @param user user to change preferred email for
* @param url base URL of running perun instance passed from RPC
* @param email new email address to send notification to
* @param changeId ID of change request in DB
* @param subject Template subject or null
* @param content Template message or null
* @throws InternalErrorException
*/
public static void sendValidationEmail(User user, String url, String email, int changeId, String subject, String content) throws InternalErrorException {
// create mail sender
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("localhost");
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null ||subject.isEmpty()) {
message.setSubject("["+instanceName+"] New email address verification");
} else {
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// get validation link params
String i = Integer.toString(changeId, Character.MAX_RADIX);
String m = Utils.getMessageAuthenticationCode(i);
try {
// !! There is a hard-requirement for Perun instance
// to host GUI on same server as RPC like: "serverUrl/gui/"
URL urlObject = new URL(url);
// use default if unknown rpc path
String path = "/gui/";
if (urlObject.getPath().contains("/krb/")) {
path = "/krb/gui/";
} else if (urlObject.getPath().contains("/fed/")) {
path = "/fed/gui/";
} else if (urlObject.getPath().contains("/cert/")) {
path = "/cert/gui/";
}
StringBuilder link = new StringBuilder();
link.append(urlObject.getProtocol());
link.append("://");
link.append(urlObject.getHost());
link.append(path);
link.append("?i=");
link.append(URLEncoder.encode(i, "UTF-8"));
link.append("&m=");
link.append(URLEncoder.encode(m, "UTF-8"));
link.append("&u=" + user.getId());
// Build message
String text = "Dear "+user.getDisplayName()+",\n\nWe've received request to change your preferred email address to: "+email+"."+
"\n\nTo confirm this change please use link below:\n\n"+link+"\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (content == null || content.isEmpty()) {
message.setText(text);
} else {
content = content.replace("{link}",link);
message.setText(content);
}
mailSender.send(message);
} catch (UnsupportedEncodingException ex) {
throw new InternalErrorException("Unable to encode validation URL for mail change.", ex);
} catch (MalformedURLException ex) {
throw new InternalErrorException("Not valid URL of running Perun instance.", ex);
}
}
/**
* Sends email with link to non-authz password reset GUI where user
* can reset forgotten password
*
* @param user user to send notification for
* @param email user's email to send notification to
* @param namespace namespace to reset password in
* @param url base URL of Perun instance
* @param id ID of pwd reset request
* @param messageTemplate message of the email
* @param subject subject of the email
* @throws InternalErrorException
*/
public static void sendPasswordResetEmail(User user, String email, String namespace, String url, int id, String messageTemplate, String subject) throws InternalErrorException {
// create mail sender
JavaMailSender mailSender = BeansUtils.getDefaultMailSender();
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null) {
message.setSubject("[" + instanceName + "] Password reset in namespace: " + namespace);
} else {
subject = subject.replace("{namespace}", namespace);
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// get validation link params
String i = cipherInput(String.valueOf(user.getId()), false);
String m = cipherInput(String.valueOf(id), false);
try {
URL urlObject = new URL(url);
StringBuilder link = new StringBuilder();
link.append(urlObject.getProtocol());
link.append("://");
link.append(urlObject.getHost());
// reset link uses non-authz
link.append("/non/pwd-reset/");
link.append("?i=");
link.append(URLEncoder.encode(i, "UTF-8"));
link.append("&m=");
link.append(URLEncoder.encode(m, "UTF-8"));
// append login-namespace so GUI is themes and password checked by namespace rules
link.append("&login-namespace=");
link.append(URLEncoder.encode(namespace, "UTF-8"));
//validity formatting
String validity = Integer.toString(BeansUtils.getCoreConfig().getPwdresetValidationWindow());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now().plusHours(Integer.parseInt(validity));
String validityFormatted = dtf.format(localDateTime);
// Build message en
String textEn = "Dear " + user.getDisplayName() + ",\n\nWe've received request to reset your password in namespace \"" + namespace + "\"." +
"\n\nPlease visit the link below, where you can set new password:\n\n" + link + "\n\n" +
"Link is valid till " + validityFormatted + "\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (messageTemplate == null) {
message.setText(textEn);
} else {
// allow enforcing per-language links
if (messageTemplate.contains("{link-")) {
Pattern pattern = Pattern.compile("\\{link-[^}]+}");
Matcher matcher = pattern.matcher(messageTemplate);
while (matcher.find()) {
// whole "{link-something}"
String toSubstitute = matcher.group(0);
String langLink = link.toString();
Pattern namespacePattern = Pattern.compile("-(.*?)}");
Matcher m2 = namespacePattern.matcher(toSubstitute);
if (m2.find()) {
// only language "cs", "en",...
String lang = m2.group(1);
langLink = langLink + "&locale=" + lang;
}
messageTemplate = messageTemplate.replace(toSubstitute, langLink);
}
} else {
messageTemplate = messageTemplate.replace("{link}", link);
}
messageTemplate = messageTemplate.replace("{displayName}", user.getDisplayName());
messageTemplate = messageTemplate.replace("{namespace}", namespace);
messageTemplate = messageTemplate.replace("{validity}", validityFormatted);
message.setText(messageTemplate);
}
mailSender.send(message);
} catch (MailException ex) {
throw new InternalErrorException("Unable to send mail for password reset.", ex);
} catch (UnsupportedEncodingException ex) {
throw new InternalErrorException("Unable to encode URL for password reset.", ex);
} catch (MalformedURLException ex) {
throw new InternalErrorException("Not valid URL of running Perun instance.", ex);
}
}
/**
* Sends email to user confirming his password was changed.
*
* @param user user to send notification for
* @param email user's email to send notification to
* @param namespace namespace the password was re-set
* @param login login of user
* @param subject Subject from template or null
* @param content Message from template or null
*/
public static void sendPasswordResetConfirmationEmail(User user, String email, String namespace, String login, String subject, String content) {
// create mail sender
JavaMailSender mailSender = BeansUtils.getDefaultMailSender();
// create message
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
String instanceName = BeansUtils.getCoreConfig().getInstanceName();
if (subject == null || subject.isEmpty()) {
message.setSubject("["+instanceName+"] Password reset in namespace: "+namespace);
} else {
subject = subject.replace("{namespace}", namespace);
subject = subject.replace("{instanceName}", instanceName);
message.setSubject(subject);
}
// Build message
String text = "Dear "+user.getDisplayName()+",\n\nyour password in namespace \""+namespace+"\" was successfully reset."+
"\n\nThis message is automatically sent to all your email addresses registered in "+instanceName+" in order to prevent malicious password reset without your knowledge.\n\n" +
"If you didn't request / perform password reset, please notify your administrators and support at "+BeansUtils.getCoreConfig().getMailchangeBackupFrom()+" to resolve this security issue.\n\n" +
"Message is automatically generated." +
"\n----------------------------------------------------------------" +
"\nPerun - Identity & Access Management System";
if (content == null || content.isEmpty()) {
message.setText(text);
} else {
content = content.replace("{displayName}", user.getDisplayName());
content = content.replace("{namespace}", namespace);
content = content.replace("{login}", login);
content = content.replace("{instanceName}", instanceName);
message.setText(content);
}
mailSender.send(message);
}
/**
* Return en/decrypted version of input using AES/CBC/PKCS5PADDING cipher.
* Perun's internal secretKey and initVector are used (you can configure them in
* perun.properties file).
*
* @param plainText text to en/decrypt
* @param decrypt TRUE = decrypt input / FALSE = encrypt input
* @return en/decrypted text
* @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException if anything fails
*/
public static String cipherInput(String plainText, boolean decrypt) throws InternalErrorException {
try {
String encryptionKey = BeansUtils.getCoreConfig().getPwdresetSecretKey();
String initVector = BeansUtils.getCoreConfig().getPwdresetInitVector();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecretKeySpec k = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8), "AES");
c.init((decrypt) ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, k, new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8)));
if (decrypt) {
byte[] bytes = Base64.decodeBase64(plainText.getBytes(StandardCharsets.UTF_8));
return new String(c.doFinal(bytes), StandardCharsets.UTF_8);
} else {
byte[] bytes = Base64.encodeBase64(c.doFinal(plainText.getBytes(StandardCharsets.UTF_8)));
return new String(bytes, StandardCharsets.UTF_8);
}
} catch (Exception ex) {
throw new InternalErrorException("Error when encrypting message", ex);
}
}
/**
* Checks whether the destination is not null and is of the right type.
*
* @param destination destination to check
* @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException if destination is null
* @throws cz.metacentrum.perun.core.api.exceptions.WrongPatternException if destination is not of the right type
*/
public static void checkDestinationType(Destination destination) throws InternalErrorException, WrongPatternException {
if (destination == null) {
throw new InternalErrorException("Destination is null.");
}
String destinationType = destination.getType();
if ((!Objects.equals(destinationType, Destination.DESTINATIONHOSTTYPE)
&& (!Objects.equals(destinationType, Destination.DESTINATIONEMAILTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONSEMAILTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONURLTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONUSERHOSTTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONUSERHOSTPORTTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONSERVICESPECIFICTYPE))
&& (!Objects.equals(destinationType, Destination.DESTINATIONWINDOWS))
&& (!Objects.equals(destinationType, Destination.DESTINATIONWINDOWSPROXY)))) {
throw new WrongPatternException("Destination type " + destinationType + " is not supported.");
}
}
/**
* Sends SMS to the phone number of a user with the given message.
* The phone number is taken from the user attribute urn:perun:user:attribute-def:def:phone.
*
* @param sess session
* @param user receiver of the message
* @param message sms message to send
* @throws InternalErrorException when the attribute value cannot be found or is broken
* @throws cz.metacentrum.perun.core.api.exceptions.PrivilegeException when the actor has not right to get the attribute
* @throws cz.metacentrum.perun.core.api.exceptions.UserNotExistsException when given user does not exist
*/
public static void sendSMS(PerunSession sess, User user, String message) throws InternalErrorException, PrivilegeException, UserNotExistsException {
if (user == null) {
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException("user is null");
}
if (message == null) {
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException("message is null");
}
String telNumber;
try {
telNumber = (String) sess.getPerun().getAttributesManager().getAttribute(sess, user, userPhoneAttribute).getValue();
} catch (AttributeNotExistsException ex ) {
log.error("Sendig SMS with text \"{}\" to user {} failed: cannot get tel. number.", message, user );
throw new InternalErrorException("The attribute " + userPhoneAttribute + " has not been found.", ex);
} catch (WrongAttributeAssignmentException ex) {
log.error("Sendig SMS with text \"{}\" to user {} failed: cannot get tel. number.", message, user );
throw new InternalErrorException("The attribute " + userPhoneAttribute + " has not been found in user attributes.", ex);
}
sendSMS(telNumber, message);
}
/**
* Sends SMS to the phone number of a member with the given message.
* The phone number is taken from the user attribute urn:perun:member:attribute-def:def:phone.
*
* @param sess session
* @param member receiver of the message
* @param message sms message to send
* @throws InternalErrorException when the attribute value cannot be found or is broken
* @throws cz.metacentrum.perun.core.api.exceptions.PrivilegeException when the actor has not right to get the attribute
* @throws cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException when given member does not exist
*/
public static void sendSMS(PerunSession sess, Member member, String message) throws InternalErrorException, PrivilegeException, MemberNotExistsException {
String telNumber;
try {
telNumber = (String) sess.getPerun().getAttributesManager().getAttribute(sess, member, memberPhoneAttribute).getValue();
} catch (AttributeNotExistsException ex) {
log.error("Sendig SMS with text \"{}\" to member {} failed: cannot get tel. number.", message, member );
throw new InternalErrorException("The attribute " + memberPhoneAttribute + " has not been found.", ex);
} catch (WrongAttributeAssignmentException ex) {
log.error("Sendig SMS with text \"{}\" to member {} failed: cannot get tel. number.", message, member );
throw new InternalErrorException("The attribute " + memberPhoneAttribute + " has not been found in user attributes.", ex);
}
sendSMS(telNumber, message);
}
/**
* Sends SMS to the phone number with the given message.
* The sending provides external program for sending sms.
* Its path is saved in the perun property perun.sms.program.
*
* @param telNumber phone number of the receiver
* @param message sms message to send
* @throws InternalErrorException when there is something wrong with external program
* @throws IllegalArgumentException when the phone or message has a wrong format
*/
public static void sendSMS(String telNumber, String message) throws InternalErrorException {
log.debug("Sending SMS with text \"{}\" to tel. number {}.", message, telNumber);
try {
// create properties list
List<String> processProperties = new ArrayList<>();
// pass the location of external program for sending sms
processProperties.add(BeansUtils.getCoreConfig().getSmsProgram());
// pass program options
processProperties.add("-p");
processProperties.add(telNumber);
processProperties.add("-m");
processProperties.add(message);
// execute
ProcessBuilder pb = new ProcessBuilder(processProperties);
Process process;
process = pb.start();
int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ex) {
String errMsg = "The external process for sending sms was interrupted.";
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException(errMsg, ex);
}
// handle response
if (exitValue == 0) {
// successful
log.debug("SMS with text \"{}\" to tel. number {} successfully sent.", message, telNumber);
} else if ((exitValue == 1) || (exitValue == 2)) {
// users fault
String errMsg = getStringFromInputStream(process.getErrorStream());
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException(errMsg);
} else if (exitValue > 2) {
// internal fault
String errMsg = getStringFromInputStream(process.getErrorStream());
log.error("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException(errMsg);
}
} catch (IOException ex) {
log.warn("Sending SMS with text \"{}\" to tel. number {} failed.", message, telNumber);
throw new InternalErrorException("Cannot access the sms external application.", ex);
}
}
/**
* Get BigDecimal number like '1024' in Bytes and create better readable
* String with metric value like '1K' where K means KiloBytes.
*
* Use M,G,T,P,E like multipliers of 1024.
*
* If quota is not dividable by 1024 use B (Bytes) without dividing.
*
* @param quota in big natural number
* @return string with number and metric
*/
public static String bigDecimalBytesToReadableStringWithMetric(BigDecimal quota) throws InternalErrorException {
if(quota == null) throw new InternalErrorException("Quota in BigDecimal can't be null if we want to convert it to number with metric.");
//Prepare variable for result
String stringWithMetric;
//Try to divide quota to get result module 1024^x = 0 where X is in [K-0,M-1,G-2,T-3,P-4,E-5]
//If module is bigger than 0, try x-1
if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.E)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^5
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.E)).stripTrailingZeros().toPlainString() + "E";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.P)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^4
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.P)).stripTrailingZeros().toPlainString() + "P";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.T)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^3
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.T)).stripTrailingZeros().toPlainString() + "T";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.G)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^2
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.G)).stripTrailingZeros().toPlainString() + "G";
} else if(!quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.M)).stripTrailingZeros().toPlainString().contains(".")) {
//divide by 1024^1
stringWithMetric = quota.divide(BigDecimal.valueOf(ModulesUtilsBlImpl.M)).stripTrailingZeros().toPlainString() + "M";
} else {
//can't be diveded by 1024^x where x>0 so let it be in the format like it already is, convert it to BigInteger without fractional part
stringWithMetric = quota.toBigInteger().toString() + "K";
}
//return result format with metric
return stringWithMetric;
}
private static String getStringFromInputStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
return out.toString();
}
/**
* IMPORTANT: this method not convert utf to ascii, just try to convert some problematic
* chars to UTF and others change to '?'!!!
*
* @param s
* @return converted string from ascii to something near utf
*/
public synchronized static String utftoasci(String s){
final StringBuilder sb = new StringBuilder( s.length() * 2 );
final StringCharacterIterator iterator = new StringCharacterIterator( s );
char ch = iterator.current();
while( ch != StringCharacterIterator.DONE ){
if(Character.getNumericValue(ch)>=0){
sb.append( ch );
}else{
boolean f=false;
if(Character.toString(ch).equals("Ê")){sb.append("E");f=true;}
if(Character.toString(ch).equals("È")){sb.append("E");f=true;}
if(Character.toString(ch).equals("ë")){sb.append("e");f=true;}
if(Character.toString(ch).equals("é")){sb.append("e");f=true;}
if(Character.toString(ch).equals("è")){sb.append("e");f=true;}
if(Character.toString(ch).equals("Â")){sb.append("A");f=true;}
if(Character.toString(ch).equals("ä")){sb.append("a");f=true;}
if(Character.toString(ch).equals("ß")){sb.append("ss");f=true;}
if(Character.toString(ch).equals("Ç")){sb.append("C");f=true;}
if(Character.toString(ch).equals("Ö")){sb.append("O");f=true;}
if(Character.toString(ch).equals("º")){sb.append("");f=true;}
if(Character.toString(ch).equals("ª")){sb.append("");f=true;}
if(Character.toString(ch).equals("º")){sb.append("");f=true;}
if(Character.toString(ch).equals("Ñ")){sb.append("N");f=true;}
if(Character.toString(ch).equals("É")){sb.append("E");f=true;}
if(Character.toString(ch).equals("Ä")){sb.append("A");f=true;}
if(Character.toString(ch).equals("Å")){sb.append("A");f=true;}
if(Character.toString(ch).equals("Ü")){sb.append("U");f=true;}
if(Character.toString(ch).equals("ö")){sb.append("o");f=true;}
if(Character.toString(ch).equals("ü")){sb.append("u");f=true;}
if(Character.toString(ch).equals("á")){sb.append("a");f=true;}
if(Character.toString(ch).equals("Ó")){sb.append("O");f=true;}
if(Character.toString(ch).equals("ě")){sb.append("e");f=true;}
if(Character.toString(ch).equals("Ě")){sb.append("E");f=true;}
if(Character.toString(ch).equals("š")){sb.append("s");f=true;}
if(Character.toString(ch).equals("Š")){sb.append("S");f=true;}
if(Character.toString(ch).equals("č")){sb.append("c");f=true;}
if(Character.toString(ch).equals("Č")){sb.append("C");f=true;}
if(Character.toString(ch).equals("ř")){sb.append("r");f=true;}
if(Character.toString(ch).equals("Ř")){sb.append("R");f=true;}
if(Character.toString(ch).equals("ž")){sb.append("z");f=true;}
if(Character.toString(ch).equals("Ž")){sb.append("Z");f=true;}
if(Character.toString(ch).equals("ý")){sb.append("y");f=true;}
if(Character.toString(ch).equals("Ý")){sb.append("Y");f=true;}
if(Character.toString(ch).equals("í")){sb.append("i");f=true;}
if(Character.toString(ch).equals("Í")){sb.append("I");f=true;}
if(Character.toString(ch).equals("ó")){sb.append("o");f=true;}
if(Character.toString(ch).equals("ú")){sb.append("u");f=true;}
if(Character.toString(ch).equals("Ú")){sb.append("u");f=true;}
if(Character.toString(ch).equals("ů")){sb.append("u");f=true;}
if(Character.toString(ch).equals("Ů")){sb.append("U");f=true;}
if(Character.toString(ch).equals("Ň")){sb.append("N");f=true;}
if(Character.toString(ch).equals("ň")){sb.append("n");f=true;}
if(Character.toString(ch).equals("Ť")){sb.append("T");f=true;}
if(Character.toString(ch).equals("ť")){sb.append("t");f=true;}
if(Character.toString(ch).equals(" ")){sb.append(" ");f=true;}
if(!f){
sb.append("?");
}
}
ch = iterator.next();
}
return sb.toString();
}
/**
* Convert input string (expected UTF-8) to ASCII if possible.
* Any non-ASCII character is replaced by replacement parameter.
*
* @param input String to convert from UTF-8 to ASCII.
* @param replacement Replacement character used for all non-ASCII chars in input.
* @return converted string from ascii to something near utf
*/
public synchronized static String toASCII(String input, Character replacement) {
String normalizedOutput = "";
// take unicode characters one by one and normalize them
for ( int i=0; i<input.length(); i++ ) {
char c = input.charAt(i);
// normalize a single unicode character, then remove every non-ascii symbol (like accents)
String normalizedChar = Normalizer.normalize(String.valueOf(c) , Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
if ( ! normalizedChar.isEmpty() ) {
// if there is a valid ascii representation, use it
normalizedOutput += normalizedChar;
} else {
// otherwise replace character with an "replacement"
normalizedOutput += replacement;
}
}
return normalizedOutput;
}
/**
* Determine if attribute is large (can contain value over 4kb).
*
* @param sess perun session
* @param attribute attribute to be checked
* @return true if the attribute is large
*/
public static boolean isLargeAttribute(PerunSession sess, AttributeDefinition attribute) {
return (attribute.getType().equals(LinkedHashMap.class.getName()) ||
attribute.getType().equals(BeansUtils.largeStringClassName) ||
attribute.getType().equals(BeansUtils.largeArrayListClassName));
}
/**
* Extends given date by given period.
*
* @param localDate date to be extended
* @param period period used to extend date
* @throws InternalErrorException when the period has wrong format,
* allowed format is given by regex "\\+([0-9]+)([dmy]?)"
*/
public static LocalDate extendDateByPeriod(LocalDate localDate, String period) throws InternalErrorException {
// We will add days/months/years
Pattern p = Pattern.compile("\\+([0-9]+)([dmy]?)");
Matcher m = p.matcher(period);
if (m.matches()) {
String countString = m.group(1);
int amount = Integer.valueOf(countString);
String dmyString = m.group(2);
switch (dmyString) {
case "d":
return localDate.plusDays(amount);
case "m":
return localDate.plusMonths(amount);
case "y":
return localDate.plusYears(amount);
default:
throw new InternalErrorException("Wrong format of period. Period: " + period);
}
} else {
throw new InternalErrorException("Wrong format of period. Period: " + period);
}
}
/**
* Returns closest future LocalDate based on values given by matcher.
* If returned value should fall to 29. 2. of non-leap year, the date is extended to 28. 2. instead.
*
* @param matcher matcher with day and month values
* @return Extended date.
*/
public static LocalDate getClosestExpirationFromStaticDate(Matcher matcher) {
int day = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
// We must detect if the extension date is in current year or in a next year (we use year 2000 in comparison because it is a leap year)
LocalDate extensionDate = LocalDate.of(2000, month, day);
// check if extension is next year
// in case of static date being today's date, we want to extend to next year (that's why we use the negation later)
boolean extensionInThisYear = LocalDate.of(2000, LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth()).isBefore(extensionDate);
// Get current year
int year = LocalDate.now().getYear();
if (!extensionInThisYear) {
// Add year to get next year
year++;
}
// Set the date to which the membership should be extended, can be changed if there was grace period, see next part of the code
if (day == 29 && month == 2 && !LocalDate.of(year, 1,1).isLeapYear()) {
// If extended date is 29. 2. of non-leap year, the date is set to 28. 2.
extensionDate = LocalDate.of(year, 2, 28);
} else {
extensionDate = LocalDate.of(year, month, day);
}
return extensionDate;
}
/**
* Prepares grace period date by values from given matcher.
* @param matcher matcher
* @return pair of field(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS) and amount
* @throws InternalErrorException when given matcher contains invalid data
* @throws IllegalArgumentException when matcher does not match gracePeriod format
*/
public static Pair<Integer, TemporalUnit> prepareGracePeriodDate(Matcher matcher) throws InternalErrorException {
if (!matcher.matches()) {
throw new IllegalArgumentException("Wrong format of gracePeriod.");
}
String countString = matcher.group(1);
int amount = Integer.valueOf(countString);
TemporalUnit field;
String dmyString = matcher.group(2);
switch (dmyString) {
case "d":
field = ChronoUnit.DAYS;
break;
case "m":
field = ChronoUnit.MONTHS;
break;
case "y":
field = ChronoUnit.YEARS;
break;
default:
throw new InternalErrorException("Wrong format of gracePeriod.");
}
return new Pair<>(amount, field);
}
/**
* We need to escape some special characters for LDAP filtering.
* We need to escape these characters: '\\', '*', '(', ')', '\000'
*
* @param searchString search string which need to be escaped properly
* @return properly escaped search string
*/
public static String escapeStringForLDAP(String searchString) {
if(searchString == null) return "";
return searchString.replace("\\", "\\5C").replace("*", "\\2A").replace("(", "\\28").replace(")", "\\29").replace("\000", "\\00");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_2469_1
|
crossvul-java_data_bad_3076_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_4
|
crossvul-java_data_good_3076_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factorySynchUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_SYNCHRONIZATION));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceSynchUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_SYNCHRONIZATION));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySynchUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSynchUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySynchUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSynchUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_5
|
crossvul-java_data_bad_3083_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_3
|
crossvul-java_data_bad_3080_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
} finally {
h.stop();
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT);
if (http1PendingCount == null) {
this.host.log("http1 pending op stats not present");
return false;
}
ServiceStat http2PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT);
if (http2PendingCount == null) {
this.host.log("http2 pending op stats not present");
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertTrue(this.host.getServiceStage(servicePath) == ProcessingStage.AVAILABLE);
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Service
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
1,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
URI serviceUri = states.keySet().iterator().next();
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
// Subscribe to created service
TestContext ctx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
TestContext notifyCtx = this.host.testCreate(2);
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
this.host.testWait(ctx);
// do a PATCH, to trigger a notification
TestContext patchCtx = this.host.testCreate(1);
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
this.host.testWait(patchCtx);
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> this.host.getServiceStage(serviceUri.getPath()) == null);
// Let's do a PATCH again
st.name = "secondPatch";
patchCtx = this.host.testCreate(1);
patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
this.host.testWait(patchCtx);
// Wait for the patch notifications. This will exit only
// when both notifications have been received.
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void getAvailableServicesWithOptions() throws Throwable {
setUp(false);
int serviceCount = 5;
List<URI> exampleURIs = new ArrayList<>();
this.host.createExampleServices(this.host, serviceCount, exampleURIs,
Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_3
|
crossvul-java_data_bad_3079_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void testUtilityStats() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals(accumulatedValue));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN, AggregationType.MAX));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink));
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version > 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
double maxAvg = 0;
double countPerMaxAvgBin = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.avg != null && bin.avg > maxAvg) {
maxAvg = bin.avg;
countPerMaxAvgBin = bin.count;
}
}
assertTrue(maxAvg > 0);
assertTrue(countPerMaxAvgBin >= 1);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_4
|
crossvul-java_data_good_3078_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_4
|
crossvul-java_data_good_3081_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_1
|
crossvul-java_data_bad_4667_0
|
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed 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.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Provides utility methods for working with {@linkplain File files}.
*
* <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
* JDK's {@link java.nio.file.Files} class.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@GwtIncompatible
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered reader
*/
@Beta
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
* java.nio.file.OpenOption...)}.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered writer
*/
@Beta
public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a new {@link ByteSource} for reading bytes from the given file.
*
* @since 14.0
*/
public static ByteSource asByteSource(File file) {
return new FileByteSource(file);
}
private static final class FileByteSource extends ByteSource {
private final File file;
private FileByteSource(File file) {
this.file = checkNotNull(file);
}
@Override
public FileInputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public Optional<Long> sizeIfKnown() {
if (file.isFile()) {
return Optional.of(file.length());
} else {
return Optional.absent();
}
}
@Override
public long size() throws IOException {
if (!file.isFile()) {
throw new FileNotFoundException(file.toString());
}
return file.length();
}
@Override
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
@Override
public String toString() {
return "Files.asByteSource(" + file + ")";
}
}
/**
* Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
* control how the file is opened for writing. When no mode is provided, the file will be
* truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
* will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static ByteSink asByteSink(File file, FileWriteMode... modes) {
return new FileByteSink(file, modes);
}
private static final class FileByteSink extends ByteSink {
private final File file;
private final ImmutableSet<FileWriteMode> modes;
private FileByteSink(File file, FileWriteMode... modes) {
this.file = checkNotNull(file);
this.modes = ImmutableSet.copyOf(modes);
}
@Override
public FileOutputStream openStream() throws IOException {
return new FileOutputStream(file, modes.contains(APPEND));
}
@Override
public String toString() {
return "Files.asByteSink(" + file + ", " + modes + ")";
}
}
/**
* Returns a new {@link CharSource} for reading character data from the given file using the given
* character set.
*
* @since 14.0
*/
public static CharSource asCharSource(File file, Charset charset) {
return asByteSource(file).asCharSource(charset);
}
/**
* Returns a new {@link CharSink} for writing character data to the given file using the given
* character set. The given {@code modes} control how the file is opened for writing. When no mode
* is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
* APPEND} mode is provided, writes will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
return asByteSink(file, modes).asCharSink(charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest possible byte array
* (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
@Beta
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
/**
* Reads all characters from a file into a {@link String}, using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static String toString(File file, Charset charset) throws IOException {
return asCharSource(file, charset).read();
}
/**
* Overwrites a file with the contents of a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
@Beta
public static void write(byte[] from, File to) throws IOException {
asByteSink(to).write(from);
}
/**
* Writes a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset).write(from);
}
/**
* Copies all bytes from a file to an output stream.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
@Beta
public static void copy(File from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Copies all the bytes from one file to another.
*
* <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process
* termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
* need to guard against those conditions, you should employ other file-level synchronization.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten
* with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i>
* file, the contents of that file will be deleted.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void copy(File from, File to) throws IOException {
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
asByteSource(from).copyTo(asByteSink(to));
}
/**
* Copies all characters from a file to an appendable object, using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static void copy(File from, Charset charset, Appendable to) throws IOException {
asCharSource(from, charset).copyTo(to);
}
/**
* Appends a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
* method is scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static void append(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, FileWriteMode.APPEND).write(from);
}
/**
* Returns true if the given files exist, are not directories, and contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
@Beta
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
@Beta
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
@SuppressWarnings("GoodTime") // reading system time without TimeSource
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException(
"Failed to create directory within "
+ TEMP_DIR_ATTEMPTS
+ " attempts (tried "
+ baseName
+ "0 to "
+ baseName
+ (TEMP_DIR_ATTEMPTS - 1)
+ ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the same as the unix command of
* the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
@Beta
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified file. Note that if
* this operation fails it may have succeeded in creating some (but not all) of the necessary
* parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
* directories of the specified file could not be created.
* @since 4.0
*/
@Beta
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
* mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
* -- or even that the caller can create it, but this method makes no such guarantees even for
* non-root files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves a file from one path to another. This method can rename a file and/or move it to a
* different directory. In either case {@code to} must be the target path for the file itself; not
* just the new name for the file or the path to the new parent directory.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include line-termination characters, but
* does include other leading and trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static String readFirstLine(File file, Charset charset) throws IOException {
return asCharSource(file, charset).readFirstLine();
}
/**
* Reads all of the lines from a file. The lines do not include line-termination characters, but
* do include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Files.asCharSource(file, charset).readLines()}.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
@Beta
public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return asCharSource(file, charset)
.readLines(
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Streams lines from a {@link File}, stopping when our callback returns false, or we have read
* all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
* @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
/**
* Fully maps a file read-only in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
* MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
return mapInternal(file, mode, -1);
}
/**
* Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
* long, long)} using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
* with the requested {@code size}. Thus this method is useful for creating memory mapped files
* which do not yet exist.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
checkArgument(size >= 0, "size (%s) may not be negative", size);
return mapInternal(file, mode, size);
}
private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
Closer closer = Closer.create();
try {
RandomAccessFile raf =
closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
FileChannel channel = closer.register(raf.getChannel());
return channel.map(mode, 0, size == -1 ? channel.size() : size);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent
* to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* <p>These heuristics do not always match the behavior of the filesystem. In particular, consider
* the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
* symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
* sibling of {@code a} referred to by {@code b}.
*
* @since 11.0
*/
@Beta
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<>();
// resolve ., .., and //
for (String component : components) {
switch (component) {
case ".":
continue;
case "..":
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
break;
default:
path.add(component);
break;
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for
* the given file name, or the empty string if the file has no extension. The result does not
* include the '{@code .}'.
*
* <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's
* name as determined by {@link File#getName}. It does not account for any filesystem-specific
* behavior that the {@link File} API does not already account for. For example, on NTFS it will
* report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
* will drop the {@code ":.txt"} part of the name when the file is actually created on the
* filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>.
*
* @since 11.0
*/
@Beta
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its <a
* href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
@Beta
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
/**
* Returns a {@link TreeTraverser} instance for {@link File} trees.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* @since 15.0
* @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
* {@link #fileTraverser()} instead with the same semantics as this method.
*/
@Deprecated
static TreeTraverser<File> fileTreeTraverser() {
return FILE_TREE_TRAVERSER;
}
private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
new TreeTraverser<File>() {
@Override
public Iterable<File> children(File file) {
return fileTreeChildren(file);
}
@Override
public String toString() {
return "Files.fileTreeTraverser()";
}
};
/**
* Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
* starts from a {@link File} and will return all files and directories it encounters.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
* except that it doesn't follow symbolic links and returns {@code Path} instances.
*
* <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
* a directory, no exception will be thrown and the returned {@link Iterable} will contain a
* single element: that file.
*
* <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
* with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
* "/home/alice", ...]}
*
* @since 23.5
*/
@Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
private static final SuccessorsFunction<File> FILE_TREE =
new SuccessorsFunction<File>() {
@Override
public Iterable<File> successors(File file) {
return fileTreeChildren(file);
}
};
private static Iterable<File> fileTreeChildren(File file) {
// check isDirectory() just because it may be faster than listFiles() on a non-directory
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return Collections.unmodifiableList(Arrays.asList(files));
}
}
return Collections.emptyList();
}
/**
* Returns a predicate that returns the result of {@link File#isDirectory} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isDirectory() {
return FilePredicate.IS_DIRECTORY;
}
/**
* Returns a predicate that returns the result of {@link File#isFile} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isFile() {
return FilePredicate.IS_FILE;
}
private enum FilePredicate implements Predicate<File> {
IS_DIRECTORY {
@Override
public boolean apply(File file) {
return file.isDirectory();
}
@Override
public String toString() {
return "Files.isDirectory()";
}
},
IS_FILE {
@Override
public boolean apply(File file) {
return file.isFile();
}
@Override
public String toString() {
return "Files.isFile()";
}
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_4667_0
|
crossvul-java_data_bad_3080_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_2
|
crossvul-java_data_good_3076_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_4
|
crossvul-java_data_bad_3083_2
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_2
|
crossvul-java_data_good_3076_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SynchronizationRequest;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION)) {
handleSynchRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleSynchRequest(Operation op) {
if (op.getAction() != Action.PATCH && op.getAction() != Action.PUT) {
Operation.failActionNotSupported(op);
return;
}
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
SynchronizationRequest synchRequest = op.getBody(SynchronizationRequest.class);
if (synchRequest.kind == null || !synchRequest.kind.equals(Utils.buildKind(SynchronizationRequest.class))) {
op.fail(new IllegalArgumentException(String.format(
"Invalid 'kind' in the request body")));
return;
}
if (!synchRequest.documentSelfLink.equals(this.parent.getSelfLink())) {
op.fail(new IllegalArgumentException("Invalid param in the body: " + synchRequest.documentSelfLink));
return;
}
// Synchronize the FactoryService
if (this.parent instanceof FactoryService) {
((FactoryService)this.parent).synchronizeChildServicesIfOwner(new Operation());
op.complete();
return;
}
if (this.parent instanceof StatelessService) {
op.fail(new IllegalArgumentException("Nothing to synchronize for stateless service: " +
synchRequest.documentSelfLink));
return;
}
// Synchronize the single child service.
synchronizeChildService(this.parent.getSelfLink(), op);
}
private void synchronizeChildService(String link, Operation op) {
// To trigger synchronization of the child-service, we make
// a SYNCH-OWNER request. The request body is an empty document
// with just the documentSelfLink property set to the link
// of the child-service. This is done so that the FactoryService
// routes the request to the DOCUMENT_OWNER.
ServiceDocument d = new ServiceDocument();
d.documentSelfLink = UriUtils.getLastPathSegment(link);
String factoryLink = UriUtils.getParentPath(link);
Operation.CompletionHandler c = (o, e) -> {
if (e != null) {
String msg = String.format("Synchronization failed for service %s with status code %d, message %s",
o.getUri().getPath(), o.getStatusCode(), e.getMessage());
this.parent.getHost().log(Level.WARNING, msg);
op.fail(new IllegalStateException(msg));
return;
}
op.complete();
};
Operation.createPost(this, factoryLink)
.setBody(d)
.setCompletion(c)
.setReferer(getUri())
.setConnectionSharing(true)
.setConnectionTag(ServiceClient.CONNECTION_TAG_SYNCHRONIZATION)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.sendWith(this.parent);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public void setProcessingStage(ProcessingStage initialized) {
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_0
|
crossvul-java_data_bad_3079_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
if (op.hasBody()) {
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (op.getAction()) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceDocument rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_0
|
crossvul-java_data_good_3079_7
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.services.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.AuthorizationSetupHelper;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.FactoryService;
import com.vmware.xenon.common.NodeSelectorService.SelectAndForwardRequest;
import com.vmware.xenon.common.NodeSelectorService.SelectOwnerResponse;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationJoin;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceHost.HttpScheme;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.StatefulService;
import com.vmware.xenon.common.SynchronizationTaskService;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.RoundRobinIterator;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleTaskService.ExampleTaskServiceState;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupBroadcastResult.PeerNodeResult;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceErrorResponse;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceState;
import com.vmware.xenon.services.common.ResourceGroupService.PatchQueryRequest;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestNodeGroupService {
public static class PeriodicExampleFactoryService extends FactoryService {
public static final String SELF_LINK = "test/examples-periodic";
public PeriodicExampleFactoryService() {
super(ExampleServiceState.class);
}
@Override
public Service createServiceInstance() throws Throwable {
ExampleService s = new ExampleService();
s.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
return s;
}
}
public static class ExampleServiceWithCustomSelector extends StatefulService {
public ExampleServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.REPLICATION, true);
super.toggleOption(ServiceOption.OWNER_SELECTION, true);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ExampleFactoryServiceWithCustomSelector extends FactoryService {
public ExampleFactoryServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.setPeerNodeSelectorPath(CUSTOM_GROUP_NODE_SELECTOR);
}
@Override
public Service createServiceInstance() throws Throwable {
return new ExampleServiceWithCustomSelector();
}
}
private static final String CUSTOM_EXAMPLE_SERVICE_KIND = "xenon:examplestate";
private static final String CUSTOM_NODE_GROUP_NAME = "custom";
private static final String CUSTOM_NODE_GROUP = UriUtils.buildUriPath(
ServiceUriPaths.NODE_GROUP_FACTORY,
CUSTOM_NODE_GROUP_NAME);
private static final String CUSTOM_GROUP_NODE_SELECTOR = UriUtils.buildUriPath(
ServiceUriPaths.NODE_SELECTOR_PREFIX,
CUSTOM_NODE_GROUP_NAME);
public static final long DEFAULT_MAINT_INTERVAL_MICROS = TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
private VerificationHost host;
/**
* Command line argument specifying number of times to run the same test method.
*/
public int testIterationCount = 1;
/**
* Command line argument specifying default number of in process service hosts
*/
public int nodeCount = 3;
/**
* Command line argument specifying request count
*/
public int updateCount = 10;
/**
* Command line argument specifying service instance count
*/
public int serviceCount = 10;
/**
* Command line argument specifying test duration
*/
public long testDurationSeconds;
/**
* Command line argument specifying iterations per test method
*/
public long iterationCount = 1;
/**
* Command line argument used by replication long running tests
*/
public long totalOperationLimit = Long.MAX_VALUE;
private NodeGroupConfig nodeGroupConfig = new NodeGroupConfig();
private EnumSet<ServiceOption> postCreationServiceOptions = EnumSet.noneOf(ServiceOption.class);
private boolean expectFailure;
private long expectedFailureStartTimeMicros;
private List<URI> expectedFailedHosts = new ArrayList<>();
private String replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
private String replicationNodeSelector = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
private long replicationFactor;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
if (!this.host.isRemotePeerTest() &&
!CUSTOM_EXAMPLE_SERVICE_KIND.equals(current.documentKind)) {
return false;
}
return current.name.equals(initial.name);
};
private Function<ExampleServiceState, Void> exampleStateUpdateBodySetter = (
ExampleServiceState state) -> {
state.name = Utils.getNowMicrosUtc() + "";
return null;
};
private boolean isPeerSynchronizationEnabled = true;
private boolean isAuthorizationEnabled = false;
private HttpScheme replicationUriScheme;
private boolean skipAvailabilityChecks = false;
private boolean isMultiLocationTest = false;
private void setUp(int localHostCount) throws Throwable {
if (this.host != null) {
return;
}
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
this.host.setAuthorizationEnabled(this.isAuthorizationEnabled);
VerificationHost.createAndAttachSSLClient(this.host);
if (this.replicationUriScheme == HttpScheme.HTTPS_ONLY) {
// disable HTTP, forcing host.getPublicUri() to return a HTTPS schemed URI. This in
// turn forces the node group to use HTTPS for join, replication, etc
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// the default is disable (-1) so we must set port to 0, to enable SSL and make the
// runtime pick a random HTTPS port
this.host.setSecurePort(0);
}
if (this.testDurationSeconds > 0) {
// for long running tests use the default interval to match production code
this.host.maintenanceIntervalMillis = TimeUnit.MICROSECONDS.toMillis(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
}
this.host.start();
if (this.host.isAuthorizationEnabled()) {
this.host.setSystemAuthorizationContext();
}
CommandLineArgumentParser.parseFromProperties(this.host);
this.host.setStressTest(this.host.isStressTest);
this.host.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
this.host.setMultiLocationTest(this.isMultiLocationTest);
this.host.setUpPeerHosts(localHostCount);
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
setUpPeerHostWithAdditionalServices(h1);
}
// If the peer hosts are remote, then we undo CUSTOM_EXAMPLE_SERVICE_KIND
// from the KINDS cache and use the real documentKind of ExampleService.
if (this.host.isRemotePeerTest()) {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
}
}
private void setUpPeerHostWithAdditionalServices(VerificationHost h1) throws Throwable {
h1.setStressTest(this.host.isStressTest);
h1.waitForServiceAvailable(ExampleService.FACTORY_LINK);
Replication1xExampleFactoryService exampleFactory1x = new Replication1xExampleFactoryService();
h1.startServiceAndWait(exampleFactory1x,
Replication1xExampleFactoryService.SELF_LINK,
null);
Replication3xExampleFactoryService exampleFactory3x = new Replication3xExampleFactoryService();
h1.startServiceAndWait(exampleFactory3x,
Replication3xExampleFactoryService.SELF_LINK,
null);
// start the replication test factory service with OWNER_SELECTION
ReplicationFactoryTestService ownerSelRplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(ownerSelRplFactory,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK,
null);
// start the replication test factory service with STRICT update checking
ReplicationFactoryTestService strictReplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(strictReplFactory,
ReplicationFactoryTestService.STRICT_SELF_LINK, null);
// start the replication test factory service with simple replication, no owner selection
ReplicationFactoryTestService replFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(replFactory,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK, null);
}
private Map<URI, URI> getFactoriesPerNodeGroup(String factoryLink) {
Map<URI, URI> map = this.host.getNodeGroupToFactoryMap(factoryLink);
for (URI h : this.expectedFailedHosts) {
URI e = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
// do not send messages through hosts that will be stopped: this allows all messages to
// end the node group and the succeed or fail based on the test goals. If we let messages
// route through a host that we will abruptly stop, the message might timeout, which is
// OK for the expected failure case when quorum is not met, but will prevent is from confirming
// in the non eager consistency case, that all updates were written to at least one host
map.remove(e);
}
return map;
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
Utils.registerKind(ExampleServiceState.class, CUSTOM_EXAMPLE_SERVICE_KIND);
}
private void setUpOnDemandLoad() throws Throwable {
setUp();
// we need at least 5 nodes, because we're going to stop 2
// nodes and we need majority quorum
this.nodeCount = Math.max(5, this.nodeCount);
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
// create node group, join nodes and set majority quorum
setUp(this.nodeCount);
toggleOnDemandLoad();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.host.getPeerCount() / 2 + 1);
}
private void toggleOnDemandLoad() {
for (URI nodeUri : this.host.getNodeGroupMap().keySet()) {
URI factoryUri = UriUtils.buildUri(nodeUri, ExampleService.FACTORY_LINK);
this.host.toggleServiceOptions(factoryUri, EnumSet.of(ServiceOption.ON_DEMAND_LOAD),
null);
}
}
@After
public void tearDown() throws InterruptedException {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
if (this.host == null) {
return;
}
if (this.host.isRemotePeerTest()) {
try {
this.host.logNodeProcessLogs(this.host.getNodeGroupMap().keySet(),
ServiceUriPaths.PROCESS_LOG);
} catch (Throwable e) {
this.host.log("Failure retrieving process logs: %s", Utils.toString(e));
}
try {
this.host.logNodeManagementState(this.host.getNodeGroupMap().keySet());
} catch (Throwable e) {
this.host.log("Failure retrieving management state: %s", Utils.toString(e));
}
}
this.host.tearDownInProcessPeers();
this.host.toggleNegativeTestMode(false);
this.host.tearDown();
this.host = null;
System.clearProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS);
}
@Test
public void synchronizationCollisionWithPosts() throws Throwable {
// POST requests go through the FactoryService
// and do not get queued with Synchronization
// requests, so if synchronization was running
// while POSTs were happening for the same factory
// service, we could run into collisions. This test
// verifies that xenon handles such collisions and
// POST requests are always successful.
// Join the nodes with full quorum and wait for nodes to
// converge and synchronization to complete.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// Find the owner node for /core/examples. We will
// use it to start on-demand synchronization for
// this factory
URI factoryUri = UriUtils.buildUri(this.host.getPeerHost(), ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(factoryUri, this.replicationNodeSelector);
String taskPath = UriUtils.buildUriPath(
SynchronizationTaskService.FACTORY_LINK,
UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
VerificationHost owner = null;
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
if (peer.isOwner(ExampleService.FACTORY_LINK, ServiceUriPaths.DEFAULT_NODE_SELECTOR)) {
owner = peer;
break;
}
}
this.host.log(Level.INFO, "Owner of synch-task is %s", owner.getId());
// Get the membershipUpdateTimeMicros so that we can
// kick-off the synch-task on-demand.
URI taskUri = UriUtils.buildUri(owner, taskPath);
SynchronizationTaskService.State taskState = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
long membershipUpdateTimeMicros = taskState.membershipUpdateTimeMicros;
// Start posting and in the middle also start
// synchronization. All POSTs should succeed!
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
TestContext ctx = this.host.testCreate((this.serviceCount * 10) + 1);
for (int i = 0; i < this.serviceCount * 10; i++) {
if (i == 5) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK);
task.factorySelfLink = ExampleService.FACTORY_LINK;
task.factoryStateKind = Utils.buildKind(ExampleService.ExampleServiceState.class);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros + 1;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
Operation post = Operation
.createPost(owner, SynchronizationTaskService.FACTORY_LINK)
.setBody(task)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
Operation post = Operation
.createPost(factoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void commandLineJoinRetries() throws Throwable {
this.host = VerificationHost.create(0);
this.host.start();
ExampleServiceHost nodeA = null;
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
this.setUp(1);
try {
// start a node, supplying a bogus peer. Verify we retry, up to expiration which is
// the operation timeout
nodeA = new ExampleServiceHost();
String id = "nodeA-" + VerificationHost.hostNumber.incrementAndGet();
int bogusPort = 1;
String[] args = {
"--port=0",
"--id=" + id,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolderA.getRoot().getAbsolutePath(),
"--peerNodes=" + "http://127.0.0.1:" + bogusPort
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
// verify we see a specific retry stat
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI statsUri = UriUtils.buildStatsUri(nodeGroupUri);
this.host.waitFor("expected stat did not converge", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsUri);
ServiceStat st = stats.entries.get(NodeGroupService.STAT_NAME_JOIN_RETRY_COUNT);
if (st == null || st.latestValue < 1) {
return false;
}
return true;
});
} finally {
if (nodeA != null) {
nodeA.stop();
tmpFolderA.delete();
}
}
}
@Test
public void synchronizationOnDemandLoad() throws Throwable {
// Setup peer nodes
setUp(this.nodeCount);
long intervalMicros = TimeUnit.MILLISECONDS.toMicros(200);
// Start the ODL Factory service on all the peers.
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
// Reduce cache clear delay to short duration
// to cause ODL service stops.
h.setServiceCacheClearDelayMicros(h.getMaintenanceIntervalMicros());
// create an on demand load factory and services
OnDemandLoadFactoryService.create(h);
}
// join the nodes and set full quorum.
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Create a few child-services.
VerificationHost h = this.host.getPeerHost();
Map<URI, ExampleServiceState> childServices = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = UUID.randomUUID().toString();
o.setBody(initialState);
},
UriUtils.buildFactoryUri(h, OnDemandLoadFactoryService.class));
// Verify that each peer host reports the correct value for ODL stop count.
for (VerificationHost vh : this.host.getInProcessHostMap().values()) {
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(vh, this.serviceCount));
}
// Add a new host to the cluster.
VerificationHost newHost = this.host.setUpLocalPeerHost(0, h.getMaintenanceIntervalMicros(),
null);
newHost.setServiceCacheClearDelayMicros(intervalMicros);
OnDemandLoadFactoryService.create(newHost);
this.host.joinNodesAndVerifyConvergence(this.nodeCount + 1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Do GETs on each previously created child services by calling the newly added host.
// This will trigger synchronization for the child services.
this.host.log(Level.INFO, "Verifying synchronization for ODL services");
for (Entry<URI, ExampleServiceState> childService : childServices.entrySet()) {
String childServicePath = childService.getKey().getPath();
ExampleServiceState state = this.host.getServiceState(null,
ExampleServiceState.class, UriUtils.buildUri(newHost, childServicePath));
assertNotNull(state);
}
// Verify that the new peer host reports the correct value for ODL stop count.
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(newHost, this.serviceCount));
}
private boolean checkOdlServiceStopCount(VerificationHost host, int serviceCount)
throws Throwable {
ServiceStat stopCount = host
.getServiceStats(host.getManagementServiceUri())
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
if (stopCount == null || stopCount.latestValue < serviceCount) {
this.host.log(Level.INFO,
"Current stopCount is %s",
(stopCount != null) ? String.valueOf(stopCount.latestValue) : "null");
return false;
}
return true;
}
@Test
public void customNodeGroupWithObservers() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
Logger.getAnonymousLogger().info("Iteration: " + i);
verifyCustomNodeGroupWithObservers();
tearDown();
}
}
private void verifyCustomNodeGroupWithObservers() throws Throwable {
setUp(this.nodeCount);
// on one of the hosts create the custom group but with self as an observer. That peer should
// never receive replicated or broadcast requests
URI observerHostUri = this.host.getPeerHostUri();
ServiceHostState observerHostState = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_MANAGEMENT));
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerHostState.id;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerHostUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
final String customFactoryLink = "custom-factory";
// start a node selector attached to the custom group
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
NodeSelectorState initialState = new NodeSelectorState();
initialState.nodeGroupLink = CUSTOM_NODE_GROUP;
h.startServiceAndWait(new ConsistentHashingNodeSelectorService(),
CUSTOM_GROUP_NODE_SELECTOR, initialState);
// start the factory that is attached to the custom group selector
h.startServiceAndWait(ExampleFactoryServiceWithCustomSelector.class, customFactoryLink);
}
URI customNodeGroupServiceOnObserver = UriUtils
.buildUri(observerHostUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
expectedOptionsPerNode.put(customNodeGroupServiceOnObserver,
observerSelfState.options);
this.host.joinNodesAndVerifyConvergence(CUSTOM_NODE_GROUP, this.nodeCount,
this.nodeCount, expectedOptionsPerNode);
// one of the nodes is observer, so we must set quorum to 2 explicitly
this.host.setNodeGroupQuorum(2, customNodeGroupServiceOnObserver);
this.host.waitForNodeSelectorQuorumConvergence(CUSTOM_GROUP_NODE_SELECTOR, 2);
this.host.waitForNodeGroupIsAvailableConvergence(CUSTOM_NODE_GROUP);
int restartCount = 0;
// verify that the observer node shows up as OBSERVER on all peers, including self
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI customNodeGroupUri = UriUtils.buildUri(hostUri, CUSTOM_NODE_GROUP);
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
customNodeGroupUri);
for (NodeState ns : ngs.nodes.values()) {
if (ns.id.equals(observerHostState.id)) {
assertTrue(ns.options.contains(NodeOption.OBSERVER));
} else {
assertTrue(ns.options.contains(NodeOption.PEER));
}
}
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(customNodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", restartCount, 0);
// join all the nodes through the default group, making sure another group still works
this.host.joinNodesAndVerifyConvergence(this.nodeCount, true);
URI observerFactoryUri = UriUtils.buildUri(observerHostUri, customFactoryLink);
waitForReplicatedFactoryServiceAvailable(observerFactoryUri, CUSTOM_GROUP_NODE_SELECTOR);
// create N services on the custom group, verify none of them got created on the observer.
// We actually post directly to the observer node, which should forward to the other nodes
Map<URI, ExampleServiceState> serviceStatesOnPost = this.host.doFactoryChildServiceStart(
null, this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = Utils.getNowMicrosUtc() + "";
o.setBody(body);
},
observerFactoryUri);
ServiceDocumentQueryResult r = this.host.getFactoryState(observerFactoryUri);
assertEquals(0, r.documentLinks.size());
// do a GET on each service and confirm the owner id is never that of the observer node
Map<URI, ExampleServiceState> serviceStatesFromGet = this.host.getServiceState(
null, ExampleServiceState.class, serviceStatesOnPost.keySet());
for (ExampleServiceState s : serviceStatesFromGet.values()) {
if (observerHostState.id.equals(s.documentOwner)) {
throw new IllegalStateException("Observer node reported state for service");
}
}
// create additional example services which are not associated with the custom node group
// and verify that they are always included in queries which target the custom node group
// (e.g. that the query is never executed on the OBSERVER node).
createExampleServices(observerHostUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI serviceUri = UriUtils.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
URI forwardQueryUri = UriUtils.buildForwardRequestUri(serviceUri, null,
CUSTOM_GROUP_NODE_SELECTOR);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(forwardQueryUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Forwarded query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
}
task.querySpec.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.BROADCAST);
task.nodeSelectorLink = CUSTOM_GROUP_NODE_SELECTOR;
URI queryPostUri = UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_QUERY_TASKS);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(queryPostUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Broadcast query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
URI existingNodeGroup = this.host.getPeerNodeGroupUri();
// start more nodes, insert them to existing group, but with no synchronization required
// start some additional nodes
Collection<VerificationHost> existingHosts = this.host.getInProcessHostMap().values();
int additionalHostCount = this.nodeCount;
this.host.setUpPeerHosts(additionalHostCount);
List<ServiceHost> newHosts = Collections.synchronizedList(new ArrayList<>());
newHosts.addAll(this.host.getInProcessHostMap().values());
newHosts.removeAll(existingHosts);
expectedOptionsPerNode.clear();
// join new nodes with existing node group.
TestContext testContext = this.host.testCreate(newHosts.size());
for (ServiceHost h : newHosts) {
URI newCustomNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
JoinPeerRequest joinBody = JoinPeerRequest.create(existingNodeGroup, null);
joinBody.localNodeOptions = EnumSet.of(NodeOption.PEER);
this.host.send(Operation.createPost(newCustomNodeGroupUri)
.setBody(joinBody)
.setCompletion(testContext.getCompletion()));
expectedOptionsPerNode.put(newCustomNodeGroupUri, joinBody.localNodeOptions);
}
testContext.await();
this.host.waitForNodeGroupConvergence(this.host.getNodeGroupMap().values(),
this.host.getNodeGroupMap().size(),
this.host.getNodeGroupMap().size(),
expectedOptionsPerNode, false);
restartCount = 0;
// do another restart check. None of the new nodes should have reported restarts
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI nodeGroupUri = UriUtils.buildUri(hostUri, ServiceUriPaths.DEFAULT_NODE_GROUP);
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(nodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", 0,
restartCount);
}
@Test
public void verifyGossipForObservers() throws Throwable {
setUp(this.nodeCount);
Iterator<Entry<URI, URI>> nodeGroupIterator = this.host.getNodeGroupMap().entrySet()
.iterator();
URI observerUri = nodeGroupIterator.next().getKey();
String observerId = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerUri, ServiceUriPaths.CORE_MANAGEMENT)).id;
// Create a custom node group. Mark one node as OBSERVER and rest as PEER
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerId;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
// Pick a PEER and join it to each node in the node-group
URI peerUri = nodeGroupIterator.next().getKey();
URI peerCustomUri = UriUtils.buildUri(peerUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
Set<URI> customNodeUris = new HashSet<>();
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI nodeCustomUri = UriUtils.buildUri(nodeUri, CUSTOM_NODE_GROUP);
JoinPeerRequest request = new JoinPeerRequest();
request.memberGroupReference = nodeCustomUri;
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(peerCustomUri)
.setBody(request)
.setReferer(this.host.getReferer())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
ctx.await();
expectedOptionsPerNode.put(nodeCustomUri,
EnumSet.of((nodeUri == observerUri)
? NodeOption.OBSERVER : NodeOption.PEER));
customNodeUris.add(nodeCustomUri);
}
// Verify that gossip will propagate the single OBSERVER and the PEER nodes
// to every node in the custom node-group.
this.host.waitForNodeGroupConvergence(
customNodeUris, this.nodeCount, this.nodeCount, expectedOptionsPerNode, false);
}
@Test
public void synchronizationOneByOneWithAbruptNodeShutdown() throws Throwable {
setUp(this.nodeCount);
this.replicationTargetFactoryLink = PeriodicExampleFactoryService.SELF_LINK;
// start the periodic example service factory on each node
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.startServiceAndWait(PeriodicExampleFactoryService.class,
PeriodicExampleFactoryService.SELF_LINK);
}
// On one host, add some services. They exist only on this host and we expect them to synchronize
// across all hosts once this one joins with the group
VerificationHost initialHost = this.host.getPeerHost();
URI hostUriWithInitialState = initialHost.getUri();
Map<String, ExampleServiceState> exampleStatesPerSelfLink = createExampleServices(
hostUriWithInitialState);
URI hostWithStateNodeGroup = UriUtils.buildUri(hostUriWithInitialState,
ServiceUriPaths.DEFAULT_NODE_GROUP);
// before start joins, verify isolated factory synchronization is done
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
// join a node, with no state, one by one, to the host with state.
// The steps are:
// 1) set quorum to node group size + 1
// 2) Join new empty node with existing node group
// 3) verify convergence of factory state
// 4) repeat
List<URI> joinedHosts = new ArrayList<>();
Map<URI, URI> factories = new HashMap<>();
factories.put(hostWithStateNodeGroup, UriUtils.buildUri(hostWithStateNodeGroup,
this.replicationTargetFactoryLink));
joinedHosts.add(hostWithStateNodeGroup);
int fullQuorum = 1;
for (URI nodeGroupUri : this.host.getNodeGroupMap().values()) {
// skip host with state
if (hostWithStateNodeGroup.equals(nodeGroupUri)) {
continue;
}
this.host.log("Setting quorum to %d, already joined: %d",
fullQuorum + 1, joinedHosts.size());
// set quorum to expected full node group size, for the setup hosts
this.host.setNodeGroupQuorum(++fullQuorum);
this.host.testStart(1);
// join empty node, with node with state
this.host.joinNodeGroup(hostWithStateNodeGroup, nodeGroupUri, fullQuorum);
this.host.testWait();
joinedHosts.add(nodeGroupUri);
factories.put(nodeGroupUri, UriUtils.buildUri(nodeGroupUri,
this.replicationTargetFactoryLink));
this.host.waitForNodeGroupConvergence(joinedHosts, fullQuorum, fullQuorum, true);
this.host.waitForNodeGroupIsAvailableConvergence(nodeGroupUri.getPath(), joinedHosts);
this.waitForReplicatedFactoryChildServiceConvergence(
factories,
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker, exampleStatesPerSelfLink.size(),
0);
// Do updates, which will verify that the services are converged in terms of ownership.
// Since we also synchronize on demand, if there was any discrepancy, after updates, the
// services will converge
doExampleServicePatch(exampleStatesPerSelfLink,
joinedHosts.get(0));
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink, initialHost, joinedHosts, 0, 1,
ownerIds.size() - 1);
}
doNodeStopWithUpdates(exampleStatesPerSelfLink);
}
private void doExampleServicePatch(Map<String, ExampleServiceState> states,
URI nodeGroupOnSomeHost) throws Throwable {
this.host.log("Starting PATCH to %d example services", states.size());
TestContext ctx = this.host
.testCreate(this.updateCount * states.size());
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
for (int i = 0; i < this.updateCount; i++) {
for (Entry<String, ExampleServiceState> e : states.entrySet()) {
ExampleServiceState st = Utils.clone(e.getValue());
st.counter = (long) i;
Operation patch = Operation
.createPatch(UriUtils.buildUri(nodeGroupOnSomeHost, e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
this.host.log("Done with PATCH to %d example services", states.size());
}
public void doNodeStopWithUpdates(Map<String, ExampleServiceState> exampleStatesPerSelfLink)
throws Throwable {
this.host.log("Starting to stop nodes and send updates");
VerificationHost remainingHost = this.host.getPeerHost();
Collection<VerificationHost> hostsToStop = new ArrayList<>(this.host.getInProcessHostMap()
.values());
hostsToStop.remove(remainingHost);
List<URI> targetServices = new ArrayList<>();
for (String link : exampleStatesPerSelfLink.keySet()) {
// build the URIs using the host we plan to keep, so the maps we use below to lookup
// stats from URIs, work before and after node stop
targetServices.add(UriUtils.buildUri(remainingHost, link));
}
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(this.host.getTimeoutSeconds() / 3);
}
// capture current stats from each service
Map<URI, ServiceStats> prevStats = verifyMaintStatsAfterSynchronization(targetServices,
null);
stopHostsAndVerifyQueuing(hostsToStop, remainingHost, targetServices);
// its important to verify document ownership before we do any updates on the services.
// This is because we verify, that even without any on demand synchronization,
// the factory driven synchronization set the services in the proper state
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
List<URI> remainingHosts = new ArrayList<>(this.host.getNodeGroupMap().keySet());
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink,
this.host.getInProcessHostMap().values().iterator().next(),
remainingHosts, 0, 1,
ownerIds.size() - 1);
// confirm maintenance is back up and running on all services
verifyMaintStatsAfterSynchronization(targetServices, prevStats);
// nodes are stopped, do updates again, quorum is relaxed, they should work
doExampleServicePatch(exampleStatesPerSelfLink, remainingHost.getUri());
this.host.log("Done with stop nodes and send updates");
}
private void verifyDynamicMaintOptionToggle(Map<String, ExampleServiceState> childStates) {
List<URI> targetServices = new ArrayList<>();
childStates.keySet().forEach((l) -> targetServices.add(this.host.getPeerServiceUri(l)));
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
Map<URI, ServiceConfiguration> configPerService = this.host.getServiceState(
null, ServiceConfiguration.class, targetServiceConfig);
for (ServiceConfiguration cfg : configPerService.values()) {
assertTrue(!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE));
}
for (URI child : targetServices) {
this.host.toggleServiceOptions(child,
EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE),
null);
}
verifyMaintStatsAfterSynchronization(targetServices, null);
}
private Map<URI, ServiceStats> verifyMaintStatsAfterSynchronization(List<URI> targetServices,
Map<URI, ServiceStats> statsPerService) {
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
if (statsPerService == null) {
statsPerService = new HashMap<>();
}
final Map<URI, ServiceStats> previousStatsPerService = statsPerService;
this.host.waitFor(
"maintenance not enabled",
() -> {
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, targetServiceStats);
for (Entry<URI, ServiceStats> currentEntry : stats.entrySet()) {
ServiceStats previousStats = previousStatsPerService.get(currentEntry
.getKey());
ServiceStats currentStats = currentEntry.getValue();
ServiceStat previousMaintStat = previousStats == null ? new ServiceStat()
: previousStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
double previousValue = previousMaintStat == null ? 0L
: previousMaintStat.latestValue;
ServiceStat maintStat = currentStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null || maintStat.latestValue <= previousValue) {
return false;
}
}
previousStatsPerService.putAll(stats);
return true;
});
return statsPerService;
}
private Map<String, ExampleServiceState> createExampleServices(URI hostUri) throws Throwable {
URI factoryUri = UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink);
this.host.log("POSTing children to %s", hostUri);
// add some services on one of the peers, so we can verify the get synchronized after they all join
Map<URI, ExampleServiceState> exampleStates = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
}, factoryUri);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
for (ExampleServiceState s : exampleStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
return exampleStatesPerSelfLink;
}
@Test
public void synchronizationWithPeerNodeListAndDuplicates()
throws Throwable {
ExampleServiceHost h = null;
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
setUp(this.nodeCount);
// the hosts are started, but not joined. We need to relax the quorum for any updates
// to go through
this.host.setNodeGroupQuorum(1);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
// add the *same* service instance, all *all* peers, so we force synchronization and epoch
// change on an instance that exists everywhere
int dupServiceCount = this.serviceCount;
AtomicInteger counter = new AtomicInteger();
Map<URI, ExampleServiceState> dupStates = new HashMap<>();
for (VerificationHost v : this.host.getInProcessHostMap().values()) {
counter.set(0);
URI factoryUri = UriUtils.buildFactoryUri(v,
ExampleService.class);
dupStates = this.host.doFactoryChildServiceStart(
null,
dupServiceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.documentSelfLink = "duplicateExampleInstance-"
+ counter.incrementAndGet();
s.name = s.documentSelfLink;
o.setBody(s);
}, factoryUri);
}
for (ExampleServiceState s : dupStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
// increment to account for link found on all nodes
this.serviceCount = exampleStatesPerSelfLink.size();
// create peer argument list, all the nodes join.
Collection<URI> peerNodeGroupUris = new ArrayList<>();
StringBuilder peerNodes = new StringBuilder();
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peerNodeGroupUris.add(UriUtils.buildUri(peer, ServiceUriPaths.DEFAULT_NODE_GROUP));
peerNodes.append(peer.getUri().toString()).append(",");
}
CountDownLatch notifications = new CountDownLatch(this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
this.host.subscribeForNodeGroupConvergence(nodeGroup, this.nodeCount + 1,
(o, e) -> {
if (e != null) {
this.host.log("Error in notificaiton: %s", Utils.toString(e));
return;
}
notifications.countDown();
});
}
// now start a new Host and supply the already created peer, then observe the automatic
// join
h = new ExampleServiceHost();
int quorum = this.host.getPeerCount() + 1;
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--port=0",
"--id=" + mainHostId,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + peerNodes.toString()
};
h.initialize(args);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
h.start();
URI mainHostNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
int totalCount = this.nodeCount + 1;
peerNodeGroupUris.add(mainHostNodeGroupUri);
this.host.waitForNodeGroupIsAvailableConvergence();
this.host.waitForNodeGroupConvergence(peerNodeGroupUris, totalCount,
totalCount, true);
this.host.setNodeGroupQuorum(quorum, mainHostNodeGroupUri);
this.host.setNodeGroupQuorum(quorum);
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
int peerNodeCount = h.getInitialPeerHosts().size();
// include self in peers
assertTrue(totalCount >= peerNodeCount + 1);
// Before factory synch is complete, make sure POSTs to existing services fail,
// since they are not marked idempotent.
verifyReplicatedInConflictPost(dupStates);
// now verify all nodes synchronize and see the example service instances that existed on the single
// host
waitForReplicatedFactoryChildServiceConvergence(
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker,
this.serviceCount, 0);
// Send some updates after the full group has formed and verify the updates are seen by services on all nodes
doStateUpdateReplicationTest(Action.PATCH, this.serviceCount, this.updateCount, 0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
exampleStatesPerSelfLink);
URI exampleFactoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(exampleFactoryUri, ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
} finally {
this.host.log("test finished");
if (h != null) {
h.stop();
tmpFolder.delete();
}
}
}
private void verifyReplicatedInConflictPost(Map<URI, ExampleServiceState> dupStates)
throws Throwable {
// Its impossible to guarantee that this runs during factory synch. It might run before,
// it might run during, it might run after. Since we runs 1000s of tests per day, CI
// will let us know if the production code works. Here, we add a small sleep so we increase
// chance we overlap with factory synchronization.
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(
this.host.getPeerHost().getMaintenanceIntervalMicros()));
// Issue a POST for a service we know exists and expect failure, since the example service
// is not marked IDEMPOTENT. We expect CONFLICT error code, but if synchronization is active
// we want to confirm we dont get 500, but the 409 is preserved
TestContext ctx = this.host.testCreate(dupStates.size());
for (ExampleServiceState st : dupStates.values()) {
URI factoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
Operation post = Operation.createPost(factoryUri).setBody(st)
.setCompletion((o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
ctx.failIteration(new IllegalStateException(
"Expected conflict status, got " + o.getStatusCode()));
return;
}
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"Expected failure on duplicate POST"));
});
this.host.send(post);
}
this.host.testWait(ctx);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopOnDemandLoad() throws Throwable {
tearDown();
for (int i = 0; i < this.testIterationCount; i++) {
setUpOnDemandLoad();
int hostStopCount = 2;
doReplicationWithQuorumAfterAbruptNodeStop(hostStopCount);
this.host.log("Done with iteration %d", i);
tearDown();
this.host = null;
}
}
private void doReplicationWithQuorumAfterAbruptNodeStop(int hostStopCount)
throws Throwable {
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop minority number of hosts - quorum is still intact
int i = 0;
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(e.getValue());
if (++i >= hostStopCount) {
break;
}
}
// do some updates with strong quorum enabled
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopMultiLocation()
throws Throwable {
// we need 6 nodes, 3 in each location
this.nodeCount = 6;
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
this.isMultiLocationTest = true;
if (this.host == null) {
// create node group, join nodes and set local majority quorum
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(2);
}
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop hosts in location "L2"
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
VerificationHost h = e.getValue();
if (h.getLocation().equals(VerificationHost.LOCATION2)) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(h);
}
}
// do some updates
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
/**
* This test validates that if a host, joined in a peer node group, stops/fails and another
* host, listening on the same address:port, rejoins, the existing peer members will mark the
* OLD host instance as FAILED, and mark the new instance, with the new ID as HEALTHY
*
* @throws Throwable
*/
@Test
public void nodeRestartWithSameAddressDifferentId() throws Throwable {
int failedNodeCount = 1;
int afterFailureQuorum = this.nodeCount - failedNodeCount;
setUp(this.nodeCount);
setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(5));
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.log("Stopping node");
// relax quorum for convergence check
this.host.setNodeGroupQuorum(afterFailureQuorum);
// we should now have N nodes, that see each other. Stop one of the
// nodes, and verify the other host's node group deletes the entry
List<ServiceHostState> hostStates = stopHostsToSimulateFailure(failedNodeCount);
URI remainingPeerNodeGroup = this.host.getPeerNodeGroupUri();
// wait for convergence of the remaining peers, before restarting. The failed host
// should be marked FAILED, otherwise we will not converge
this.host.waitForNodeGroupConvergence(this.nodeCount - failedNodeCount);
ServiceHostState stoppedHostState = hostStates.get(0);
// start a new HOST, with a new ID, but with the same address:port as the one we stopped
this.host.testStart(1);
VerificationHost newHost = this.host.setUpLocalPeerHost(stoppedHostState.httpPort,
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null);
this.host.testWait();
// re-join the remaining peers
URI newHostNodeGroupService = UriUtils
.buildUri(newHost.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.joinNodeGroup(newHostNodeGroupService, remainingPeerNodeGroup);
this.host.testWait();
// now wait for convergence. If the logic is correct, the old HOST, that listened on the
// same port as the new host, should stay in the FAILED state, but the new host should
// be marked as HEALTHY
this.host.waitForNodeGroupConvergence(this.nodeCount);
}
public void setMaintenanceIntervalMillis(long defaultMaintIntervalMillis) {
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
// set short interval so failure detection and convergence happens quickly
h1.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(defaultMaintIntervalMillis));
}
}
@Test
public void synchronizationRequestQueuing() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
VerificationHost peerHost = this.host.getPeerHost();
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(peerHost, 1, exampleUris, null);
URI instanceUri = exampleUris.get(0);
ExampleServiceState synchState = new ExampleServiceState();
synchState.documentSelfLink = UriUtils.getLastPathSegment(instanceUri);
TestContext ctx = this.host.testCreate(this.updateCount);
for (int i = 0; i < this.updateCount; i++) {
Operation op = Operation.createPost(peerHost, ExampleService.FACTORY_LINK)
.setBody(synchState)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(op);
}
ctx.await();
}
@Test
public void enforceHighQuorumWithNodeConcurrentStop()
throws Throwable {
int hostRestartCount = 2;
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(1);
}
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.host.setNodeGroupQuorum((this.nodeCount + 1) / 2);
// do some replication with strong quorum enabled
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
long now = Utils.getNowMicrosUtc();
validatePerOperationReplicationQuorum(childStates, now);
// expect failure, since we will stop some hosts, break quorum
this.expectFailure = true;
// when quorum is not met the runtime will just queue requests until expiration, so
// we set expiration to something quick. Some requests will make it past queuing
// and will fail because replication quorum is not met
long opTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(500);
setOperationTimeoutMicros(opTimeoutMicros);
int i = 0;
for (URI h : this.host.getInProcessHostMap().keySet()) {
this.expectedFailedHosts.add(h);
if (++i >= hostRestartCount) {
break;
}
}
// stop one host right away
stopHostsToSimulateFailure(1);
// concurrently with the PATCH requests below, stop another host
Runnable r = () -> {
stopHostsToSimulateFailure(hostRestartCount - 1);
// add a small bit of time slop since its feasible a host completed a operation *after* we stopped it,
// the netty handlers are stopped in async (not forced) mode
this.expectedFailureStartTimeMicros = Utils.getNowMicrosUtc()
+ TimeUnit.MILLISECONDS.toMicros(250);
};
this.host.schedule(r, 1, TimeUnit.MILLISECONDS);
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
this.updateCount,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), this.updateCount,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), 1,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
private void validatePerOperationReplicationQuorum(Map<String, ExampleServiceState> childStates,
long now) throws Throwable {
Random r = new Random();
// issue a patch, with per operation quorum set, verify it applied
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(body);
// add an explicit replication count header, using either the "all" value, or an
// explicit node count
if (r.nextBoolean()) {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
} else {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
this.nodeCount + "");
}
this.host.send(patch);
this.host.testWait(ctx);
// Go to each peer, directly to their index, and verify update is present. This is not
// proof the per operation quorum was applied "synchronously", before the response
// was sent, but over many runs, if there is a race or its applied asynchronously,
// we will see failures
for (URI hostBaseUri : this.host.getNodeGroupMap().keySet()) {
URI indexUri = UriUtils.buildUri(hostBaseUri, ServiceUriPaths.CORE_DOCUMENT_INDEX);
indexUri = UriUtils.buildIndexQueryUri(indexUri,
e.getKey(), true, false, ServiceOption.PERSISTENCE);
ExampleServiceState afterState = this.host.getServiceState(null,
ExampleServiceState.class, indexUri);
assertEquals(body.counter, afterState.counter);
}
}
this.host.toggleNegativeTestMode(true);
// verify that if we try to set per operation quorum too high, request will fail
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
(this.nodeCount * 2) + "")
.setCompletion(ctx.getExpectedFailureCompletion())
.setBody(body);
this.host.send(patch);
this.host.testWait(ctx);
break;
}
this.host.toggleNegativeTestMode(false);
}
private void setOperationTimeoutMicros(long opTimeoutMicros) {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setOperationTimeOutMicros(opTimeoutMicros);
}
this.host.setOperationTimeOutMicros(opTimeoutMicros);
}
/**
* This test creates N local service hosts, each with K instances of a replicated service. The
* service will create a query task, also replicated, and self patch itself. The test makes sure
* all K instances, on all N hosts see the self PATCHs AND that the query tasks exist on all
* hosts
*
* @throws Throwable
*/
@Test
public void replicationWithCrossServiceDependencies() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI hostUri = this.host.getPeerServiceUri(null);
URI factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> ownerSelectedServices = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri, ReplicationFactoryTestService.STRICT_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ReplicationTestServiceState.class));
q.query.addBooleanClause(kindClause);
Query nameClause = new Query();
nameClause.setTermPropertyName("stringField")
.setTermMatchValue("*")
.setTermMatchType(MatchType.WILDCARD);
q.query.addBooleanClause(nameClause);
// expect results for strict and regular service instances
int expectedServiceCount = this.serviceCount * 3;
Date exp = this.host.getTestExpiration();
while (exp.after(new Date())) {
// create N direct query tasks. Direct tasks complete in the context of the POST to the
// query task factory
int count = 10;
URI queryFactoryUri = UriUtils.extendUri(hostUri,
ServiceUriPaths.CORE_QUERY_TASKS);
TestContext testContext = this.host.testCreate(count);
Map<String, QueryTask> taskResults = new ConcurrentSkipListMap<>();
for (int i = 0; i < count; i++) {
QueryTask qt = QueryTask.create(q);
qt.taskInfo.isDirect = true;
qt.documentSelfLink = UUID.randomUUID().toString();
Operation startPost = Operation
.createPost(queryFactoryUri)
.setBody(qt)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
qt.results = rsp.results;
qt.documentOwner = rsp.documentOwner;
taskResults.put(rsp.documentSelfLink, qt);
testContext.complete();
});
this.host.send(startPost);
}
testContext.await();
this.host.logThroughput();
boolean converged = true;
for (QueryTask qt : taskResults.values()) {
if (qt.results == null || qt.results.documentLinks == null) {
throw new IllegalStateException("Missing results");
}
if (qt.results.documentLinks.size() != expectedServiceCount) {
this.host.log("%s", Utils.toJsonHtml(qt));
converged = false;
break;
}
}
if (!converged) {
Thread.sleep(250);
continue;
}
break;
}
if (exp.before(new Date())) {
throw new TimeoutException();
}
// Negative tests: Make sure custom error response body is preserved
URI childUri = ownerSelectedServices.keySet().iterator().next();
TestContext testContext = this.host.testCreate(1);
ReplicationTestServiceState badRequestBody = new ReplicationTestServiceState();
this.host
.send(Operation
.createPatch(childUri)
.setBody(badRequestBody)
.setCompletion(
(o, e) -> {
if (e == null) {
testContext.fail(new IllegalStateException(
"Expected failure"));
return;
}
ReplicationTestServiceErrorResponse rsp = o
.getBody(ReplicationTestServiceErrorResponse.class);
if (!ReplicationTestServiceErrorResponse.KIND
.equals(rsp.documentKind)) {
testContext.fail(new IllegalStateException(
"Expected custom response body"));
return;
}
testContext.complete();
}));
testContext.await();
// verify that each owner selected service reports stats from the same node that reports state
Map<URI, ReplicationTestServiceState> latestState = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
Map<String, String> ownerIdPerLink = new HashMap<>();
List<URI> statsUris = new ArrayList<>();
for (ReplicationTestServiceState state : latestState.values()) {
URI statsUri = this.host.getPeerServiceUri(UriUtils.buildUriPath(
state.documentSelfLink, ServiceHost.SERVICE_URI_SUFFIX_STATS));
ownerIdPerLink.put(state.documentSelfLink, state.documentOwner);
statsUris.add(statsUri);
}
Map<URI, ServiceStats> latestStats = this.host.getServiceState(null, ServiceStats.class,
statsUris);
for (ServiceStats perServiceStats : latestStats.values()) {
String serviceLink = UriUtils.getParentPath(perServiceStats.documentSelfLink);
String expectedOwnerId = ownerIdPerLink.get(serviceLink);
if (expectedOwnerId.equals(perServiceStats.documentOwner)) {
continue;
}
throw new IllegalStateException("owner routing issue with stats: "
+ Utils.toJsonHtml(perServiceStats));
}
exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
// verify all factories report same number of children
for (VerificationHost peerHost : this.host.getInProcessHostMap().values()) {
factoryUri = UriUtils.buildUri(peerHost,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
ServiceDocumentQueryResult rsp = this.host.getFactoryState(factoryUri);
if (rsp.documentLinks.size() != latestState.size()) {
this.host.log("Factory %s reporting %d children, expected %d", factoryUri,
rsp.documentLinks.size(), latestState.size());
isConverged = false;
break;
}
}
if (!isConverged) {
Thread.sleep(250);
continue;
}
break;
}
if (new Date().after(exp)) {
throw new TimeoutException("factories did not converge");
}
this.host.log("Inducing synchronization");
// Induce synchronization on stable node group. No changes should be observed since
// all nodes should have identical state
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
// give synchronization a chance to run, its 100% asynchronous so we can't really tell when each
// child is done, but a small delay should be sufficient for 99.9% of test environments, even under
// load
Thread.sleep(2000);
// verify that example states did not change due to the induced synchronization
Map<URI, ReplicationTestServiceState> latestStateAfter = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
for (Entry<URI, ReplicationTestServiceState> afterEntry : latestStateAfter.entrySet()) {
ReplicationTestServiceState beforeState = latestState.get(afterEntry.getKey());
ReplicationTestServiceState afterState = afterEntry.getValue();
assertEquals(beforeState.documentVersion, afterState.documentVersion);
}
verifyOperationJoinAcrossPeers(latestStateAfter);
}
private Map<URI, ReplicationTestServiceState> doReplicatedServiceFactoryPost(int serviceCount,
Consumer<Operation> setBodyCallback, URI factoryUri) throws Throwable,
InterruptedException, TimeoutException {
ServiceDocumentDescription sdd = this.host
.buildDescription(ReplicationTestServiceState.class);
Map<URI, ReplicationTestServiceState> serviceMap = this.host.doFactoryChildServiceStart(
null, serviceCount, ReplicationTestServiceState.class, setBodyCallback, factoryUri);
Date expiration = this.host.getTestExpiration();
boolean isConverged = true;
Map<URI, String> uriToSignature = new HashMap<>();
while (new Date().before(expiration)) {
isConverged = true;
uriToSignature.clear();
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
URI baseUri = e.getKey();
VerificationHost h = e.getValue();
URI u = UriUtils.buildUri(baseUri, factoryUri.getPath());
u = UriUtils.buildExpandLinksQueryUri(u);
ServiceDocumentQueryResult r = this.host.getFactoryState(u);
if (r.documents.size() != serviceCount) {
this.host.log("instance count mismatch, expected %d, got %d, from %s",
serviceCount, r.documents.size(), u);
isConverged = false;
break;
}
for (URI instanceUri : serviceMap.keySet()) {
ReplicationTestServiceState initialState = serviceMap.get(instanceUri);
ReplicationTestServiceState newState = Utils.fromJson(
r.documents.get(instanceUri.getPath()),
ReplicationTestServiceState.class);
if (newState.documentVersion == 0) {
this.host.log("version mismatch, expected %d, got %d, from %s", 0,
newState.documentVersion, instanceUri);
isConverged = false;
break;
}
if (initialState.stringField.equals(newState.stringField)) {
this.host.log("field mismatch, expected %s, got %s, from %s",
initialState.stringField, newState.stringField, instanceUri);
isConverged = false;
break;
}
if (newState.queryTaskLink == null) {
this.host.log("missing query task link from %s", instanceUri);
isConverged = false;
break;
}
// Only instances with OWNER_SELECTION patch string field with self link so bypass this check
if (!newState.documentSelfLink
.contains(ReplicationFactoryTestService.STRICT_SELF_LINK)
&& !newState.documentSelfLink
.contains(ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK)
&& !newState.stringField.equals(newState.documentSelfLink)) {
this.host.log("State not in final state");
isConverged = false;
break;
}
String sig = uriToSignature.get(instanceUri);
if (sig == null) {
sig = Utils.computeSignature(newState, sdd);
uriToSignature.put(instanceUri, sig);
} else {
String newSig = Utils.computeSignature(newState, sdd);
if (!sig.equals(newSig)) {
isConverged = false;
this.host.log("signature mismatch, expected %s, got %s, from %s",
sig, newSig, instanceUri);
}
}
ProcessingStage ps = h.getServiceStage(newState.queryTaskLink);
if (ps == null || ps != ProcessingStage.AVAILABLE) {
this.host.log("missing query task service from %s", newState.queryTaskLink,
instanceUri);
isConverged = false;
break;
}
}
if (isConverged == false) {
break;
}
}
if (isConverged == true) {
break;
}
Thread.sleep(100);
}
if (!isConverged) {
throw new TimeoutException("States did not converge");
}
return serviceMap;
}
@Test
public void replicationWithOutOfOrderPostAndUpdates() throws Throwable {
// This test verifies that if a replica receives
// replication requests of POST and PATCH/PUT
// out-of-order, xenon can still handle it
// by doing retries for failed out-of-order
// updates. To verify this, we setup a node
// group and set quorum to just 1, so that the post
// returns as soon as the owner commits the post,
// so that we increase the chance of out-of-order
// update replication requests.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
state.counter = 1L;
VerificationHost peer = this.host.getPeerHost();
TestContext ctx = this.host.testCreate(this.serviceCount * this.updateCount);
for (int i = 0; i < this.serviceCount; i++) {
Operation post = Operation
.createPost(peer, ExampleService.FACTORY_LINK)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
for (int k = 0; k < this.updateCount; k++) {
ExampleServiceState update = new ExampleServiceState();
state.counter = (long) k;
Operation patch = Operation
.createPatch(peer, rsp.documentSelfLink)
.setBody(update)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
});
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void replication() throws Throwable {
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replicationSsl() throws Throwable {
this.replicationUriScheme = ServiceHost.HttpScheme.HTTPS_ONLY;
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replication1x() throws Throwable {
this.replicationFactor = 1L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication1xExampleFactoryService.SELF_LINK;
doReplication();
}
@Test
public void replication3x() throws Throwable {
this.replicationFactor = 3L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_3X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication3xExampleFactoryService.SELF_LINK;
this.nodeCount = Math.max(5, this.nodeCount);
doReplication();
}
private void doReplication() throws Throwable {
this.isPeerSynchronizationEnabled = false;
CommandLineArgumentParser.parseFromProperties(this);
Date expiration = new Date();
if (this.testDurationSeconds > 0) {
expiration = new Date(expiration.getTime()
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
}
Map<Action, Long> elapsedTimePerAction = new HashMap<>();
Map<Action, Long> countPerAction = new HashMap<>();
long totalOperations = 0;
int iterationCount = 0;
do {
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// for limited replication factor, we will still set the quorum high, and expect
// the limited replication selector to use the minimum between majority of replication
// factor, versus node group membership quorum
this.host.setNodeGroupQuorum(this.nodeCount);
// since we have disabled peer synch, trigger it explicitly so factories become available
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
waitForReplicationFactoryConvergence();
if (this.replicationUriScheme == ServiceHost.HttpScheme.HTTPS_ONLY) {
// confirm nodes are joined using HTTPS group references
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
assertTrue(UriUtils.HTTPS_SCHEME.equals(nodeGroup.getScheme()));
}
}
}
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, countPerAction, elapsedTimePerAction);
totalOperations += this.serviceCount;
if (this.testDurationSeconds == 0) {
// various validation tests, executed just once, ignored in long running test
this.host.doExampleServiceUpdateAndQueryByVersion(this.host.getPeerHostUri(),
this.serviceCount);
verifyReplicatedForcedPostAfterDelete(childStates);
verifyInstantNotFoundFailureOnBadLinks();
verifyReplicatedIdempotentPost(childStates);
verifyDynamicMaintOptionToggle(childStates);
}
totalOperations += this.serviceCount;
if (expiration == null) {
expiration = this.host.getTestExpiration();
}
int expectedVersion = this.updateCount;
if (!this.host.isStressTest()
&& (this.host.getPeerCount() > 16
|| this.serviceCount * this.updateCount > 100)) {
this.host.setStressTest(true);
}
long opCount = this.serviceCount * this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
expectedVersion += this.updateCount;
totalOperations += opCount;
childStates = doStateUpdateReplicationTest(Action.PUT, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += opCount;
Date queryExp = this.host.getTestExpiration();
if (expiration.after(queryExp)) {
queryExp = expiration;
}
while (new Date().before(queryExp)) {
Set<String> links = verifyReplicatedServiceCountWithBroadcastQueries();
if (links.size() < this.serviceCount) {
this.host.log("Found only %d links across nodes, retrying", links.size());
Thread.sleep(500);
continue;
}
break;
}
totalOperations += this.serviceCount;
if (queryExp.before(new Date())) {
throw new TimeoutException();
}
expectedVersion += 1;
doStateUpdateReplicationTest(Action.DELETE, this.serviceCount, 1,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += this.serviceCount;
// compute the binary serialized payload, and the JSON payload size
ExampleServiceState st = childStates.values().iterator().next();
String json = Utils.toJson(st);
int byteCount = KryoSerializers.serializeDocument(st, 4096).position();
int jsonByteCount = json.getBytes(Utils.CHARSET).length;
// estimate total bytes transferred between nodes. The owner receives JSON from the client
// but then uses binary serialization to the N-1 replicas
long totalBytes = jsonByteCount * totalOperations
+ (this.nodeCount - 1) * byteCount * totalOperations;
this.host.log(
"Bytes per json:%d, per binary: %d, Total operations: %d, Total bytes:%d",
jsonByteCount,
byteCount,
totalOperations,
totalBytes);
if (iterationCount++ < 2 && this.testDurationSeconds > 0) {
// ignore data during JVM warm-up, first two iterations
countPerAction.clear();
elapsedTimePerAction.clear();
}
} while (new Date().before(expiration) && this.totalOperationLimit > totalOperations);
logHostStats();
logPerActionThroughput(elapsedTimePerAction, countPerAction);
this.host.doNodeGroupStatsVerification(this.host.getNodeGroupMap());
}
private void logHostStats() {
for (URI u : this.host.getNodeGroupMap().keySet()) {
URI mgmtUri = UriUtils.buildUri(u, ServiceHostManagementService.SELF_LINK);
mgmtUri = UriUtils.buildStatsUri(mgmtUri);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, mgmtUri);
this.host.log("%s: %s", u, Utils.toJsonHtml(stats));
}
}
private void logPerActionThroughput(Map<Action, Long> elapsedTimePerAction,
Map<Action, Long> countPerAction) {
for (Action a : EnumSet.allOf(Action.class)) {
Long count = countPerAction.get(a);
if (count == null) {
continue;
}
Long elapsedMicros = elapsedTimePerAction.get(a);
double thpt = (count * 1.0) / (1.0 * elapsedMicros);
thpt *= 1000000;
this.host.log("Total ops for %s: %d, Throughput (ops/sec): %f", a, count, thpt);
}
}
private void updatePerfDataPerAction(Action a, Long startTime, Long opCount,
Map<Action, Long> countPerAction, Map<Action, Long> elapsedTime) {
if (opCount == null || countPerAction != null) {
countPerAction.merge(a, opCount, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
if (startTime == null || elapsedTime == null) {
return;
}
long delta = Utils.getNowMicrosUtc() - startTime;
elapsedTime.merge(a, delta, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
private void verifyReplicatedIdempotentPost(Map<String, ExampleServiceState> childStates)
throws Throwable {
// verify IDEMPOTENT POST conversion to PUT, with replication
// Since the factory is not idempotent by default, enable the option dynamically
Map<URI, URI> exampleFactoryUris = this.host
.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK);
for (URI factoryUri : exampleFactoryUris.values()) {
this.host.toggleServiceOptions(factoryUri,
EnumSet.of(ServiceOption.IDEMPOTENT_POST), null);
}
TestContext ctx = this.host.testCreate(childStates.size());
for (Entry<String, ExampleServiceState> entry : childStates.entrySet()) {
Operation post = Operation
.createPost(this.host.getPeerServiceUri(ExampleService.FACTORY_LINK))
.setBody(entry.getValue())
.setCompletion(ctx.getCompletion());
this.host.send(post);
}
ctx.await();
}
/**
* Verifies that DELETE actions propagate and commit, and, that forced POST actions succeed
*/
private void verifyReplicatedForcedPostAfterDelete(Map<String, ExampleServiceState> childStates)
throws Throwable {
// delete one of the children, then re-create but with a zero version, using a special
// directive that forces creation
Entry<String, ExampleServiceState> childEntry = childStates.entrySet().iterator().next();
TestContext ctx = this.host.testCreate(1);
Operation delete = Operation
.createDelete(this.host.getPeerServiceUri(childEntry.getKey()))
.setCompletion(ctx.getCompletion());
this.host.send(delete);
ctx.await();
if (!this.host.isRemotePeerTest()) {
this.host.waitFor("services not deleted", () -> {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(childEntry.getKey());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
childEntry.getKey(), h.toString(), stg);
return false;
}
}
return true;
});
}
TestContext postCtx = this.host.testCreate(1);
Operation opPost = Operation
.createPost(this.host.getPeerServiceUri(this.replicationTargetFactoryLink))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE)
.setBody(childEntry.getValue())
.setCompletion((o, e) -> {
if (e != null) {
postCtx.failIteration(e);
} else {
postCtx.completeIteration();
}
});
this.host.send(opPost);
this.host.testWait(postCtx);
}
private void waitForReplicationFactoryConvergence() throws Throwable {
// for code coverage, verify the convenience method on the host also reports available
WaitHandler wh = () -> {
TestContext ctx = this.host.testCreate(1);
boolean[] isReady = new boolean[1];
CompletionHandler ch = (o, e) -> {
if (e != null) {
isReady[0] = false;
} else {
isReady[0] = true;
}
ctx.completeIteration();
};
VerificationHost peerHost = this.host.getPeerHost();
if (peerHost == null) {
NodeGroupUtils.checkServiceAvailability(ch, this.host,
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
} else {
peerHost.checkReplicatedServiceAvailable(ch, this.replicationTargetFactoryLink);
}
ctx.await();
return isReady[0];
};
this.host.waitFor("available check timeout for " + this.replicationTargetFactoryLink, wh);
}
private Set<String> verifyReplicatedServiceCountWithBroadcastQueries()
throws Throwable {
// create a query task, which will execute on a randomly selected node. Since there is no guarantee the node
// selected to execute the query task is the one with all the replicated services, broadcast to all nodes, then
// join the results
URI nodeUri = this.host.getPeerHostUri();
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
URI queryTaskFactoryUri = UriUtils
.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
// send the POST to the forwarding service on one of the nodes, with the broadcast query parameter set
URI forwardingService = UriUtils.buildBroadcastRequestUri(queryTaskFactoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
Set<String> links = new HashSet<>();
TestContext testContext = this.host.testCreate(1);
Operation postQuery = Operation
.createPost(forwardingService)
.setBody(task)
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
NodeGroupBroadcastResponse rsp = o
.getBody(NodeGroupBroadcastResponse.class);
NodeGroupBroadcastResult broadcastResponse = NodeGroupUtils.toBroadcastResult(rsp);
if (broadcastResponse.hasFailure()) {
testContext.fail(new IllegalStateException(
"Failure from query tasks: " + Utils.toJsonHtml(rsp)));
return;
}
// verify broadcast requests should come from all discrete nodes
Set<String> ownerIds = new HashSet<>();
for (PeerNodeResult successResponse : broadcastResponse.successResponses) {
QueryTask qt = successResponse.castBodyTo(QueryTask.class);
this.host.log("Broadcast response from %s %s", qt.documentSelfLink,
qt.documentOwner);
ownerIds.add(qt.documentOwner);
if (qt.results == null) {
this.host.log("Node %s had no results", successResponse.requestUri);
continue;
}
for (String l : qt.results.documentLinks) {
links.add(l);
}
}
testContext.completeIteration();
});
this.host.send(postQuery);
testContext.await();
return links;
}
private void verifyInstantNotFoundFailureOnBadLinks() throws Throwable {
this.host.toggleNegativeTestMode(true);
TestContext testContext = this.host.testCreate(this.serviceCount);
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.complete();
return;
}
// strange, service exists, lets verify
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(o.getUri().getPath());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
o.getUri().getPath(), h.toString(), stg);
}
}
testContext.fail(new Throwable("Expected service to not exist:"
+ o.toString()));
};
// do a negative test: send request to a example child we know does not exist, but disable queuing
// so we get 404 right away
for (int i = 0; i < this.serviceCount; i++) {
URI factoryURI = this.host.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK)
.values().iterator().next();
URI bogusChild = UriUtils.extendUri(factoryURI,
Utils.getNowMicrosUtc() + UUID.randomUUID().toString());
Operation patch = Operation.createPatch(bogusChild)
.setCompletion(c)
.setBody(new ExampleServiceState());
this.host.send(patch);
}
testContext.await();
this.host.toggleNegativeTestMode(false);
}
@Test
public void factorySynchronization() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
factorySynchronizationNoChildren();
factoryDuplicatePost();
}
@Test
public void replicationWithAuthzCacheClear() throws Throwable {
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.setNodeGroupQuorum(this.nodeCount);
VerificationHost groupHost = this.host.getPeerHost();
groupHost.setSystemAuthorizationContext();
// wait for auth related services to be stabilized
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, ResourceGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, RoleService.FACTORY_LINK));
String fooUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"foo@vmware.com");
String barUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"bar@vmware.com");
String bazUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"baz@vmware.com");
// create user, user-group, resource-group, role for foo@vmware.com
// user: /core/authz/users/foo@vmware.com
// user-group: /core/authz/user-groups/foo-user-group
// resource-group: /core/authz/resource-groups/foo-resource-group
// role: /core/authz/roles/foo-role-1
TestContext testContext = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("foo@vmware.com")
.setUserEmail("foo@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setUserGroupName("foo-user-group")
.setResourceGroupName("foo-resource-group")
.setRoleName("foo-role-1")
.setCompletion(testContext.getCompletion())
.start();
testContext.await();
// create another user-group, resource-group, and role for foo@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: /core/authz/role/foo-role-2
TestContext ctxToCreateAnotherRole = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(fooUserLink)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setRoleName("foo-role-2")
.setCompletion(ctxToCreateAnotherRole.getCompletion())
.setupRole();
ctxToCreateAnotherRole.await();
// create user, user-group, resource-group, role for bar@vmware.com
// user: /core/authz/users/bar@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("bar@vmware.com")
.setUserEmail("bar@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBar.getCompletion())
.start();
ctxToCreateBar.await();
// create user, user-group, resource-group, role for baz@vmware.com
// user: /core/authz/users/baz@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBaz = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("baz@vmware.com")
.setUserEmail("baz@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBaz.getCompletion())
.start();
ctxToCreateBaz.await();
AuthorizationContext fooAuthContext = groupHost.assumeIdentity(fooUserLink);
AuthorizationContext barAuthContext = groupHost.assumeIdentity(barUserLink);
AuthorizationContext bazAuthContext = groupHost.assumeIdentity(bazUserLink);
String fooToken = fooAuthContext.getToken();
String barToken = barAuthContext.getToken();
String bazToken = bazAuthContext.getToken();
groupHost.resetSystemAuthorizationContext();
// verify GET will NOT clear cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/users/foo@vmware.com")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/resource-groups/foo-resource-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
// verify deleting role should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user-group should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
// delete the user group associated with the user
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify creating new role should clear the auth cache (using bar@vmware.com)
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
Query q = Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.build();
TestContext ctxToCreateAnotherRoleForBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(barUserLink)
.setResourceGroupName("/core/authz/resource-groups/new-rg")
.setResourceQuery(q)
.setRoleName("bar-role-2")
.setCompletion(ctxToCreateAnotherRoleForBar.getCompletion())
.setupRole();
ctxToCreateAnotherRoleForBar.await();
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
//
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
// Updating the resource group should be able to handle the fact that the user group does not exist
String newResourceGroupLink = "/core/authz/resource-groups/new-rg";
Query updateResourceGroupQuery = Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.query = updateResourceGroupQuery;
this.host.sendAndWaitExpectSuccess(
Operation.createPut(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(resourceGroupState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
// verify patching user should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
UserState userState = new UserState();
userState.userGroupLinks = new HashSet<>();
userState.userGroupLinks.add("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, fooUserLink))
.setBody(userState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user should clear the auth cache
populateAuthCacheInAllPeers(bazAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(groupHost, bazUserLink)));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(bazToken);
// verify patching ResourceGroup should clear the auth cache
// uses "new-rg" resource group that has associated to user bar
TestRequestSender sender = new TestRequestSender(this.host.getPeerHost());
groupHost.setSystemAuthorizationContext();
Operation newResourceGroupGetOp = Operation.createGet(groupHost, newResourceGroupLink);
ResourceGroupState newResourceGroupState = sender.sendAndWait(newResourceGroupGetOp, ResourceGroupState.class);
groupHost.resetSystemAuthorizationContext();
PatchQueryRequest patchBody = PatchQueryRequest.create(newResourceGroupState.query, false);
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(patchBody));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
}
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {
// send a GET request to the ExampleService factory to populate auth cache on each peer.
// since factory is not OWNER_SELECTION service, request goes to the specified node.
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setAuthorizationContext(authContext);
// based on the role created in test, all users have access to ExampleService
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(peer, ExampleService.FACTORY_LINK)));
}
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(authContext.getToken(), true));
}
private void verifyAuthCacheHasClearedInAllPeers(String userToken) {
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(userToken, false));
}
private boolean checkCacheInAllPeers(String token, boolean expectEntries) throws Throwable {
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setSystemAuthorizationContext();
MinimalTestService s = new MinimalTestService();
peer.addPrivilegedService(MinimalTestService.class);
peer.startServiceAndWait(s, UUID.randomUUID().toString(), null);
peer.resetSystemAuthorizationContext();
boolean contextFound = peer.getAuthorizationContext(s, token) != null;
if ((expectEntries && !contextFound) || (!expectEntries && contextFound)) {
return false;
}
}
return true;
}
private void factoryDuplicatePost() throws Throwable, InterruptedException, TimeoutException {
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI factoryUri = this.host
.getPeerServiceUri(ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> states = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
TestContext testContext = serviceHost.testCreate(states.size());
ReplicationTestServiceState initialState = new ReplicationTestServiceState();
for (URI uri : states.keySet()) {
initialState.documentSelfLink = uri.toString().substring(uri.toString()
.lastIndexOf(UriUtils.URI_PATH_CHAR) + 1);
Operation createPost = Operation
.createPost(factoryUri)
.setBody(initialState)
.setCompletion(
(o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
testContext.fail(
new IllegalStateException(
"Incorrect response code received"));
return;
}
testContext.complete();
});
serviceHost.send(createPost);
}
testContext.await();
}
private void factorySynchronizationNoChildren() throws Throwable {
int factoryCount = Math.max(this.serviceCount, 25);
setUp(this.nodeCount);
// start many factories, in each host, so when the nodes join there will be a storm
// of synchronization requests between the nodes + factory instances
TestContext testContext = this.host.testCreate(this.nodeCount * factoryCount);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
for (int i = 0; i < factoryCount; i++) {
Operation startPost = Operation.createPost(
UriUtils.buildUri(h,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, UUID
.randomUUID().toString())))
.setCompletion(testContext.getCompletion());
h.startService(startPost, ExampleService.createFactory());
}
}
testContext.await();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
@Test
public void forwardingAndSelection() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
for (int i = 0; i < this.iterationCount; i++) {
directOwnerSelection();
forwardingToPeerId();
forwardingToKeyHashNode();
broadcast();
}
}
public void broadcast() throws Throwable {
// Do a broadcast on a local, non replicated service. Replicated services can not
// be used with broadcast since they will duplicate the update and potentially route
// to a single node
URI nodeGroup = this.host.getPeerNodeGroupUri();
long c = this.updateCount * this.nodeCount;
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
// we broadcast one update, per service, through one peer. We expect to see
// the same update across all peers, just like with replicated services
nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildBroadcastRequestUri(serviceUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
for (URI baseHostUri : this.host.getNodeGroupMap().keySet()) {
List<URI> uris = new ArrayList<>();
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(baseHostUri, s.documentSelfLink);
uris.add(serviceUri);
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service broadcast failure");
}
}
}
}
public void forwardingToKeyHashNode() throws Throwable {
long c = this.updateCount * this.nodeCount;
Map<String, List<String>> ownersPerServiceLink = new HashMap<>();
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to owner, per service link
// 2) verify the request ended up on the owner the partitioning service predicted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
URI nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildForwardRequestUri(serviceUri,
null,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
this.host.logThroughput();
AtomicInteger assignedLinks = new AtomicInteger();
TestContext testContextForPost = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
// make sure the key is the path to the service. The initial state self link is not a
// path ...
String key = UriUtils.normalizeUriPath(s.documentSelfLink);
s.documentSelfLink = key;
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion((o, e) -> {
if (e != null) {
testContextForPost.fail(e);
return;
}
synchronized (ownersPerServiceLink) {
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
List<String> links = ownersPerServiceLink.get(rsp.ownerNodeId);
if (links == null) {
links = new ArrayList<>();
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
links.add(key);
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
assignedLinks.incrementAndGet();
testContextForPost.complete();
});
this.host.send(post);
}
testContextForPost.await();
assertTrue(assignedLinks.get() == initialStates.size());
// verify the services on the node that should be owner, has modified state
for (Entry<String, List<String>> e : ownersPerServiceLink.entrySet()) {
String nodeId = e.getKey();
List<String> links = e.getValue();
NodeState ns = this.host.getNodeStateMap().get(nodeId);
List<URI> uris = new ArrayList<>();
// make a list of URIs to the services assigned to this peer node
for (String l : links) {
uris.add(UriUtils.buildUri(ns.groupReference, l));
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service forwarding failure");
} else {
}
}
}
}
public void forwardingToPeerId() throws Throwable {
long c = this.updateCount * this.nodeCount;
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to a specific peer id, per service link
// 2) verify the request ended up on the peer we targeted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
s = Utils.clone(s);
// set the owner to be the target node. we will use this to verify it matches
// the id in the state, which is set through a forwarded PATCH
s.documentOwner = peer.getId();
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
VerificationHost peerEntryPoint = this.host.getPeerHost();
// add a custom header and make sure the service sees it in its handler, in the request
// headers, and we see a service response header in our response
String headerName = MinimalTestService.TEST_HEADER_NAME.toLowerCase();
UUID id = UUID.randomUUID();
String headerRequestValue = "request-" + id;
String headerResponseValue = "response-" + id;
TestContext testContextForPut = this.host.testCreate(initialStates.size() * this.nodeCount);
for (ServiceDocument s : initialStates) {
// send a PATCH the id for each document, to each peer. If it routes to the proper peer
// the initial state.documentOwner, will match the state.id
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
// For testing coverage, force the use of the same forwarding service instance.
// We make all request flow from one peer to others, testing both loopback p2p
// and true forwarding. Otherwise, the forwarding happens by directly contacting
// peer we want to land on!
URI localForwardingUri = UriUtils.buildUri(peerEntryPoint.getUri(),
s.documentSelfLink);
// add a query to make sure it does not affect forwarding
localForwardingUri = UriUtils.extendUriWithQuery(localForwardingUri, "k", "v",
"k1", "v1", "k2", "v2");
URI u = UriUtils.buildForwardToPeerUri(localForwardingUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR, EnumSet.noneOf(ServiceOption.class));
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = peer.getId();
this.host.send(Operation.createPut(u)
.addRequestHeader(headerName, headerRequestValue)
.setCompletion(
(o, e) -> {
if (e != null) {
testContextForPut.fail(e);
return;
}
String value = o.getResponseHeader(headerName);
if (value == null || !value.equals(headerResponseValue)) {
testContextForPut.fail(new IllegalArgumentException(
"response header not found"));
return;
}
testContextForPut.complete();
})
.setBody(body));
}
}
testContextForPut.await();
this.host.logThroughput();
TestContext ctx = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation get = Operation.createGet(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
MinimalTestServiceState rsp = o
.getBody(MinimalTestServiceState.class);
if (!rsp.id.equals(rsp.documentOwner)) {
ctx.fail(
new IllegalStateException("Expected: "
+ rsp.documentOwner + " was: " + rsp.id));
} else {
ctx.complete();
}
});
this.host.send(get);
}
}
ctx.await();
// Do a negative test: Send a request that will induce failure in the service handler and
// make sure we receive back failure, with a ServiceErrorResponse body
this.host.toggleDebuggingMode(true);
TestContext testCxtForPut = this.host.testCreate(this.host.getInProcessHostMap().size());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
ServiceDocument s = initialStates.get(0);
URI serviceUri = UriUtils.buildUri(peerEntryPoint.getUri(), s.documentSelfLink);
URI u = UriUtils.buildForwardToPeerUri(serviceUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
null);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
// setting id to null will cause validation failure.
body.id = null;
this.host.send(Operation.createPut(u)
.setCompletion(
(o, e) -> {
if (e == null) {
testCxtForPut.fail(new IllegalStateException(
"expected failure"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (rsp.message == null || rsp.message.isEmpty()) {
testCxtForPut.fail(new IllegalStateException(
"expected error response message"));
return;
}
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)
|| 0 != Double.compare(Math.PI, rsp.customErrorField)) {
testCxtForPut.fail(new IllegalStateException(
"expected custom error fields"));
return;
}
testCxtForPut.complete();
})
.setBody(body));
}
testCxtForPut.await();
this.host.toggleDebuggingMode(false);
}
private void directOwnerSelection() throws Throwable {
Map<URI, Map<String, Long>> keyToNodeAssignmentsPerNode = new HashMap<>();
List<String> keys = new ArrayList<>();
long c = this.updateCount * this.nodeCount;
// generate N keys once, then ask each node to assign to its peers. Each node should come up
// with the same distribution
for (int i = 0; i < c; i++) {
keys.add(Utils.getNowMicrosUtc() + "");
}
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
keyToNodeAssignmentsPerNode.put(nodeGroup, new HashMap<>());
}
this.host.waitForNodeGroupConvergence(this.nodeCount);
TestContext testContext = this.host.testCreate(c * this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
for (String key : keys) {
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation
.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion(
(o, e) -> {
try {
synchronized (keyToNodeAssignmentsPerNode) {
SelectOwnerResponse rsp = o
.getBody(SelectOwnerResponse.class);
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode
.get(nodeGroup);
Long l = assignmentsPerNode.get(rsp.ownerNodeId);
if (l == null) {
l = 0L;
}
assignmentsPerNode.put(rsp.ownerNodeId, l + 1);
testContext.complete();
}
} catch (Throwable ex) {
testContext.fail(ex);
}
});
this.host.send(post);
}
}
testContext.await();
this.host.logThroughput();
Map<String, Long> countPerNode = null;
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode.get(nodeGroup);
if (countPerNode == null) {
countPerNode = assignmentsPerNode;
}
this.host.log("Node group %s assignments: %s", nodeGroup, assignmentsPerNode);
for (Entry<String, Long> e : assignmentsPerNode.entrySet()) {
// we assume that with random keys, and random node ids, each node will get at least
// one key.
assertTrue(e.getValue() > 0);
Long count = countPerNode.get(e.getKey());
if (count == null) {
continue;
}
if (!count.equals(e.getValue())) {
this.host.logNodeGroupState();
throw new IllegalStateException(
"Node id got assigned the same key different number of times, on one of the nodes");
}
}
}
}
@Test
public void replicationFullQuorumMissingServiceOnPeer() throws Throwable {
// This test verifies the following scenario:
// A new node joins an existing node-group with
// services already created. Synchronization is
// still in-progress and a write request arrives.
// If the quorum is configured to FULL, the write
// request will fail on the new node with not-found
// error, since synchronization hasn't completed.
// The test verifies that when this happens, the
// owner node will try to synchronize on-demand
// and retry the original update reqeust.
// Artificially setting the replica not found timeout to
// a lower-value, to reduce the wait time before owner
// retries
System.setProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS,
Long.toString(TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS)));
this.host = VerificationHost.create(0);
this.host.setPeerSynchronizationEnabled(false);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.start();
// Setup one host and create some example
// services on it.
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(this.host, this.serviceCount, exampleUris, null);
// Add a second host with synchronization disabled,
// Join it to the existing host.
VerificationHost host2 = new VerificationHost();
try {
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--id=" + mainHostId,
"--port=0",
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + this.host.getUri()
};
host2.initialize(args);
host2.setPeerSynchronizationEnabled(false);
host2.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
host2.start();
this.host.addPeerNode(host2);
// Wait for node-group to converge
List<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.buildUri(this.host, ServiceUriPaths.DEFAULT_NODE_GROUP));
nodeGroupUris.add(UriUtils.buildUri(host2, ServiceUriPaths.DEFAULT_NODE_GROUP));
this.host.waitForNodeGroupConvergence(nodeGroupUris, 2, 2, true);
// Set the quorum to full.
this.host.setNodeGroupQuorum(2, nodeGroupUris.get(0));
host2.setNodeGroupQuorum(2);
// Filter the created examples to only those
// that are owned by host-1.
List<URI> host1Examples = exampleUris.stream()
.filter(e -> this.host.isOwner(e.getPath(), ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.collect(Collectors.toList());
// Start patching all filtered examples. Because
// synchronization is disabled each of these
// example services will not exist on the new
// node that we added resulting in a non_found
// error. However, the owner will retry this
// after on-demand synchronization and hence
// patches should succeed.
ExampleServiceState state = new ExampleServiceState();
state.counter = 1L;
if (host1Examples.size() > 0) {
this.host.log(Level.INFO, "Starting patches");
TestContext ctx = this.host.testCreate(host1Examples.size());
for (URI exampleUri : host1Examples) {
Operation patch = Operation
.createPatch(exampleUri)
.setBody(state)
.setReferer("localhost")
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
ctx.await();
}
} finally {
host2.tearDown();
}
}
@Test
public void replicationWithAuthAndNodeRestart() throws Throwable {
AuthorizationHelper authHelper;
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
authHelper = new AuthorizationHelper(this.host);
// relax quorum to allow for divergent writes, on independent nodes (not yet joined)
this.host.setSystemAuthorizationContext();
// Create the same users and roles on every peer independently
Map<ServiceHost, Collection<String>> roleLinksByHost = new HashMap<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String email = "jane@doe.com";
authHelper.createUserService(h, email);
authHelper.createRoles(h, email);
}
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = getRolesByHost(roleLinksByHost);
// Join nodes to force synchronization and convergence
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> newRoleStateByHost = getRolesByHost(roleLinksByHost);
// Verify that every host independently advances their version & epoch
for (ServiceHost h : roleStateByHost.keySet()) {
Map<URI, RoleState> roleState = roleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState oldRole = roleState.get(u);
RoleState newRole = newRoleStateByHost.get(h).get(u);
assertTrue("version should have advanced",
newRole.documentVersion > oldRole.documentVersion);
assertTrue("epoch should have advanced",
newRole.documentEpoch > oldRole.documentEpoch);
}
}
// Verify that every host converged to the same version, epoch, and owner
Map<String, Long> versions = new HashMap<>();
Map<String, Long> epochs = new HashMap<>();
Map<String, String> owners = new HashMap<>();
for (ServiceHost h : newRoleStateByHost.keySet()) {
Map<URI, RoleState> roleState = newRoleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState newRole = roleState.get(u);
if (versions.containsKey(newRole.documentSelfLink)) {
assertTrue(versions.get(newRole.documentSelfLink) == newRole.documentVersion);
} else {
versions.put(newRole.documentSelfLink, newRole.documentVersion);
}
if (epochs.containsKey(newRole.documentSelfLink)) {
assertTrue(Objects.equals(epochs.get(newRole.documentSelfLink),
newRole.documentEpoch));
} else {
epochs.put(newRole.documentSelfLink, newRole.documentEpoch);
}
if (owners.containsKey(newRole.documentSelfLink)) {
assertEquals(owners.get(newRole.documentSelfLink), newRole.documentOwner);
} else {
owners.put(newRole.documentSelfLink, newRole.documentOwner);
}
}
}
// create some example tasks, which delete example services. We dont have any
// examples services created, which is good, since we just want these tasks to
// go to finished state, then verify, after node restart, they all start
Set<String> exampleTaskLinks = new ConcurrentSkipListSet<>();
createReplicatedExampleTasks(exampleTaskLinks, null);
Set<String> exampleLinks = new ConcurrentSkipListSet<>();
verifyReplicatedAuthorizedPost(exampleLinks);
// verify restart, with authorization.
// stop one host
VerificationHost hostToStop = this.host.getInProcessHostMap().values().iterator().next();
stopAndRestartHost(exampleLinks, exampleTaskLinks, hostToStop);
}
private void createReplicatedExampleTasks(Set<String> exampleTaskLinks, String name)
throws Throwable {
URI factoryUri = UriUtils.buildFactoryUri(this.host.getPeerHost(),
ExampleTaskService.class);
this.host.setSystemAuthorizationContext();
// Sample body that this user is authorized to create
ExampleTaskServiceState exampleServiceState = new ExampleTaskServiceState();
if (name != null) {
exampleServiceState.customQueryClause = Query.Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, name).build();
}
this.host.log("creating example *task* instances");
TestContext testContext = this.host.testCreate(this.serviceCount);
for (int i = 0; i < this.serviceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
ExampleTaskServiceState rsp = o.getBody(ExampleTaskServiceState.class);
synchronized (exampleTaskLinks) {
exampleTaskLinks.add(rsp.documentSelfLink);
}
testContext.complete();
};
this.host.send(Operation
.createPost(factoryUri)
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
// ensure all tasks are in finished state
this.host.waitFor("Example tasks did not finish", () -> {
ServiceDocumentQueryResult rsp = this.host.getExpandedFactoryState(factoryUri);
for (Object o : rsp.documents.values()) {
ExampleTaskServiceState doc = Utils.fromJson(o, ExampleTaskServiceState.class);
if (TaskState.isFailed(doc.taskInfo)) {
this.host.log("task %s failed: %s", doc.documentSelfLink, doc.failureMessage);
throw new IllegalStateException("task failed");
}
if (!TaskState.isFinished(doc.taskInfo)) {
return false;
}
}
return true;
});
}
private void verifyReplicatedAuthorizedPost(Set<String> exampleLinks)
throws Throwable {
Collection<VerificationHost> hosts = this.host.getInProcessHostMap().values();
RoundRobinIterator<VerificationHost> it = new RoundRobinIterator<>(hosts);
int exampleServiceCount = this.serviceCount;
String userLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "jane@doe.com");
// Verify we can assert identity and make a request to every host
this.host.assumeIdentity(userLink);
// Sample body that this user is authorized to create
ExampleServiceState exampleServiceState = new ExampleServiceState();
exampleServiceState.name = "jane";
this.host.log("creating example instances");
TestContext testContext = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
try {
// Verify the user is set as principal
ExampleServiceState state = o.getBody(ExampleServiceState.class);
assertEquals(state.documentAuthPrincipalLink,
userLink);
exampleLinks.add(state.documentSelfLink);
testContext.complete();
} catch (Throwable e2) {
testContext.fail(e2);
}
};
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
this.host.toggleNegativeTestMode(true);
// Sample body that this user is NOT authorized to create
ExampleServiceState invalidExampleServiceState = new ExampleServiceState();
invalidExampleServiceState.name = "somebody other than jane";
this.host.log("issuing non authorized request");
TestContext testCtx = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(invalidExampleServiceState)
.setCompletion((o, e) -> {
if (e != null) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, o.getStatusCode());
testCtx.complete();
return;
}
testCtx.fail(new IllegalStateException("expected failure"));
}));
}
testCtx.await();
this.host.toggleNegativeTestMode(false);
}
private void stopAndRestartHost(Set<String> exampleLinks, Set<String> exampleTaskLinks,
VerificationHost hostToStop)
throws Throwable, InterruptedException {
// relax quorum
this.host.setNodeGroupQuorum(this.nodeCount - 1);
// expire node that went away quickly to avoid alot of log spam from gossip failures
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(1);
this.host.setNodeGroupConfig(cfg);
this.host.stopHostAndPreserveState(hostToStop);
this.host.waitForNodeGroupConvergence(2, 2);
VerificationHost existingHost = this.host.getInProcessHostMap().values().iterator().next();
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleTaskService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// create some additional tasks on the remaining two hosts, but make sure they don't delete
// any example service instances, by specifying a name value we know will not match anything
createReplicatedExampleTasks(exampleTaskLinks, UUID.randomUUID().toString());
// delete some of the task links, to test synchronization of deleted entries on the restarted
// host
Set<String> deletedExampleLinks = deleteSomeServices(exampleLinks);
// increase quorum on existing nodes, so they wait for new node
this.host.setNodeGroupQuorum(this.nodeCount);
hostToStop.setPort(0);
hostToStop.setSecurePort(0);
if (!VerificationHost.restartStatefulHost(hostToStop)) {
this.host.log("Failed restart of host, aborting");
return;
}
// restart host, rejoin it
URI nodeGroupU = UriUtils.buildUri(hostToStop, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI eNodeGroupU = UriUtils.buildUri(existingHost, ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.setSystemAuthorizationContext();
this.host.joinNodeGroup(nodeGroupU, eNodeGroupU, this.nodeCount);
this.host.testWait();
this.host.addPeerNode(hostToStop);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// set quorum on new node as well
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.resetAuthorizationContext();
this.host.waitFor("Task services not started in restarted host:" + exampleTaskLinks, () -> {
return checkChildServicesIfStarted(exampleTaskLinks, hostToStop) == 0;
});
// verify all services, not previously deleted, are restarted
this.host.waitFor("Services not started in restarted host:" + exampleLinks, () -> {
return checkChildServicesIfStarted(exampleLinks, hostToStop) == 0;
});
int deletedCount = deletedExampleLinks.size();
this.host.waitFor("Deleted services still present in restarted host", () -> {
return checkChildServicesIfStarted(deletedExampleLinks, hostToStop) == deletedCount;
});
}
private Set<String> deleteSomeServices(Set<String> exampleLinks)
throws Throwable {
int deleteCount = exampleLinks.size() / 3;
Iterator<String> itLinks = exampleLinks.iterator();
Set<String> deletedExampleLinks = new HashSet<>();
TestContext testContext = this.host.testCreate(deleteCount);
for (int i = 0; i < deleteCount; i++) {
String link = itLinks.next();
deletedExampleLinks.add(link);
exampleLinks.remove(link);
Operation delete = Operation.createDelete(this.host.getPeerServiceUri(link))
.setCompletion(testContext.getCompletion());
this.host.send(delete);
}
testContext.await();
this.host.log("Deleted links: %s", deletedExampleLinks);
return deletedExampleLinks;
}
private int checkChildServicesIfStarted(Set<String> exampleTaskLinks,
VerificationHost host) {
this.host.setSystemAuthorizationContext();
int notStartedCount = 0;
for (String s : exampleTaskLinks) {
ProcessingStage st = host.getServiceStage(s);
if (st == null) {
notStartedCount++;
}
}
this.host.resetAuthorizationContext();
if (notStartedCount > 0) {
this.host.log("%d services not started on %s (%s)", notStartedCount,
host.getPublicUri(), host.getId());
}
return notStartedCount;
}
private Map<ServiceHost, Map<URI, RoleState>> getRolesByHost(
Map<ServiceHost, Collection<String>> roleLinksByHost) throws Throwable {
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = new HashMap<>();
for (ServiceHost h : roleLinksByHost.keySet()) {
Collection<String> roleLinks = roleLinksByHost.get(h);
Collection<URI> roleURIs = new ArrayList<>();
for (String link : roleLinks) {
roleURIs.add(UriUtils.buildUri(h, link));
}
Map<URI, RoleState> serviceState = this.host.getServiceState(null, RoleState.class,
roleURIs);
roleStateByHost.put(h, serviceState);
}
return roleStateByHost;
}
private void verifyOperationJoinAcrossPeers(Map<URI, ReplicationTestServiceState> childStates)
throws Throwable {
// do a OperationJoin across N nodes, making sure join works when forwarding is involved
List<Operation> joinedOps = new ArrayList<>();
for (ReplicationTestServiceState st : childStates.values()) {
Operation get = Operation.createGet(
this.host.getPeerServiceUri(st.documentSelfLink)).setReferer(
this.host.getReferer());
joinedOps.add(get);
}
TestContext testContext = this.host.testCreate(1);
OperationJoin
.create(joinedOps)
.setCompletion(
(ops, exc) -> {
if (exc != null) {
testContext.fail(exc.values().iterator().next());
return;
}
for (Operation o : ops.values()) {
ReplicationTestServiceState state = o.getBody(
ReplicationTestServiceState.class);
if (state.stringField == null) {
testContext.fail(new IllegalStateException());
return;
}
}
testContext.complete();
})
.sendWith(this.host.getPeerHost());
testContext.await();
}
public Map<String, Set<String>> computeOwnerIdsPerLink(VerificationHost joinedHost,
Collection<String> links)
throws Throwable {
TestContext testContext = this.host.testCreate(links.size());
Map<String, Set<String>> expectedOwnersPerLink = new ConcurrentSkipListMap<>();
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
Set<String> eligibleNodeIds = new HashSet<>();
for (NodeState ns : rsp.selectedNodes) {
eligibleNodeIds.add(ns.id);
}
expectedOwnersPerLink.put(rsp.key, eligibleNodeIds);
testContext.complete();
};
for (String link : links) {
Operation selectOp = Operation.createGet(null)
.setCompletion(c)
.setExpiration(this.host.getOperationTimeoutMicros() + Utils.getNowMicrosUtc());
joinedHost.selectOwner(this.replicationNodeSelector, link, selectOp);
}
testContext.await();
return expectedOwnersPerLink;
}
public <T extends ServiceDocument> void verifyDocumentOwnerAndEpoch(Map<String, T> childStates,
VerificationHost joinedHost,
List<URI> joinedHostUris,
int minExpectedEpochRetries,
int maxExpectedEpochRetries, int expectedOwnerChanges)
throws Throwable, InterruptedException, TimeoutException {
Map<URI, NodeGroupState> joinedHostNodeGroupStates = this.host.getServiceState(null,
NodeGroupState.class, joinedHostUris);
Set<String> joinedHostOwnerIds = new HashSet<>();
for (NodeGroupState st : joinedHostNodeGroupStates.values()) {
joinedHostOwnerIds.add(st.documentOwner);
}
this.host.waitFor("ownership did not converge", () -> {
Map<String, Set<String>> ownerIdsPerLink = computeOwnerIdsPerLink(joinedHost,
childStates.keySet());
boolean isConverged = true;
Map<String, Set<Long>> epochsPerLink = new HashMap<>();
List<URI> nodeSelectorStatsUris = new ArrayList<>();
for (URI baseNodeUri : joinedHostUris) {
nodeSelectorStatsUris.add(UriUtils.buildUri(baseNodeUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
URI factoryUri = UriUtils.buildUri(
baseNodeUri, this.replicationTargetFactoryLink);
ServiceDocumentQueryResult factoryRsp = this.host
.getFactoryState(factoryUri);
if (factoryRsp.documentLinks == null
|| factoryRsp.documentLinks.size() != childStates.size()) {
isConverged = false;
// services not all started in new nodes yet;
this.host.log("Node %s does not have all services: %s", baseNodeUri,
Utils.toJsonHtml(factoryRsp));
break;
}
List<URI> childUris = new ArrayList<>();
for (String link : childStates.keySet()) {
childUris.add(UriUtils.buildUri(baseNodeUri, link));
}
// retrieve the document state directly from each service
Map<URI, ServiceDocument> childDocs = this.host.getServiceState(null,
ServiceDocument.class, childUris);
List<URI> childStatUris = new ArrayList<>();
for (ServiceDocument state : childDocs.values()) {
if (state.documentOwner == null) {
this.host.log("Owner not set in service on new node: %s",
Utils.toJsonHtml(state));
isConverged = false;
break;
}
URI statUri = UriUtils.buildUri(baseNodeUri, state.documentSelfLink,
ServiceHost.SERVICE_URI_SUFFIX_STATS);
childStatUris.add(statUri);
Set<Long> epochs = epochsPerLink.get(state.documentEpoch);
if (epochs == null) {
epochs = new HashSet<>();
epochsPerLink.put(state.documentSelfLink, epochs);
}
epochs.add(state.documentEpoch);
Set<String> eligibleNodeIds = ownerIdsPerLink.get(state.documentSelfLink);
if (!joinedHostOwnerIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not expected: %s, valid ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
if (eligibleNodeIds != null && !eligibleNodeIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not eligible: %s, eligible ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
}
int nodeGroupMaintCount = 0;
int docOwnerToggleOffCount = 0;
int docOwnerToggleCount = 0;
// verify stats were reported by owner node, not a random peer
Map<URI, ServiceStats> allChildStats = this.host.getServiceState(null,
ServiceStats.class, childStatUris);
for (ServiceStats childStats : allChildStats.values()) {
String parentLink = UriUtils.getParentPath(childStats.documentSelfLink);
Set<String> eligibleNodes = ownerIdsPerLink.get(parentLink);
if (!eligibleNodes.contains(childStats.documentOwner)) {
this.host.log("Stats for %s owner not expected. Is %s, should be %s",
parentLink, childStats.documentOwner,
ownerIdsPerLink.get(parentLink));
isConverged = false;
break;
}
ServiceStat maintStat = childStats.entries
.get(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (maintStat != null) {
nodeGroupMaintCount++;
}
ServiceStat docOwnerToggleOffStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
if (docOwnerToggleOffStat != null) {
docOwnerToggleOffCount++;
}
ServiceStat docOwnerToggleStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
if (docOwnerToggleStat != null) {
docOwnerToggleCount++;
}
}
this.host.log("Node group change maintenance observed: %d", nodeGroupMaintCount);
if (nodeGroupMaintCount < expectedOwnerChanges) {
isConverged = false;
}
this.host.log("Toggled off doc owner count: %d, toggle on count: %d",
docOwnerToggleOffCount, docOwnerToggleCount);
if (docOwnerToggleCount < childStates.size()) {
isConverged = false;
}
// verify epochs
for (Set<Long> epochs : epochsPerLink.values()) {
if (epochs.size() > 1) {
this.host.log("Documents have different epochs:%s", epochs.toString());
isConverged = false;
}
}
if (!isConverged) {
break;
}
}
return isConverged;
});
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild) throws Throwable {
return doStateUpdateReplicationTest(action, childCount, updateCount, expectedVersion,
updateBodySetter, convergenceChecker, initialStatesPerChild, null, null);
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild,
Map<Action, Long> countsPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
int testCount = childCount * updateCount;
String testName = "Replication with " + action;
TestContext testContext = this.host.testCreate(testCount);
testContext.setTestName(testName).logBefore();
if (!this.expectFailure) {
// Before we do the replication test, wait for factory availability.
for (URI fu : this.host.getNodeGroupToFactoryMap(this.replicationTargetFactoryLink)
.values()) {
// confirm that /factory/available returns 200 across all nodes
waitForReplicatedFactoryServiceAvailable(fu, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
}
long before = Utils.getNowMicrosUtc();
AtomicInteger failedCount = new AtomicInteger();
// issue an update to each child service and verify it was reflected
// among
// peers
for (T initState : initialStatesPerChild.values()) {
// change a field in the initial state of each service but keep it
// the same across all updates so potential re ordering of the
// updates does not cause spurious test breaks
updateBodySetter.apply(initState);
for (int i = 0; i < updateCount; i++) {
long sentTime = 0;
if (this.expectFailure) {
sentTime = Utils.getNowMicrosUtc();
}
URI factoryOnRandomPeerUri = this.host
.getPeerServiceUri(this.replicationTargetFactoryLink);
long finalSentTime = sentTime;
this.host
.send(Operation
.createPatch(UriUtils.buildUri(factoryOnRandomPeerUri,
initState.documentSelfLink))
.setAction(action)
.forceRemote()
.setBodyNoCloning(initState)
.setCompletion(
(o, e) -> {
if (e != null) {
if (this.expectFailure) {
failedCount.incrementAndGet();
testContext.complete();
return;
}
testContext.fail(e);
return;
}
if (this.expectFailure
&& this.expectedFailureStartTimeMicros > 0
&& finalSentTime > this.expectedFailureStartTimeMicros) {
testContext.fail(new IllegalStateException(
"Request should have failed: %s"
+ o.toString()
+ " sent at " + finalSentTime));
return;
}
testContext.complete();
}));
}
}
testContext.await();
testContext.logAfter();
updatePerfDataPerAction(action, before, (long) (childCount * updateCount), countsPerAction,
elapsedTimePerAction);
if (this.expectFailure) {
this.host.log("Failed count: %d", failedCount.get());
if (failedCount.get() == 0) {
throw new IllegalStateException(
"Possible false negative but expected at least one failure");
}
return initialStatesPerChild;
}
// All updates sent to all children within one host, now wait for
// convergence
if (action != Action.DELETE) {
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
childCount,
expectedVersion);
}
// for DELETE replication, we expect the child services to be stopped
// across hosts and their state marked "deleted". So confirm no children
// are available
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
0,
expectedVersion);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction)
throws Throwable {
return doExampleFactoryPostReplicationTest(childCount, null,
countPerAction, elapsedTimePerAction);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
EnumSet<TestProperty> props,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
this.host.toggleNegativeTestMode(true);
}
String factoryPath = this.replicationTargetFactoryLink;
Map<String, ExampleServiceState> serviceStates = new HashMap<>();
long before = Utils.getNowMicrosUtc();
TestContext testContext = this.host.testCreate(childCount);
testContext.setTestName("POST replication");
testContext.logBefore();
for (int i = 0; i < childCount; i++) {
URI factoryOnRandomPeerUri = this.host.getPeerServiceUri(factoryPath);
Operation post = Operation
.createPost(factoryOnRandomPeerUri)
.setCompletion(testContext.getCompletion());
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = "" + post.getId();
initialState.counter = Long.MIN_VALUE;
// set the self link as a hint so the child service URI is
// predefined instead of random
initialState.documentSelfLink = "" + post.getId();
// factory service is started on all hosts. Now issue a POST to one,
// to create a child service with some initial state.
post.setReferer(this.host.getReferer());
this.host.sendRequest(post.setBody(initialState));
// initial state is cloned and sent, now we can change self link per
// child to reflect its runtime URI, which will
// contain the factory service path
initialState.documentSelfLink = UriUtils.buildUriPath(factoryPath,
initialState.documentSelfLink);
serviceStates.put(initialState.documentSelfLink, initialState);
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
// do not wait for convergence of the child services. Instead
// proceed to the next test which is probably stopping hosts
// abruptly
return serviceStates;
}
testContext.await();
updatePerfDataPerAction(Action.POST, before, (long) this.serviceCount, countPerAction,
elapsedTimePerAction);
testContext.logAfter();
return waitForReplicatedFactoryChildServiceConvergence(serviceStates,
this.exampleStateConvergenceChecker,
childCount,
0L);
}
private void updateExampleServiceOptions(
Map<String, ExampleServiceState> statesPerSelfLink) throws Throwable {
if (this.postCreationServiceOptions == null || this.postCreationServiceOptions.isEmpty()) {
return;
}
TestContext testContext = this.host.testCreate(statesPerSelfLink.size());
URI nodeGroup = this.host.getNodeGroupMap().values().iterator().next();
for (String link : statesPerSelfLink.keySet()) {
URI bUri = UriUtils.buildBroadcastRequestUri(
UriUtils.buildUri(nodeGroup, link, ServiceHost.SERVICE_URI_SUFFIX_CONFIG),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
ServiceConfigUpdateRequest cfgBody = ServiceConfigUpdateRequest.create();
cfgBody.addOptions = this.postCreationServiceOptions;
this.host.send(Operation.createPatch(bUri)
.setBody(cfgBody)
.setCompletion(testContext.getCompletion()));
}
testContext.await();
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
return waitForReplicatedFactoryChildServiceConvergence(
getFactoriesPerNodeGroup(this.replicationTargetFactoryLink),
serviceStates,
stateChecker,
expectedChildCount,
expectedVersion);
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<URI, URI> factories,
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
// now poll all hosts until they converge: They all have a child service
// with the expected URI and it has the same state
Map<String, T> updatedStatesPerSelfLink = new HashMap<>();
Date expiration = new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(this.host.getTimeoutSeconds()));
do {
URI node = factories.keySet().iterator().next();
AtomicInteger getFailureCount = new AtomicInteger();
if (expectedChildCount != 0) {
// issue direct GETs to the services, we do not trust the factory
for (String link : serviceStates.keySet()) {
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(node, link))
.setReferer(this.host.getReferer())
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(5))
.setCompletion(
(o, e) -> {
if (e != null) {
getFailureCount.incrementAndGet();
}
ctx.completeIteration();
});
this.host.sendRequest(get);
this.host.testWait(ctx);
}
}
if (getFailureCount.get() > 0) {
this.host.log("Child services not propagated yet. Failure count: %d",
getFailureCount.get());
Thread.sleep(500);
continue;
}
TestContext testContext = this.host.testCreate(factories.size());
Map<URI, ServiceDocumentQueryResult> childServicesPerNode = new HashMap<>();
for (URI remoteFactory : factories.values()) {
URI factoryUriWithExpand = UriUtils.buildExpandLinksQueryUri(remoteFactory);
Operation get = Operation.createGet(factoryUriWithExpand)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.complete();
return;
}
if (!o.hasBody()) {
testContext.complete();
return;
}
ServiceDocumentQueryResult r = o
.getBody(ServiceDocumentQueryResult.class);
synchronized (childServicesPerNode) {
childServicesPerNode.put(o.getUri(), r);
}
testContext.complete();
});
this.host.send(get);
}
testContext.await();
long expectedNodeCountPerLinkMax = factories.size();
long expectedNodeCountPerLinkMin = expectedNodeCountPerLinkMax;
if (this.replicationFactor != 0) {
// We expect services to end up either on K nodes, or K + 1 nodes,
// if limited replication is enabled. The reason we might end up with services on
// an additional node, is because we elect an owner to synchronize an entire factory,
// using the factory's link, and that might end up on a node not used for any child.
// This will produce children on that node, giving us K+1 replication, which is acceptable
// given K (replication factor) << N (total nodes in group)
expectedNodeCountPerLinkMax = this.replicationFactor + 1;
expectedNodeCountPerLinkMin = this.replicationFactor;
}
if (expectedChildCount == 0) {
expectedNodeCountPerLinkMax = 0;
expectedNodeCountPerLinkMin = 0;
}
// build a service link to node map so we can tell on which node each service instance landed
Map<String, Set<URI>> linkToNodeMap = new HashMap<>();
boolean isConverged = true;
for (Entry<URI, ServiceDocumentQueryResult> entry : childServicesPerNode.entrySet()) {
for (String link : entry.getValue().documentLinks) {
if (!serviceStates.containsKey(link)) {
this.host.log("service %s not expected, node: %s", link, entry.getKey());
isConverged = false;
continue;
}
Set<URI> hostsPerLink = linkToNodeMap.get(link);
if (hostsPerLink == null) {
hostsPerLink = new HashSet<>();
}
hostsPerLink.add(entry.getKey());
linkToNodeMap.put(link, hostsPerLink);
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
// each link must exist on N hosts, where N is either the replication factor, or, if not used, all nodes
for (Entry<String, Set<URI>> e : linkToNodeMap.entrySet()) {
if (e.getValue() == null && this.replicationFactor == 0) {
this.host.log("Service %s not found on any nodes", e.getKey());
isConverged = false;
continue;
}
if (e.getValue().size() < expectedNodeCountPerLinkMin
|| e.getValue().size() > expectedNodeCountPerLinkMax) {
this.host.log("Service %s found on %d nodes, expected %d -> %d", e.getKey(), e
.getValue().size(), expectedNodeCountPerLinkMin,
expectedNodeCountPerLinkMax);
isConverged = false;
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
if (expectedChildCount == 0) {
// DELETE test, all children removed from all hosts, we are done
return updatedStatesPerSelfLink;
}
// verify /available reports correct results on the factory.
URI factoryUri = factories.values().iterator().next();
Class<?> stateType = serviceStates.values().iterator().next().getClass();
waitForReplicatedFactoryServiceAvailable(factoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// we have the correct number of services on all hosts. Now verify
// the state of each service matches what we expect
isConverged = true;
for (Entry<String, Set<URI>> entry : linkToNodeMap.entrySet()) {
String selfLink = entry.getKey();
int convergedNodeCount = 0;
for (URI nodeUri : entry.getValue()) {
ServiceDocumentQueryResult childLinksAndDocsPerHost = childServicesPerNode
.get(nodeUri);
Object jsonState = childLinksAndDocsPerHost.documents.get(selfLink);
if (jsonState == null && this.replicationFactor == 0) {
this.host
.log("Service %s not present on host %s", selfLink, entry.getKey());
continue;
}
if (jsonState == null) {
continue;
}
T initialState = serviceStates.get(selfLink);
if (initialState == null) {
continue;
}
@SuppressWarnings("unchecked")
T stateOnNode = (T) Utils.fromJson(jsonState, stateType);
if (!stateChecker.test(initialState, stateOnNode)) {
this.host
.log("State for %s not converged on node %s. Current state: %s, Initial: %s",
selfLink, nodeUri, Utils.toJsonHtml(stateOnNode),
Utils.toJsonHtml(initialState));
break;
}
if (stateOnNode.documentVersion < expectedVersion) {
this.host
.log("Version (%d, expected %d) not converged, state: %s",
stateOnNode.documentVersion,
expectedVersion,
Utils.toJsonHtml(stateOnNode));
break;
}
if (stateOnNode.documentEpoch == null) {
this.host.log("Epoch is missing, state: %s",
Utils.toJsonHtml(stateOnNode));
break;
}
// Do not check exampleState.counter, in this validation loop.
// We can not compare the counter since the replication test sends the updates
// in parallel, meaning some of them will get re-ordered and ignored due to
// version being out of date.
updatedStatesPerSelfLink.put(selfLink, stateOnNode);
convergedNodeCount++;
}
if (convergedNodeCount < expectedNodeCountPerLinkMin
|| convergedNodeCount > expectedNodeCountPerLinkMax) {
isConverged = false;
break;
}
}
if (isConverged) {
return updatedStatesPerSelfLink;
}
Thread.sleep(500);
} while (new Date().before(expiration));
throw new TimeoutException();
}
private List<ServiceHostState> stopHostsToSimulateFailure(int failedNodeCount) {
int k = 0;
List<ServiceHostState> stoppedHosts = new ArrayList<>();
for (VerificationHost hostToStop : this.host.getInProcessHostMap().values()) {
this.host.log("Stopping host %s", hostToStop);
stoppedHosts.add(hostToStop.getState());
this.host.stopHost(hostToStop);
k++;
if (k >= failedNodeCount) {
break;
}
}
return stoppedHosts;
}
public static class StopVerificationTestService extends StatefulService {
public Collection<URI> serviceTargets;
public AtomicInteger outboundRequestCompletion = new AtomicInteger();
public AtomicInteger outboundRequestFailureCompletion = new AtomicInteger();
public StopVerificationTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation deleteForStop) {
// send requests to replicated services, during stop to verify that the
// runtime prevents any outbound requests from making it out
for (URI uri : this.serviceTargets) {
ReplicationTestServiceState body = new ReplicationTestServiceState();
body.stringField = ReplicationTestServiceState.CLIENT_PATCH_HINT;
for (int i = 0; i < 10; i++) {
// send patch to self, so the select owner logic gets invoked and in theory
// queues or cancels the request
Operation op = Operation.createPatch(this, uri.getPath()).setBody(body)
.setTargetReplicated(true)
.setCompletion((o, e) -> {
if (e != null) {
this.outboundRequestFailureCompletion.incrementAndGet();
} else {
this.outboundRequestCompletion.incrementAndGet();
}
});
sendRequest(op);
}
}
}
}
private void stopHostsAndVerifyQueuing(Collection<VerificationHost> hostsToStop,
VerificationHost remainingHost,
Collection<URI> serviceTargets) throws Throwable {
this.host.log("Starting to stop hosts and verify queuing");
// reduce node expiration for unavailable hosts so gossip warning
// messages do not flood the logs
this.nodeGroupConfig.nodeRemovalDelayMicros = remainingHost.getMaintenanceIntervalMicros();
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(10));
// relax quorum to single remaining host
this.host.setNodeGroupQuorum(1);
// start a special test service that will attempt to send messages when it sees
// handleStop(). This is not expected of production code, since service authors
// should never have to worry about handleStop(). We rely on the fact that handleStop
// will be called due to node shutdown, and issue requests to replicated targets,
// then check if anyone of them actually made it out (they should not have)
List<StopVerificationTestService> verificationServices = new ArrayList<>();
// Do the inverse test. Remove all of the original hosts and this time, expect all the
// documents have owners assigned to the new hosts
for (VerificationHost h : hostsToStop) {
StopVerificationTestService s = new StopVerificationTestService();
verificationServices.add(s);
s.serviceTargets = serviceTargets;
h.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.stopHost(h);
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
for (StopVerificationTestService s : verificationServices) {
if (s.outboundRequestCompletion.get() > 0) {
throw new IllegalStateException("Replicated request succeeded");
}
if (s.outboundRequestFailureCompletion.get() < serviceTargets.size()) {
// We expect at least one failure per service target, if we have less
// keep polling.
this.host.log(
"Not converged yet: service %s on host %s has %d outbound request failures, which is lower than %d",
s.getSelfLink(), s.getHost().getId(),
s.outboundRequestFailureCompletion.get(), serviceTargets.size());
isConverged = false;
break;
}
}
if (isConverged) {
this.host.log("Done with stop hosts and verify queuing");
return;
}
Thread.sleep(250);
}
throw new TimeoutException();
}
private void waitForReplicatedFactoryServiceAvailable(URI uri, String nodeSelectorPath)
throws Throwable {
if (this.skipAvailabilityChecks) {
return;
}
if (UriUtils.isHostEqual(this.host, uri)) {
VerificationHost host = this.host;
// if uri is for in-process peers, then use the one
URI peerUri = UriUtils.buildUri(uri.toString().replace(uri.getPath(), ""));
VerificationHost peer = this.host.getInProcessHostMap().get(peerUri);
if (peer != null) {
host = peer;
}
TestContext ctx = host.testCreate(1);
CompletionHandler ch = (o, e) -> {
if (e != null) {
String msg = "Failed to check replicated factory service availability";
ctx.failIteration(new RuntimeException(msg, e));
return;
}
ctx.completeIteration();
};
host.registerForServiceAvailability(ch, nodeSelectorPath, true, uri.getPath());
ctx.await();
} else {
// for remote host
this.host.waitForReplicatedFactoryServiceAvailable(uri, nodeSelectorPath);
}
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_7
|
crossvul-java_data_bad_3082_4
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_4
|
crossvul-java_data_bad_3077_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_3
|
crossvul-java_data_good_3075_0
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
if (op.hasBody()) {
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (op.getAction()) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceDocument rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_0
|
crossvul-java_data_bad_3077_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_1
|
crossvul-java_data_good_3077_1
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
OperationContext.setAuthorizationContext(null);
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
OperationContext.setAuthorizationContext(null);
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_1
|
crossvul-java_data_bad_3080_6
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_6
|
crossvul-java_data_good_3079_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void testSubscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = new TestContext(1, Duration.ofSeconds(5));
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = new TestContext(1, Duration.ofSeconds(5));
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.host.getMaintenanceIntervalMicros() * 2;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
Map<URI, ServiceSubscriptionState> subStates = this.host.getServiceState(null,
ServiceSubscriptionState.class, subUris);
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged = false;
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged = false;
break;
}
}
}
if (isConverged) {
return true;
}
if (!wait) {
return false;
}
Thread.sleep(250);
}
throw new TimeoutException("Subscriber count did not converge to " + subscriberCount);
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_3
|
crossvul-java_data_good_3077_5
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_5
|
crossvul-java_data_good_3075_3
|
/*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed 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.vmware.xenon.common;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void testSubscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = new TestContext(1, Duration.ofSeconds(5));
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = new TestContext(1, Duration.ofSeconds(5));
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.host.getMaintenanceIntervalMicros() * 2;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
Map<URI, ServiceSubscriptionState> subStates = this.host.getServiceState(null,
ServiceSubscriptionState.class, subUris);
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged = false;
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged = false;
break;
}
}
}
if (isConverged) {
return true;
}
if (!wait) {
return false;
}
Thread.sleep(250);
}
throw new TimeoutException("Subscriber count did not converge to " + subscriberCount);
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
|
./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.